diff --git a/Build/build-functions.psm1 b/Build/build-functions.psm1 index 1f5525757c..dd29014efa 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 24c93d5eca..a162ff9fae 100644 --- a/CodeGen/CodeGen.csproj +++ b/CodeGen/CodeGen.csproj @@ -1,4 +1,4 @@ - + Exe @@ -10,6 +10,7 @@ + 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 63cab0add0..82ccf14824 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,16 +37,10 @@ public string Generate() { Writer.WL(GeneratedFileHeader); Writer.WL(@" -using System; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -65,9 +62,64 @@ namespace UnitsNet Writer.WLIfText(1, GetObsoleteAttributeOrNull(_quantity)); Writer.WL(@$" [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] - public readonly partial struct {_quantity.Name} : - {(_quantity.GenerateArithmetic ? "IArithmeticQuantity" : "IQuantity")}<{_quantity.Name}, {_unitEnumName}>,"); + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] + public readonly partial struct {_quantity.Name} :"); + GenerateInterfaceExtensions(); + + Writer.WL($@" + {{ + /// + /// The numeric value this quantity was constructed with. + /// + [DataMember(Name = ""Value"", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; + + /// + /// The unit this quantity was constructed with. + /// + [DataMember(Name = ""Unit"", Order = 2, EmitDefaultValue = false)] + private readonly {_unitEnumName}? _unit; +"); + GenerateQuantityInfo(); + GenerateStaticConstructor(); + GenerateInstanceConstructors(); + GenerateStaticProperties(); + GenerateProperties(); + GenerateConversionProperties(); + GenerateStaticMethods(); + GenerateStaticFactoryMethods(); + GenerateStaticParseMethods(); + GenerateArithmeticOperators(); + GenerateRelationalOperators(); + GenerateEqualityAndComparison(); + GenerateConversionMethods(); + GenerateToString(); + + Writer.WL($@" + }} +}}"); + return Writer.ToString(); + } + + private void GenerateInterfaceExtensions() + { + // generate the base interface (either IVectorQuantity, IAffineQuantity or ILogarithmicQuantity) + if (_quantity.Logarithmic) + { + Writer.WL(@$" + ILogarithmicQuantity<{_quantity.Name}, {_unitEnumName}>,"); + } + else if (!string.IsNullOrEmpty(_quantity.AffineOffsetType)) + { + Writer.WL(@$" + IAffineQuantity<{_quantity.Name}, {_unitEnumName}, {_quantity.AffineOffsetType}>,"); + } + else // the default quantity type implements the IVectorQuantity interface + { + Writer.WL(@$" + IArithmeticQuantity<{_quantity.Name}, {_unitEnumName}>,"); + } if (_quantity.Relations.Any(r => r.Operator is "*" or "/")) { @@ -90,14 +142,13 @@ namespace UnitsNet 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")}>,"); } } Writer.WL(@$" #endif"); } - Writer.WL(@$" #if NET7_0_OR_GREATER IComparisonOperators<{_quantity.Name}, {_quantity.Name}, bool>, @@ -105,74 +156,89 @@ namespace UnitsNet #endif IComparable, IComparable<{_quantity.Name}>, - IConvertible, IEquatable<{_quantity.Name}>, IFormattable"); - - Writer.WL($@" - {{ - /// - /// The numeric value this quantity was constructed with. - /// - [DataMember(Name = ""Value"", Order = 1)] - private readonly double _value; - - /// - /// The unit this quantity was constructed with. - /// - [DataMember(Name = ""Unit"", Order = 2)] - private readonly {_unitEnumName}? _unit; -"); - GenerateStaticConstructor(); - GenerateInstanceConstructors(); - GenerateStaticProperties(); - GenerateProperties(); - GenerateConversionProperties(); - GenerateStaticMethods(); - GenerateStaticFactoryMethods(); - GenerateStaticParseMethods(); - GenerateArithmeticOperators(); - GenerateRelationalOperators(); - GenerateEqualityAndComparison(); - GenerateConversionMethods(); - GenerateToString(); - GenerateIConvertibleMethods(); - - Writer.WL($@" - }} -}}"); - return Writer.ToString(); } - private void GenerateStaticConstructor() + private void GenerateQuantityInfo() { + var quantityInfoClassName = $"{_quantity.Name}Info"; BaseDimensions baseDimensions = _quantity.BaseDimensions; + var createDimensionsExpression = _isDimensionless + ? "BaseDimensions.Dimensionless" + : $"new BaseDimensions({baseDimensions.L}, {baseDimensions.M}, {baseDimensions.T}, {baseDimensions.I}, {baseDimensions.Θ}, {baseDimensions.N}, {baseDimensions.J})"; + Writer.WL($@" - static {_quantity.Name}() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class {quantityInfoClassName}: QuantityInfo<{_quantity.Name}, {_unitEnumName}> {{"); - Writer.WL(_isDimensionless ? $@" - BaseDimensions = BaseDimensions.Dimensionless;" : $@" - BaseDimensions = new BaseDimensions({baseDimensions.L}, {baseDimensions.M}, {baseDimensions.T}, {baseDimensions.I}, {baseDimensions.Θ}, {baseDimensions.N}, {baseDimensions.J});"); - Writer.WL($@" - BaseUnit = {_unitEnumName}.{_quantity.BaseUnit}; - Units = Enum.GetValues(typeof({_unitEnumName})).Cast<{_unitEnumName}>().ToArray(); - Zero = new {_quantity.Name}(0, BaseUnit); - Info = new QuantityInfo<{_unitEnumName}>(""{_quantity.Name}"", - new UnitInfo<{_unitEnumName}>[] - {{"); + /// + public {quantityInfoClassName}(string name, {_unitEnumName} baseUnit, IEnumerable> unitMappings, {_quantity.Name} zero, BaseDimensions baseDimensions, + QuantityFromDelegate<{_quantity.Name}, {_unitEnumName}> fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + {{ + }} + /// + public {quantityInfoClassName}(string name, {_unitEnumName} baseUnit, IEnumerable> unitMappings, {_quantity.Name} zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, {_quantity.Name}.From, new ResourceManager(""UnitsNet.GeneratedCode.Resources.{_quantity.Name}"", typeof({_quantity.Name}).Assembly)) + {{ + }} + + /// + /// Creates a new instance of the class with the default settings for the {_quantity.Name} quantity. + /// + /// A new instance of the class with the default settings. + public static {quantityInfoClassName} CreateDefault() + {{ + return new {quantityInfoClassName}(nameof({_quantity.Name}), DefaultBaseUnit, GetDefaultMappings(), new {_quantity.Name}(0, DefaultBaseUnit), DefaultBaseDimensions); + }} + + /// + /// Creates a new instance of the class with the default settings for the {_quantity.Name} quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static {quantityInfoClassName} CreateDefault(Func>, IEnumerable>> customizeUnits) + {{ + return new {quantityInfoClassName}(nameof({_quantity.Name}), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new {_quantity.Name}(0, DefaultBaseUnit), DefaultBaseDimensions); + }} + + /// + /// The for is {_quantity.BaseDimensions}. + /// + public static BaseDimensions DefaultBaseDimensions {{ get; }} = {createDimensionsExpression}; + + /// + /// The default base unit of {_quantity.Name} is {_baseUnit.SingularName}. All conversions, as defined in the , go via this value. + /// + public static {_unitEnumName} DefaultBaseUnit {{ get; }} = {_unitEnumName}.{_baseUnit.SingularName}; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for {_quantity.Name}. + public static IEnumerable> GetDefaultMappings() + {{"); + foreach (Unit unit in _quantity.Units) { BaseUnits? baseUnits = unit.BaseUnits; + string baseUnitsFormat; if (baseUnits == null) { - Writer.WL($@" - new UnitInfo<{_unitEnumName}>({_unitEnumName}.{unit.SingularName}, ""{unit.PluralName}"", BaseUnits.Undefined, ""{_quantity.Name}""),"); + baseUnitsFormat = "BaseUnits.Undefined"; } else { - var baseUnitsCtorArgs = string.Join(", ", + baseUnitsFormat = $"new BaseUnits({string.Join(", ", new[] { baseUnits.L != null ? $"length: LengthUnit.{baseUnits.L}" : null, @@ -182,19 +248,49 @@ private void GenerateStaticConstructor() baseUnits.Θ != null ? $"temperature: TemperatureUnit.{baseUnits.Θ}" : null, baseUnits.N != null ? $"amount: AmountOfSubstanceUnit.{baseUnits.N}" : null, baseUnits.J != null ? $"luminousIntensity: LuminousIntensityUnit.{baseUnits.J}" : null - }.Where(str => str != null)); + }.Where(str => str != null))})"; + } + if (unit.SingularName == _quantity.BaseUnit) + { Writer.WL($@" - new UnitInfo<{_unitEnumName}>({_unitEnumName}.{unit.SingularName}, ""{unit.PluralName}"", new BaseUnits({baseUnitsCtorArgs}), ""{_quantity.Name}""),"); + 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($@" - }}, - BaseUnit, Zero, BaseDimensions); + }} + }} +"); + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + private void GenerateStaticConstructor() + { + Writer.WL($@" + static {_quantity.Name}() + {{"); + Writer.WL($@" + Info = UnitsNetSetup.CreateQuantityInfo({_quantity.Name}Info.CreateDefault); }} "); } @@ -207,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;"); @@ -226,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); @@ -243,37 +339,38 @@ 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<{_unitEnumName}> Info {{ get; }} + public static QuantityInfo<{_quantity.Name}, {_unitEnumName}> Info {{ get; }} /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions {{ get; }} + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of {_quantity.Name}, which is {_quantity.BaseUnit}. All conversions go via this value. /// - public static {_unitEnumName} BaseUnit {{ get; }} + public static {_unitEnumName} BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the {_quantity.Name} quantity. /// - public static {_unitEnumName}[] Units {{ get; }} + public static IReadOnlyCollection<{_unitEnumName}> Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit {_quantity.BaseUnit}. /// - public static {_quantity.Name} Zero {{ get; }} + public static {_quantity.Name} Zero => Info.Zero; "); - - if (_quantity.GenerateArithmetic) + + if (_quantity.Logarithmic) { Writer.WL($@" - /// - public static {_quantity.Name} AdditiveIdentity => Zero; + /// + public static QuantityValue LogarithmicScalingFactor {{get;}} = {10 * _quantity.LogarithmicScalingFactor}; "); } @@ -287,30 +384,51 @@ private void GenerateProperties() Writer.WL($@" #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public {_unitEnumName} Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo<{_unitEnumName}> QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo<{_quantity.Name}, {_unitEnumName}> QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => {_quantity.Name}.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo<{_unitEnumName}> IQuantity<{_unitEnumName}>.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo<{_quantity.Name}> IQuantityInstance<{_quantity.Name}>.QuantityInfo => Info; +#endif +"); + if (_quantity.Logarithmic) + { + Writer.WL($@" +#if NETSTANDARD2_0 + QuantityValue ILogarithmicQuantity<{_quantity.Name}>.LogarithmicScalingFactor => LogarithmicScalingFactor; +#endif +"); + } + + Writer.WL($@" + #endregion + #endregion "); } @@ -326,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}); "); } @@ -346,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. /// @@ -421,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}); }} @@ -435,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); }} @@ -501,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); }} /// @@ -532,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); }} /// @@ -557,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"")); /// @@ -565,10 +641,10 @@ public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? pro /// Error parsing string. public static {_unitEnumName} ParseUnit(string str, IFormatProvider? provider) {{ - return UnitsNetSetup.Default.UnitParser.Parse<{_unitEnumName}>(str, provider); + 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); @@ -583,10 +659,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse<{_unitEnumName}>(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); }} #endregion @@ -595,7 +671,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? private void GenerateArithmeticOperators() { - if (!_quantity.GenerateArithmetic) return; + if (_quantity.IsAffine) return; // Logarithmic units required different arithmetic if (_quantity.Logarithmic) @@ -616,35 +692,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}; }} @@ -662,53 +738,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 @@ -735,46 +819,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 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") { - expression = $"{relation.ResultQuantity.Name}.From{relation.ResultUnit.PluralName}({expression})"; + resultType = "QuantityValue"; + } + else + { + 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}; + }} +"); + } + } + + 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 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}; }} @@ -796,88 +971,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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current {_quantity.Name}. + public override int GetHashCode() + {{ + return Comparison.GetHashCode(typeof({_quantity.Name}), this.As(BaseUnit)); + }} + + /// /// 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: /// @@ -889,257 +1058,88 @@ public int CompareTo(object? obj) /// public int CompareTo({_quantity.Name} other) {{ - return _value.CompareTo(other.ToUnit(this.Unit).Value); - }} - - /// - /// - /// Compare equality to another {_quantity.Name} within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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."")] - public bool Equals({_quantity.Name} other, double tolerance, ComparisonType comparisonType) - {{ - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), ""Tolerance must be greater than or equal to 0.""); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); + return _value.CompareTo(other.As(this.Unit)); }} - +"); + // TODO see about removing this +#if EXTENDED_EQUALS_INTERFACE + + if (_quantity.IsAffine) + { + Writer.WL($@" /// public bool Equals(IQuantity? other, IQuantity tolerance) {{ - return other is {_quantity.Name} otherTyped - && (tolerance is {_quantity.Name} toleranceTyped - ? true - : throw new ArgumentException($""Tolerance quantity ({{tolerance.QuantityInfo.Name}}) did not match the other quantities of type '{_quantity.Name}'."", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); + #if NET + return this.Equals<{_quantity.Name}, {_quantity.AffineOffsetType}>(other, tolerance); + #else + return AffineQuantityExtensions.Equals(this, other, tolerance); + #endif }} /// - public bool Equals({_quantity.Name} other, {_quantity.Name} tolerance) + public bool Equals({_quantity.Name} other, {_quantity.AffineOffsetType} tolerance) {{ - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); + return this.EqualsAbsolute(other, tolerance); }} - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current {_quantity.Name}. - public override int GetHashCode() - {{ - return new {{ Info.Name, Value, Unit }}.GetHashCode(); - }} - - #endregion "); - } - - private void GenerateConversionMethods() - { - Writer.WL($@" - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As({_unitEnumName} unit) + } + else if (_quantity.Logarithmic) + { + Writer.WL($@" + /// + public bool Equals(IQuantity? other, IQuantity tolerance) {{ - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; + return LogarithmicQuantityExtensions.Equals(this, other, tolerance); }} -"); - Writer.WL( $@" - - /// - public double As(UnitSystem unitSystem) + /// + public bool Equals({_quantity.Name} other, {_quantity.Name} tolerance) {{ - return As(Info.GetDefaultUnit(unitSystem)); + return this.EqualsAbsolute(other, tolerance); }} "); - - 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) + } + else + { + Writer.WL($@" + /// + public bool Equals(IQuantity? other, IQuantity tolerance) {{ - return ToUnit(unit, DefaultConversionFunctions); + return VectorQuantityExtensions.Equals(this, other, tolerance); }} - /// - /// 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) + /// + public bool Equals({_quantity.Name} other, {_quantity.Name} tolerance) {{ - 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 NotImplementedException($""Can not convert {{Unit}} to {{unit}}.""); - }} + return this.EqualsAbsolute(other, tolerance); }} - - /// - /// 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(); +#endif 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)); - }} + #endregion "); + } + private void GenerateConversionMethods() + { Writer.WL($@" - #region Explicit implementations + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - }} + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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); - }} + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity<{_unitEnumName}> IQuantity<{_unitEnumName}>.ToUnit({_unitEnumName} unit) => ToUnit(unit); + IQuantity<{_unitEnumName}> IQuantity<{_unitEnumName}>.ToUnit({_unitEnumName} unit) => this.ToUnit(unit); - /// - IQuantity<{_unitEnumName}> IQuantity<{_unitEnumName}>.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity<{_unitEnumName}> IQuantity<{_unitEnumName}>.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion "); @@ -1159,145 +1159,19 @@ public override string ToString() return ToString(null, null); }} - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - {{ - return ToString(null, provider); - }} - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - {{ - return ToString(format, null); - }} - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) {{ - return QuantityFormatter.Format<{_unitEnumName}>(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); }} #endregion " ); } - private void GenerateIConvertibleMethods() - { - Writer.WL($@" - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - {{ - return TypeCode.Object; - }} - - bool IConvertible.ToBoolean(IFormatProvider? provider) - {{ - throw new InvalidCastException($""Converting {{typeof({_quantity.Name})}} to bool is not supported.""); - }} - - byte IConvertible.ToByte(IFormatProvider? provider) - {{ - return Convert.ToByte(_value); - }} - - char IConvertible.ToChar(IFormatProvider? provider) - {{ - throw new InvalidCastException($""Converting {{typeof({_quantity.Name})}} to char is not supported.""); - }} - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - {{ - throw new InvalidCastException($""Converting {{typeof({_quantity.Name})}} to DateTime is not supported.""); - }} - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - {{ - return Convert.ToDecimal(_value); - }} - - double IConvertible.ToDouble(IFormatProvider? provider) - {{ - return Convert.ToDouble(_value); - }} - - short IConvertible.ToInt16(IFormatProvider? provider) - {{ - return Convert.ToInt16(_value); - }} - - int IConvertible.ToInt32(IFormatProvider? provider) - {{ - return Convert.ToInt32(_value); - }} - - long IConvertible.ToInt64(IFormatProvider? provider) - {{ - return Convert.ToInt64(_value); - }} - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - {{ - return Convert.ToSByte(_value); - }} - - float IConvertible.ToSingle(IFormatProvider? provider) - {{ - return Convert.ToSingle(_value); - }} - - string IConvertible.ToString(IFormatProvider? provider) - {{ - return ToString(null, provider); - }} - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - {{ - if (conversionType == typeof({_quantity.Name})) - return this; - else if (conversionType == typeof({_unitEnumName})) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return {_quantity.Name}.Info; - else if (conversionType == typeof(BaseDimensions)) - return {_quantity.Name}.BaseDimensions; - else - throw new InvalidCastException($""Converting {{typeof({_quantity.Name})}} to {{conversionType}} is not supported.""); - }} - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - {{ - return Convert.ToUInt16(_value); - }} - - uint IConvertible.ToUInt32(IFormatProvider? provider) - {{ - return Convert.ToUInt32(_value); - }} - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - {{ - return Convert.ToUInt64(_value); - }} - - #endregion"); - } - /// private static string? GetObsoleteAttributeOrNull(Quantity quantity) => GetObsoleteAttributeOrNull(quantity.ObsoleteText); diff --git a/CodeGen/Generators/UnitsNetGen/StaticQuantityGenerator.cs b/CodeGen/Generators/UnitsNetGen/StaticQuantityGenerator.cs index 69443fa2d5..1577fd7f5d 100644 --- a/CodeGen/Generators/UnitsNetGen/StaticQuantityGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/StaticQuantityGenerator.cs @@ -1,4 +1,5 @@ -using CodeGen.Helpers; +using System.Collections.Generic; +using System.Linq; using CodeGen.JsonTypes; namespace CodeGen.Generators.UnitsNetGen @@ -16,123 +17,64 @@ public string Generate() { Writer.WL(GeneratedFileHeader); Writer.WL(@" -using System; -using System.Globalization; -using UnitsNet.Units; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; #nullable enable -namespace UnitsNet +namespace UnitsNet; + +/// +/// Dynamically parse or construct quantities when types are only known at runtime. +/// +public partial class Quantity { /// - /// Dynamically parse or construct quantities when types are only known at runtime. + /// Serves as a repository for predefined quantity conversion mappings, facilitating the automatic generation and retrieval of unit conversions in the UnitsNet library. /// - public partial class Quantity + internal static class Provider { /// - /// All QuantityInfo instances mapped by quantity name that are present in UnitsNet by default. + /// All QuantityInfo instances that are present in UnitsNet by default. /// - public static readonly IDictionary ByName = new Dictionary + internal static IReadOnlyList DefaultQuantities => new QuantityInfo[] {"); foreach (var quantity in _quantities) Writer.WL($@" - {{ ""{quantity.Name}"", {quantity.Name}.Info }},"); + {quantity.Name}.Info,"); Writer.WL(@" }; /// - /// Dynamically constructs a quantity of the given with the value in the quantity's base units. + /// All implicit quantity conversions that exist by default. /// - /// The of the quantity to create. - /// The value to construct the quantity with. - /// The created quantity. - public static IQuantity FromQuantityInfo(QuantityInfo quantityInfo, double value) - { - return quantityInfo.Name switch - {"); - foreach (var quantity in _quantities) - { - var quantityName = quantity.Name; + internal static readonly IReadOnlyList DefaultConversions = new QuantityConversionMapping[] + {"); + foreach (var quantityRelation in _quantities.SelectMany(quantity => quantity.Relations.Where(x => x.Operator == "inverse")).Distinct(new CumulativeRelationshipEqualityComparer()).OrderBy(relation => relation.LeftQuantity.Name)) Writer.WL($@" - ""{quantityName}"" => {quantityName}.From(value, {quantityName}.BaseUnit),"); - } - + new (typeof({quantityRelation.LeftQuantity.Name}), typeof({quantityRelation.RightQuantity.Name})),"); Writer.WL(@" - _ => throw new ArgumentException($""{quantityInfo.Name} is not a supported quantity."") - }; + }; + } +}"); + return Writer.ToString(); } + } - /// - /// Try to dynamically construct a quantity. - /// - /// Numeric value. - /// Unit enum value. - /// The resulting quantity if successful, otherwise default. - /// True if successful with assigned the value, otherwise false. - public static bool TryFrom(double value, Enum? unit, [NotNullWhen(true)] out IQuantity? quantity) + internal class CumulativeRelationshipEqualityComparer: IEqualityComparer{ + public bool Equals(QuantityRelation? x, QuantityRelation? y) { - quantity = unit switch - {"); - foreach (var quantity in _quantities) - { - var quantityName = quantity.Name; - var unitTypeName = $"{quantityName}Unit"; - var unitValue = unitTypeName.ToCamelCase(); - Writer.WL($@" - {unitTypeName} {unitValue} => {quantityName}.From(value, {unitValue}),"); - } - - Writer.WL(@" - _ => null - }; - - return quantity is not null; + 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))); } - /// - /// Try to dynamically parse a quantity string representation. - /// - /// The format provider to use for lookup. Defaults to if null. - /// Type of quantity, such as . - /// Quantity string representation, such as ""1.5 kg"". Must be compatible with given quantity type. - /// The resulting quantity if successful, otherwise default. - /// The parsed quantity. - public static bool TryParse(IFormatProvider? formatProvider, Type quantityType, [NotNullWhen(true)] string? quantityString, [NotNullWhen(true)] out IQuantity? quantity) + public int GetHashCode(QuantityRelation obj) { - quantity = default(IQuantity); - - if (!typeof(IQuantity).IsAssignableFrom(quantityType)) - return false; - - var parser = UnitsNetSetup.Default.QuantityParser; - - return quantityType switch - {"); - foreach (var quantity in _quantities) - { - var quantityName = quantity.Name; - Writer.WL($@" - Type _ when quantityType == typeof({quantityName}) => parser.TryParse<{quantityName}, {quantityName}Unit>(quantityString, formatProvider, {quantityName}.From, out quantity),"); - } - - Writer.WL(@" - _ => false - }; - } - - internal static IEnumerable GetQuantityTypes() - {"); - foreach (var quantity in _quantities) - Writer.WL($@" - yield return typeof({quantity.Name});"); - Writer.WL(@" - } - } -}"); - return Writer.ToString(); + return obj.LeftQuantity.GetHashCode() ^ obj.RightQuantity.GetHashCode(); } } } diff --git a/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs b/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs index 625e9a8661..18320577ef 100644 --- a/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using CodeGen.JsonTypes; @@ -58,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 @@ -82,6 +83,16 @@ internal class UnitTestBaseClassGenerator : GeneratorBase /// private readonly Dictionary>> _ambiguousAbbreviationsForCulture; + /// + /// A dictionary that maps culture names to their respective dictionaries of units and their default abbreviations. + /// + /// + /// This field is used to store the default abbreviation for each unit in a specific culture. + /// The outer dictionary key represents the culture name (e.g., "en-US"), while the inner dictionary maps a + /// to its default abbreviation. + /// + private readonly Dictionary> _defaultAbbreviationsForCulture; + /// /// The default or fallback culture for unit localizations. /// @@ -90,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; @@ -107,7 +118,8 @@ public UnitTestBaseClassGenerator(Quantity quantity) _otherOrBaseUnit = quantity.Units.Where(u => u != _baseUnit).DefaultIfEmpty(_baseUnit).First(); _otherOrBaseUnitFullName = $"{_unitEnumName}.{_otherOrBaseUnit.SingularName}"; _isDimensionless = quantity.BaseDimensions is { L: 0, M: 0, T: 0, I: 0, Θ: 0, N: 0, J: 0 }; - + + _defaultAbbreviationsForCulture = new Dictionary>(); var abbreviationsForCulture = new Dictionary>>(); foreach (Unit unit in quantity.Units) { @@ -118,6 +130,11 @@ public UnitTestBaseClassGenerator(Quantity quantity) foreach (Localization localization in unit.Localization) { + if (localization.Abbreviations.Length == 0) + { + continue; + } + if (!abbreviationsForCulture.TryGetValue(localization.Culture, out Dictionary>? localizationsForCulture)) { abbreviationsForCulture[localization.Culture] = localizationsForCulture = new Dictionary>(); @@ -134,6 +151,13 @@ public UnitTestBaseClassGenerator(Quantity quantity) localizationsForCulture[abbreviation] = [unit]; } } + + if (!_defaultAbbreviationsForCulture.TryGetValue(localization.Culture, out Dictionary? defaultLocalizationsForCulture)) + { + _defaultAbbreviationsForCulture[localization.Culture] = defaultLocalizationsForCulture = new Dictionary(); + } + + defaultLocalizationsForCulture.Add(unit, localization.Abbreviations[0]); } } @@ -238,6 +262,7 @@ public abstract partial class {_quantity.Name}TestsBase : QuantityTestsBase Writer.WL($@" new object[] {{ {GetUnitFullName(unit)} }},"); } + Writer.WL($@" }}; @@ -282,7 +307,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() {{ var quantity = new {_quantity.Name}(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); }} [Fact] @@ -299,15 +324,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void {_quantity.Name}_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() {{ + {_unitEnumName}[] unitsOrderedByName = EnumUtils.GetEnumValues<{_unitEnumName}>().OrderBy(x => x.ToString()).ToArray(); var quantity = new {_quantity.Name}(1, {_baseUnitFullName}); - QuantityInfo<{_unitEnumName}> quantityInfo = quantity.QuantityInfo; + QuantityInfo<{_quantity.Name}, {_unitEnumName}> quantityInfo = quantity.QuantityInfo; - Assert.Equal({_quantity.Name}.Zero, quantityInfo.Zero); Assert.Equal(""{_quantity.Name}"", quantityInfo.Name); + Assert.Equal({_quantity.Name}.Zero, quantityInfo.Zero); + Assert.Equal({_quantity.Name}.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal({_quantity.Name}.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues<{_unitEnumName}>().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -329,7 +372,7 @@ public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() var quantityVariable = $"quantity{i++:D2}"; Writer.WL($@" var {quantityVariable} = {_quantity.Name}.From(1, {GetUnitFullName(unit)}); - AssertEx.EqualTolerance(1, {quantityVariable}.{unit.PluralName}, {unit.PluralName}Tolerance); + Assert.Equal(1, {quantityVariable}.{unit.PluralName}); Assert.Equal({GetUnitFullName(unit)}, {quantityVariable}.Unit); "); @@ -547,50 +590,93 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }} "); } - + Writer.WL($@" - - [Fact] - public void Parse() - {{"); - foreach (var unit in _quantity.Units.Where(u => string.IsNullOrEmpty(u.ObsoleteText))) - foreach (var localization in unit.Localization) - foreach (var abbreviation in localization.Abbreviations) + [Theory]"); + foreach ((var cultureName, Dictionary abbreviations) in _uniqueAbbreviationsForCulture) { - Writer.WL($@" - try - {{ - var parsed = {_quantity.Name}.Parse(""1 {abbreviation}"", CultureInfo.GetCultureInfo(""{localization.Culture}"")); - AssertEx.EqualTolerance(1, parsed.{unit.PluralName}, {unit.PluralName}Tolerance); - Assert.Equal({GetUnitFullName(unit)}, parsed.Unit); - }} catch (AmbiguousUnitParseException) {{ /* Some units have the same abbreviations */ }} -"); + var culture = CultureInfo.GetCultureInfo(cultureName); + foreach ((var abbreviation, Unit unit) in abbreviations) + { + Writer.WL($@" + [InlineData(""{cultureName}"", ""{4.2m.ToString(culture)} {abbreviation}"", {GetUnitFullName(unit)}, 4.2)]"); + } } Writer.WL($@" + public void Parse(string culture, string quantityString, {_unitEnumName} expectedUnit, decimal expectedValue) + {{ + using var _ = new CultureScope(culture); + var parsed = {_quantity.Name}.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); }} +"); - [Fact] - public void TryParse() - {{"); - foreach (var unit in _quantity.Units.Where(u => string.IsNullOrEmpty(u.ObsoleteText))) - foreach (var localization in unit.Localization) - foreach (var abbreviation in localization.Abbreviations) + // we only generate these for a few of the quantities + if (_ambiguousAbbreviationsForCulture.Count != 0) { - // Skip units with ambiguous abbreviations, since there is no exception to describe this is why TryParse failed. - if (IsAmbiguousAbbreviation(localization, abbreviation)) continue; - Writer.WL($@" - {{ - Assert.True({_quantity.Name}.TryParse(""1 {abbreviation}"", CultureInfo.GetCultureInfo(""{localization.Culture}""), out var parsed)); - AssertEx.EqualTolerance(1, parsed.{unit.PluralName}, {unit.PluralName}Tolerance); - Assert.Equal({GetUnitFullName(unit)}, parsed.Unit); - }} + [Theory]"); + foreach ((var cultureName, Dictionary>? abbreviations) in _ambiguousAbbreviationsForCulture) + { + foreach (KeyValuePair> ambiguousPair in abbreviations) + { + Writer.WL($@" + [InlineData(""{cultureName}"", ""1 {ambiguousPair.Key}"")] // [{string.Join(", ", ambiguousPair.Value.Select(x => x.SingularName))}] "); + } + } + Writer.WL($@" + public void ParseWithAmbiguousAbbreviation(string culture, string quantityString) + {{ + Assert.Throws(() => {_quantity.Name}.Parse(quantityString, CultureInfo.GetCultureInfo(culture))); + }} "); + } // ambiguousAbbreviations + + + Writer.WL($@" + [Theory]"); + foreach ((var cultureName, Dictionary abbreviations) in _uniqueAbbreviationsForCulture) + { + var culture = CultureInfo.GetCultureInfo(cultureName); + foreach ((var abbreviation, Unit unit) in abbreviations) + { + Writer.WL($@" + [InlineData(""{cultureName}"", ""{4.2m.ToString(culture)} {abbreviation}"", {GetUnitFullName(unit)}, 4.2)]"); + } } Writer.WL($@" + 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)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); }} "); + + // we only generate these for a few of the quantities + if (_ambiguousAbbreviationsForCulture.Count != 0) + { + Writer.WL($@" + [Theory]"); + foreach ((var cultureName, Dictionary>? abbreviations) in _ambiguousAbbreviationsForCulture) + { + foreach (KeyValuePair> ambiguousPair in abbreviations) + { + Writer.WL($@" + [InlineData(""{cultureName}"", ""1 {ambiguousPair.Key}"")] // [{string.Join(", ", ambiguousPair.Value.Select(x => x.SingularName))}] "); + } + } + Writer.WL($@" + public void TryParseWithAmbiguousAbbreviation(string culture, string quantityString) + {{ + Assert.False({_quantity.Name}.TryParse(quantityString, CultureInfo.GetCultureInfo(culture), out _)); + }} +"); + } // ambiguousAbbreviations + Writer.WL($@" [Theory]"); foreach ((var abbreviation, Unit unit) in _uniqueAbbreviationsForCulture[FallbackCultureName]) @@ -775,6 +861,38 @@ public void TryParseUnitWithAmbiguousAbbreviation(string culture, string abbrevi "); } // ambiguousAbbreviations + Writer.WL($@" + [Theory]"); + foreach ((var cultureName, Dictionary abbreviations) in _defaultAbbreviationsForCulture) + { + foreach ((Unit unit, var abbreviation) in abbreviations) + { + Writer.WL($@" + [InlineData(""{cultureName}"", {GetUnitFullName(unit)}, ""{abbreviation}"")]"); + } + } + Writer.WL($@" + public void GetAbbreviationForCulture(string culture, {_unitEnumName} unit, string expectedAbbreviation) + {{ + var defaultAbbreviation = {_quantity.Name}.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }} +"); + Writer.WL($@" + [Fact] + public void GetAbbreviationWithDefaultCulture() + {{ + Assert.All({_quantity.Name}.Units, unit => + {{ + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = {_quantity.Name}.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }}); + }} +"); + Writer.WL($@" [Theory] [MemberData(nameof(UnitTypes))] @@ -806,6 +924,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); }}); }} @@ -829,20 +948,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($@" }} "); @@ -854,13 +975,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(); @@ -868,20 +989,20 @@ public void LogarithmicArithmeticOperators() protected abstract void AssertLogarithmicSubtraction(); "); } - else if (_quantity.GenerateArithmetic) + else if (!_quantity.IsAffine) { Writer.WL($@" [Fact] 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)); }} "); } @@ -934,13 +1055,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); @@ -978,35 +1092,104 @@ public void Equals_Null_ReturnsFalse() }} [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() {{ - var v = {_quantity.Name}.From{_baseUnit.PluralName}(1); - Assert.True(v.Equals({_quantity.Name}.From{_baseUnit.PluralName}(1), {_baseUnit.PluralName}Tolerance, ComparisonType.Relative)); - Assert.False(v.Equals({_quantity.Name}.Zero, {_baseUnit.PluralName}Tolerance, ComparisonType.Relative)); - Assert.True({_quantity.Name}.From{_baseUnit.PluralName}(100).Equals({_quantity.Name}.From{_baseUnit.PluralName}(120), 0.3, ComparisonType.Relative)); - Assert.False({_quantity.Name}.From{_baseUnit.PluralName}(100).Equals({_quantity.Name}.From{_baseUnit.PluralName}(120), 0.1, ComparisonType.Relative)); + {_quantity.Name} {baseUnitVariableName} = {_quantity.Name}.From{_baseUnit.PluralName}(1); + Assert.False({baseUnitVariableName}.Equals(new object())); }} [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() {{ - var v = {_quantity.Name}.From{_baseUnit.PluralName}(1); - Assert.Throws(() => v.Equals({_quantity.Name}.From{_baseUnit.PluralName}(1), -1, ComparisonType.Relative)); + {_quantity.Name} {baseUnitVariableName} = {_quantity.Name}.From{_baseUnit.PluralName}(1); + Assert.False({baseUnitVariableName}.Equals(null)); + }} +"); + var differenceResultType = _quantity.AffineOffsetType ?? _quantity.Name; + if (_quantity.Logarithmic) + { + Writer.WL($@" + + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + // note: it's currently not possible to test this due to the rounding error from (quantity - otherQuantity) + // Assert.True(quantity.Equals(otherQuantity, maxTolerance)); }} [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + public void Equals_WithNegativeTolerance_DoesNotThrowArgumentOutOfRangeException() {{ - {_quantity.Name} {baseUnitVariableName} = {_quantity.Name}.From{_baseUnit.PluralName}(1); - Assert.False({baseUnitVariableName}.Equals(new object())); + // note: unlike with vector quantities- a small tolerance maybe positive in one unit and negative in another + var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1); + var negativeTolerance = {_quantity.Name}.From{_baseUnit.PluralName}(-1); + Assert.True(quantity.Equals(quantity, negativeTolerance)); }} +"); + } + else // quantities with a linear scale + { + Writer.WL($@" + + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + }} +"); + if (_quantity.IsAffine) + { + Writer.WL($@" [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() {{ - {_quantity.Name} {baseUnitVariableName} = {_quantity.Name}.From{_baseUnit.PluralName}(1); - Assert.False({baseUnitVariableName}.Equals(null)); + var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1); + {differenceResultType} negativeTolerance = quantity - {_quantity.Name}.From{_baseUnit.PluralName}(2); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); }} +"); + } + else // vector quantities + { + Writer.WL($@" + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + {{ + var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1); + var negativeTolerance = {_quantity.Name}.From{_baseUnit.PluralName}(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + }} +"); + } + } + + Writer.WL($@" [Fact] public void HasAtLeastOneAbbreviationSpecified() @@ -1024,6 +1207,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() {{ @@ -1092,162 +1287,16 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); }} - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - }} - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - }} - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - }} - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - }} - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - }} - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - }} - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - }} - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - }} - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - }} - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - }} - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - }} - - [Fact] - public void Convert_ToString_EqualsToString() - {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - }} - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - }} - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - }} - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - }} - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof({_quantity.Name}))); - }} - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof({_unitEnumName}))); - }} - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal({_quantity.Name}.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - }} - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal({_quantity.Name}.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - }} - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - }} - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - {{ - var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - }} - [Fact] public void GetHashCode_Equals() {{ var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal(new {{{_quantity.Name}.Info.Name, quantity.Value, quantity.Unit}}.GetHashCode(), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof({_quantity.Name}), quantity.As({_quantity.Name}.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); }} "); - if (_quantity.GenerateArithmetic) + if (!_quantity.IsAffine) { Writer.WL($@" [Theory] 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/CodeGen/JsonTypes/Quantity.cs b/CodeGen/JsonTypes/Quantity.cs index f471225ad8..ac92ed51d8 100644 --- a/CodeGen/JsonTypes/Quantity.cs +++ b/CodeGen/JsonTypes/Quantity.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; @@ -14,7 +14,10 @@ internal record Quantity public BaseDimensions BaseDimensions = new(); // Default to empty public string BaseUnit = null!; + [Obsolete] public bool GenerateArithmetic = true; + public string? AffineOffsetType; + public bool IsAffine => !string.IsNullOrEmpty(AffineOffsetType); public bool Logarithmic = false; public int LogarithmicScalingFactor = 1; public string Name = null!; diff --git a/Common/UnitDefinitions/Temperature.json b/Common/UnitDefinitions/Temperature.json index c782600ae7..625bffa81e 100644 --- a/Common/UnitDefinitions/Temperature.json +++ b/Common/UnitDefinitions/Temperature.json @@ -3,6 +3,7 @@ "BaseUnit": "Kelvin", "XmlDocSummary": "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.", "GenerateArithmetic": false, + "AffineOffsetType": "TemperatureDelta", "BaseDimensions": { "Θ": 1 }, 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..6faa73e5d5 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.sln b/Samples/Samples.sln index 84ba089fe6..582e246391 100644 --- a/Samples/Samples.sln +++ b/Samples/Samples.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.27130.2020 +# Visual Studio Version 17 +VisualStudioVersion = 17.12.35514.174 d17.12 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitConverter.Wpf", "UnitConverter.Wpf\UnitConverter.Wpf\UnitConverter.Wpf.csproj", "{D04EE35D-496A-4C83-A369-09B9B2BEAEEC}" EndProject @@ -9,12 +9,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MvvmSample.Wpf", "MvvmSampl EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitConverter.Console", "UnitConverter.Console\UnitConverter.Console.csproj", "{B3141011-CEF2-46DE-B3DD-7FECD0D6108C}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_Files", "_Files", "{D3B39B9C-CE85-4929-A268-1AEBD945127C}" - ProjectSection(SolutionItems) = preProject - build.bat = build.bat - Directory.Packages.props = Directory.Packages.props - msbuild.cmd = msbuild.cmd - EndProjectSection +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitsNetSetup.Configuration", "UnitsNetSetup.Configuration\UnitsNetSetup.Configuration.csproj", "{22425924-4277-4528-8ACD-01F2EA677507}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -72,6 +67,22 @@ Global {B3141011-CEF2-46DE-B3DD-7FECD0D6108C}.Release|x64.Build.0 = Release|Any CPU {B3141011-CEF2-46DE-B3DD-7FECD0D6108C}.Release|x86.ActiveCfg = Release|Any CPU {B3141011-CEF2-46DE-B3DD-7FECD0D6108C}.Release|x86.Build.0 = Release|Any CPU + {22425924-4277-4528-8ACD-01F2EA677507}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {22425924-4277-4528-8ACD-01F2EA677507}.Debug|Any CPU.Build.0 = Debug|Any CPU + {22425924-4277-4528-8ACD-01F2EA677507}.Debug|ARM.ActiveCfg = Debug|Any CPU + {22425924-4277-4528-8ACD-01F2EA677507}.Debug|ARM.Build.0 = Debug|Any CPU + {22425924-4277-4528-8ACD-01F2EA677507}.Debug|x64.ActiveCfg = Debug|Any CPU + {22425924-4277-4528-8ACD-01F2EA677507}.Debug|x64.Build.0 = Debug|Any CPU + {22425924-4277-4528-8ACD-01F2EA677507}.Debug|x86.ActiveCfg = Debug|Any CPU + {22425924-4277-4528-8ACD-01F2EA677507}.Debug|x86.Build.0 = Debug|Any CPU + {22425924-4277-4528-8ACD-01F2EA677507}.Release|Any CPU.ActiveCfg = Release|Any CPU + {22425924-4277-4528-8ACD-01F2EA677507}.Release|Any CPU.Build.0 = Release|Any CPU + {22425924-4277-4528-8ACD-01F2EA677507}.Release|ARM.ActiveCfg = Release|Any CPU + {22425924-4277-4528-8ACD-01F2EA677507}.Release|ARM.Build.0 = Release|Any CPU + {22425924-4277-4528-8ACD-01F2EA677507}.Release|x64.ActiveCfg = Release|Any CPU + {22425924-4277-4528-8ACD-01F2EA677507}.Release|x64.Build.0 = Release|Any CPU + {22425924-4277-4528-8ACD-01F2EA677507}.Release|x86.ActiveCfg = Release|Any CPU + {22425924-4277-4528-8ACD-01F2EA677507}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE 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..abaf7891a0 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 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 7269671d09..0e82bc58e7 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToBitRateExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToBitRateExtensions.g.cs @@ -32,290 +32,290 @@ 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 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 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 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 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 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 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 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 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 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 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 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 } 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 8c3bd4a136..6369766f0f 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToDoseAreaProductExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToDoseAreaProductExtensions.g.cs @@ -32,224 +32,224 @@ 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 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 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 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 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 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 fade63eb31..5de5928c06 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToDurationExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToDurationExtensions.g.cs @@ -32,136 +32,136 @@ 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 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 580bbcb755..5eea02a12a 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToInformationExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToInformationExtensions.g.cs @@ -32,290 +32,290 @@ 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 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 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 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 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 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 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 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 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 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 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 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 } 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 52b3d5affc..10504923ad 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToLeakRateExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToLeakRateExtensions.g.cs @@ -32,37 +32,37 @@ namespace UnitsNet.NumberExtensions.NumberToLeakRate /// public static class NumberToLeakRateExtensions { - /// + /// 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 b2d80585f7..adcd9bca71 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToPressureExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToPressureExtensions.g.cs @@ -32,521 +32,521 @@ 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 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 d3694780fb..62c1c2d306 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToThermalInsulanceExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToThermalInsulanceExtensions.g.cs @@ -32,70 +32,70 @@ 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 } 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 d4506ebd9d..ac4f2f5e20 100644 --- a/UnitsNet.NumberExtensions/UnitsNet.NumberExtensions.csproj +++ b/UnitsNet.NumberExtensions/UnitsNet.NumberExtensions.csproj @@ -1,8 +1,8 @@ - + UnitsNet.NumberExtensions - 6.0.0-pre014 + 6.0.0-pre016 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). @@ -21,6 +21,7 @@ 6.0.0.0 latest enable + enable UnitsNet netstandard2.0;net8.0;net9.0 @@ -29,6 +30,10 @@ + + + + ../UnitsNet.snk @@ -46,4 +51,8 @@ + + + + diff --git a/UnitsNet.Serialization.JsonNet.Tests/AbbreviatedUnitsConverterTests.cs b/UnitsNet.Serialization.JsonNet.Tests/AbbreviatedUnitsConverterTests.cs index 5324f9a071..404de05125 100644 --- a/UnitsNet.Serialization.JsonNet.Tests/AbbreviatedUnitsConverterTests.cs +++ b/UnitsNet.Serialization.JsonNet.Tests/AbbreviatedUnitsConverterTests.cs @@ -1,4 +1,9 @@ -using Newtonsoft.Json; +using System; +using System.IO; +using System.Text; +using Newtonsoft.Json; +using UnitsNet.Serialization.JsonNet.Tests.Infrastructure; +using UnitsNet.Tests.CustomQuantities; using UnitsNet.Tests.Serialization; using UnitsNet.Units; using Xunit; @@ -7,12 +12,14 @@ 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))) { } #region Serialization tests - + [Fact] public void DoubleQuantity_SerializedWithDoubleValueAndAbbreviatedUnit() { @@ -47,6 +54,95 @@ public void InterfaceObject_SerializesWithoutKnownTypeInformation() Assert.Equal(expectedJson, json); } + [Fact] + public void InterfaceObject_WithNullValueSerializesAsNull() + { + var testObject = new TestInterfaceObject { Quantity = null! }; + var expectedJson = """{"Quantity":null}"""; + + var json = SerializeObject(testObject); + + Assert.Equal(expectedJson, json); + } + + [Fact] + public void NonNullNullableValueNestedInObject_ExpectJsonUnaffected() + { + var testObj = new TestObject() + { + NullableFrequency = Frequency.FromHertz(10), + NonNullableFrequency = Frequency.FromHertz(10) + }; + + string expectedJson = """{"NullableFrequency":{"Value":10,"Unit":"Hz","Type":"Frequency"},"NonNullableFrequency":{"Value":10,"Unit":"Hz","Type":"Frequency"}}"""; + + string json = SerializeObject(testObj); + + Assert.Equal(expectedJson, json); + } + + [Fact] + public void NullQuantityNestedInObject_SerializesAsNull() + { + var testObj = new TestObject() + { + NonNullableFrequency = Frequency.FromHertz(10) + }; + + string expectedJson = """{"NullableFrequency":null,"NonNullableFrequency":{"Value":10,"Unit":"Hz","Type":"Frequency"}}"""; + + string json = SerializeObject(testObj); + + Assert.Equal(expectedJson, json); + } + + [Fact] + public void NullObject_SerializesAsNull() + { + var abbreviatedUnitsConverter = new AbbreviatedUnitsConverter(); + var result = new StringBuilder(); + using(var stringWriter = new StringWriter(result)) + using (var writer = new JsonTextWriter(stringWriter)) + { + abbreviatedUnitsConverter.WriteJson(writer, (object)null, JsonSerializer.CreateDefault()); + } + + Assert.Equal("null", result.ToString()); + } + + [Fact] + public void WriteJson_GivenAnotherType_ThrowsJsonSerializationException() + { + var abbreviatedUnitsConverter = new AbbreviatedUnitsConverter(); + using var stringWriter = new StringWriter(); + using var writer = new JsonTextWriter(stringWriter); + Assert.Throws(() => abbreviatedUnitsConverter.WriteJson(writer, DateTime.MinValue, JsonSerializer.CreateDefault())); + } + + [Fact] + 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 @@ -57,39 +153,43 @@ public void DoubleIQuantity_DeserializedFromDoubleValueAndAbbreviatedUnit() var json = """{"Value":1.2,"Unit":"mg","Type":"Mass"}"""; var quantity = DeserializeObject(json); - + Assert.Equal(1.2, quantity.Value); Assert.Equal(MassUnit.Milligram, quantity.Unit); } [Fact] - public void DoubleQuantity_DeserializedFromDoubleValueAndAbbreviatedUnit() + public void DoubleQuantity_DeserializedFromVeryPreciseValueAndAbbreviatedUnit() { - var json = """{"Value":1.2,"Unit":"mg"}"""; + var json = """{"Value":12345678901234567890.1234567890123456789,"Unit":"mg","Type":"Mass"}"""; + var expectedValue = QuantityValue.FromDoubleRounded(1.234567890123456E+19); var quantity = DeserializeObject(json); - Assert.Equal(1.2, quantity.Value); + Assert.Equal(expectedValue, quantity.Value); Assert.Equal(MassUnit.Milligram, quantity.Unit); } [Fact] - public void DoubleIQuantity_DeserializedFromDoubleValueAndNonAmbiguousAbbreviatedUnit_WithoutQuantityType() + public void DoubleQuantity_DeserializedFromDoubleValueAndAbbreviatedUnit() { - var json = """{"Value":1.2,"Unit":"em"}"""; + var json = """{"Value":1.2,"Unit":"mg"}"""; var quantity = DeserializeObject(json); Assert.Equal(1.2, quantity.Value); - Assert.Equal(MassUnit.EarthMass, quantity.Unit); + Assert.Equal(MassUnit.Milligram, quantity.Unit); } [Fact] - public void ThrowsAmbiguousUnitParseException_WhenDeserializingAmbiguousAbbreviation_WithoutQuantityType() + public void DoubleIQuantity_DeserializedFromDoubleValueAndNonAmbiguousAbbreviatedUnit_WithoutQuantityType() { - var json = """{"Value":1.2,"Unit":"mg"}"""; + var json = """{"Value":1.2,"Unit":"em"}"""; - Assert.Throws(() => DeserializeObject(json)); + var quantity = DeserializeObject(json); + + Assert.Equal(1.2, quantity.Value); + Assert.Equal(MassUnit.EarthMass, quantity.Unit); } [Fact] @@ -116,23 +216,77 @@ public void DoubleIQuantity_DeserializedFromDoubleValueAndAbbreviatedUnit_CaseSe Assert.Equal(PressureUnit.Megabar, megabar.Unit); Assert.Equal(PressureUnit.Millibar, millibar.Unit); } + + [Fact] + public void Converter_IgnoresUnknownProperties() + { + var json = """{"Value":1.2,"Something":"Else","Unit":"mg","Type":"Mass"}"""; + + var quantity = DeserializeObject(json); + + Assert.Equal(1.2, quantity.Value); + Assert.Equal(MassUnit.Milligram, quantity.Unit); + } [Fact] - public void UnitsNetExceptionThrown_WhenDeserializing_FromUnknownQuantityType() + 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)); + Assert.Throws(() => DeserializeObject(json)); } [Fact] - public void UnitsNotFoundExceptionThrown_WhenDeserializing_FromUnknownUnit() + public void Deserializing_FromUnknownUnitForTargetQuantity_ThrowsUnitsNotFoundException() { var json = """{"Value":1.2,"Unit":"invalid","Type":"Mass"}"""; Assert.Throws(() => DeserializeObject(json)); } + [Fact] + public void DeserializingIQuantity_FromAmbiguousAbbreviationAndNoQuantityType_ThrowsAmbiguousUnitParseException() + { + var json = """{"Value":1.2,"Unit":"mg"}"""; + + Assert.Throws(() => DeserializeObject(json)); + } + + [Fact] + public void DeserializingIQuantity_FromUnknownUnitAndNoQuantityType_ThrowsUnitsNotFoundException() + { + var json = """{"Value":1.2,"Unit":"invalid"}"""; + + Assert.Throws(() => DeserializeObject(json)); + } + + [Fact] + public void DeserializingIQuantity_FromNoUnitAndNoQuantityType_ThrowsFormatException() + { + var json = """{"Value":1.2}"""; + + Assert.Throws(() => DeserializeObject(json)); + } + + [Fact] + public void ReadJson_GivenAnotherType_ThrowsJsonSerializationException() + { + var abbreviatedUnitsConverter = new AbbreviatedUnitsConverter(); + using var stringWriter = new StringReader("something"); + using var reader = new JsonTextReader(stringWriter); + Assert.Throws(() => abbreviatedUnitsConverter.ReadJson(reader, typeof(IQuantity), DateTime.MinValue, JsonSerializer.CreateDefault())); + } + + [Fact] public void DoubleIQuantity_DeserializedFromQuotedDoubleValueAndAbbreviatedUnit() { @@ -220,19 +374,39 @@ public void DoubleZeroBaseQuantity_DeserializedFromEmptyInput() Assert.Equal(0, quantity.Value); 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))] }; - #endregion + const string json = """{"Value":1.2,"Unit":"s","Type":"HowMuch"}"""; + var expectedQuantity = HowMuch.From(1.2, HowMuchUnit.Some); - #region Compatibility + // Act + HowMuch result = JsonConvert.DeserializeObject(json, settings); - [JsonObject] - class PlainOldDoubleQuantity + // Assert + Assert.Equal(expectedQuantity, result); + } + + [Fact] + public void Deserializing_NullValue_ThrowsJsonSerializationException() { - public double Value { get; set; } - public string Unit { get; set; } + 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/CustomQuantities/HowMuchTests.cs b/UnitsNet.Serialization.JsonNet.Tests/CustomQuantities/HowMuchTests.cs index b30195ff75..93741a89d1 100644 --- a/UnitsNet.Serialization.JsonNet.Tests/CustomQuantities/HowMuchTests.cs +++ b/UnitsNet.Serialization.JsonNet.Tests/CustomQuantities/HowMuchTests.cs @@ -21,5 +21,47 @@ public static void SerializeAndDeserializeCreatesSameObjectForIQuantity() var deserializedQuantity = JsonConvert.DeserializeObject(serializedQuantity, jsonSerializerSettings); Assert.Equal(quantity, deserializedQuantity); } + + [Fact] + public static void SerializeObjectWithNullQuantity() + { + var jsonSerializerSettings = new JsonSerializerSettings { Formatting = Formatting.Indented }; + var quantityConverter = new UnitsNetIQuantityJsonConverter(); + quantityConverter.RegisterCustomType(typeof(HowMuch), typeof(HowMuchUnit)); + jsonSerializerSettings.Converters.Add(quantityConverter); + + var quantity = new HowMuch(12.34, HowMuchUnit.ATon); + var objectToSerialize = new TestObject { NonNullableQuantity = quantity }; + + var serializedQuantity = JsonConvert.SerializeObject(objectToSerialize, jsonSerializerSettings); + TestObject deserializedQuantity = JsonConvert.DeserializeObject(serializedQuantity, jsonSerializerSettings); + + Assert.Equal(quantity, deserializedQuantity.NonNullableQuantity); + Assert.Null(deserializedQuantity.NullableQuantity); + } + + [Fact] + public static void SerializeObjectWithNullableQuantity() + { + var jsonSerializerSettings = new JsonSerializerSettings { Formatting = Formatting.Indented }; + var quantityConverter = new UnitsNetIQuantityJsonConverter(); + quantityConverter.RegisterCustomType(typeof(HowMuch), typeof(HowMuchUnit)); + jsonSerializerSettings.Converters.Add(quantityConverter); + + var quantity = new HowMuch(12.34, HowMuchUnit.ATon); + var objectToSerialize = new TestObject { NonNullableQuantity = quantity, NullableQuantity = quantity }; + + var serializedQuantity = JsonConvert.SerializeObject(objectToSerialize, jsonSerializerSettings); + TestObject deserializedQuantity = JsonConvert.DeserializeObject(serializedQuantity, jsonSerializerSettings); + + Assert.Equal(quantity, deserializedQuantity.NonNullableQuantity); + Assert.Equal(quantity, deserializedQuantity.NullableQuantity); + } + + public sealed class TestObject + { + public HowMuch? NullableQuantity { get; set; } + public HowMuch NonNullableQuantity { get; set; } + } } } diff --git a/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj b/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj index 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 c438447b5f..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] @@ -44,7 +43,7 @@ public void UnitsNetBaseJsonConverter_ConvertValueUnit_works_as_expected() Assert.NotNull(result); Assert.IsType(result); - Assert.True(Power.FromWatts(10.2365).Equals((Power)result, 1e-5, ComparisonType.Absolute)); + Assert.True(Power.FromWatts(10.2365).Equals((Power)result)); } [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 11977d3f67..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,55 +11,98 @@ namespace UnitsNet.Serialization.JsonNet /// /// /// { - /// "Value": 1.20, + /// "Value": 1.2, /// "Unit": "mg", /// "Type": "Mass" /// } /// /// /// - public class AbbreviatedUnitsConverter : JsonConverter + public class AbbreviatedUnitsConverter : NullableQuantityConverter { private const string ValueProperty = "Value"; 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 IDictionary _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(new Dictionary(Quantity.ByName, comparer), 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(IDictionary 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/NullableQuantityConverter.cs b/UnitsNet.Serialization.JsonNet/NullableQuantityConverter.cs new file mode 100644 index 0000000000..bc6a8a6486 --- /dev/null +++ b/UnitsNet.Serialization.JsonNet/NullableQuantityConverter.cs @@ -0,0 +1,121 @@ +// Licensed under MIT No Attribution, see LICENSE file at the root. +// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. + +using System; +using Newtonsoft.Json; + +namespace UnitsNet.Serialization.JsonNet; + +/// +/// An abstract base class for JSON serialization and deserialization of quantities that implement the interface, +/// including nullable quantities. +/// +/// +/// The type of the quantity being serialized or deserialized. This type must implement the interface. +/// +/// +/// This class extends and provides functionality to handle both direct implementations of +/// and nullable types where the underlying type implements . +/// +public abstract class NullableQuantityConverter : JsonConverter +{ + /// + /// Determines whether the specified type can be converted by this converter. + /// + /// The type of the object to check for conversion support. + /// + /// if the specified type is either directly assignable to + /// or is a nullable type with an underlying type assignable to ; + /// otherwise, . + /// + /// + /// This method checks if the provided type is compatible with the generic type parameter , + /// including nullable types where the underlying type implements . + /// + public override bool CanConvert(Type objectType) + { + // Check if the type directly implements TQuantity + if (typeof(T).IsAssignableFrom(objectType)) + { + return true; + } + + // Check if the type is a Nullable where T implements IQuantity + Type? underlyingType = Nullable.GetUnderlyingType(objectType); + return underlyingType != null && typeof(T).IsAssignableFrom(underlyingType); + } + + /// + /// Writes the JSON representation of the object. + /// + /// The to write to. + /// The value. + /// The calling serializer. + public sealed override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) + { + switch (value) + { + case T quantity: + WriteJson(writer, quantity, serializer); + break; + case null: // this case seems to be unreachable (unless calling the converter directly) + WriteJson(writer, default, serializer); + break; + default: // should not be possible (unless calling the converter directly) + throw new JsonException("Converter cannot write specified value to JSON. An IQuantity is required."); + } + } + + /// + /// Writes the JSON representation of the specified quantity. + /// + /// The to write to. + /// The quantity to write. + /// The calling serializer. + /// + /// This method is abstract and must be implemented by derived classes to define how a quantity is serialized to JSON. + /// + /// + /// Thrown if , , or is + /// . + /// + public abstract void WriteJson(JsonWriter writer, T? quantity, JsonSerializer serializer); + + + /// + /// Reads the JSON representation of the object. + /// + /// The to read from. + /// Type of the object. + /// The existing value of object being read. + /// The calling serializer. + /// The object value. + public sealed override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) + { + return existingValue switch + { + T existingQuantity => ReadJson(reader, objectType, existingQuantity, true, serializer), + null => ReadJson(reader, objectType, default, false, serializer), + _ => throw new JsonException("Converter cannot read JSON with the specified existing value. An IQuantity is required.") + }; + } + + /// + /// Reads JSON to deserialize an object of type . + /// + /// The to read from. + /// The type of the object to deserialize. + /// The existing value of the object being deserialized, if any. + /// + /// A boolean indicating whether an existing value is provided. + /// If true, contains the current value. + /// + /// The used for deserialization. + /// + /// A deserialized instance of or null if the JSON represents a null value. + /// + /// + /// Thrown if the JSON cannot be deserialized into an object of type . + /// + public abstract T? ReadJson(JsonReader reader, Type objectType, T? existingValue, bool hasExistingValue, JsonSerializer serializer); +} 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 ba3fa99a4f..2faf6e68b4 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-pre016 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 bd4d213012..342edaeceb 100644 --- a/UnitsNet.Serialization.JsonNet/UnitsNetBaseJsonConverter.cs +++ b/UnitsNet.Serialization.JsonNet/UnitsNetBaseJsonConverter.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Concurrent; -using System.Globalization; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -15,13 +14,13 @@ namespace UnitsNet.Serialization.JsonNet /// Contains shared functionality used by and /// /// The type being converted. Should either be or - public abstract class UnitsNetBaseJsonConverter : JsonConverter + public abstract class UnitsNetBaseJsonConverter : NullableQuantityConverter { private readonly ConcurrentDictionary _registeredTypes = new(); /// /// 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. /// @@ -92,10 +91,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/UnitsNetIComparableJsonConverter.cs b/UnitsNet.Serialization.JsonNet/UnitsNetIComparableJsonConverter.cs index 66445578f1..b5d9b29147 100644 --- a/UnitsNet.Serialization.JsonNet/UnitsNetIComparableJsonConverter.cs +++ b/UnitsNet.Serialization.JsonNet/UnitsNetIComparableJsonConverter.cs @@ -15,7 +15,7 @@ namespace UnitsNet.Serialization.JsonNet /// Should only be used when UnitsNet types are assigned to properties of type IComparable. /// Requires TypeNameHandling on to be set to something other than so that it outputs $type when serializing. /// - public sealed class UnitsNetIComparableJsonConverter : UnitsNetBaseJsonConverter + public sealed class UnitsNetIComparableJsonConverter : UnitsNetBaseJsonConverter { /// /// Indicates if this JsonConverter is capable of writing JSON diff --git a/UnitsNet.Serialization.JsonNet/UnitsNetIQuantityJsonConverter.cs b/UnitsNet.Serialization.JsonNet/UnitsNetIQuantityJsonConverter.cs index d25ec17172..9d03a5c352 100644 --- a/UnitsNet.Serialization.JsonNet/UnitsNetIQuantityJsonConverter.cs +++ b/UnitsNet.Serialization.JsonNet/UnitsNetIQuantityJsonConverter.cs @@ -12,7 +12,7 @@ namespace UnitsNet.Serialization.JsonNet /// JSON.net converter for IQuantity types (e.g. all units in UnitsNet) /// Use this converter to serialize and deserialize UnitsNet types to and from JSON /// - public sealed class UnitsNetIQuantityJsonConverter : UnitsNetBaseJsonConverter + public sealed class UnitsNetIQuantityJsonConverter : UnitsNetBaseJsonConverter { /// /// Writes the JSON representation of the object. 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..926a914d8f --- /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.QuantityInfoLookup.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..d131771725 --- /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.QuantityInfoLookup) + { + } + + /// + /// 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.QuantityInfoLookup, 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..cbf3280c88 --- /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.QuantityInfoLookup.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.QuantityInfoLookup) + { + } + + /// + /// 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..fd05ea94d1 --- /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.QuantityInfoLookup) + { + } + + /// + /// 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.QuantityInfoLookup, 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..bee420103b --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson/UnitsNet.Serialization.SystemTextJson.csproj @@ -0,0 +1,54 @@ + + + + UnitsNet.Serialization.SystemTextJson + 6.0.0-pre016 + 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 new file mode 100644 index 0000000000..fdee9ccce0 --- /dev/null +++ b/UnitsNet.Tests/AffineQuantityExtensionsTest.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; +using System.Collections.Generic; +using UnitsNet.Units; +using Xunit; + +namespace UnitsNet.Tests; + +public class AffineQuantityExtensionsTest +{ + [Theory] + [InlineData(25.0, 25.0, 0.1, true)] // Equal values + [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 + public void Equals_Temperature_TemperatureDelta(double value1, double value2, double toleranceValue, bool expected) + { + var temperature1 = Temperature.FromDegreesCelsius(value1); + var temperature2 = Temperature.FromDegreesCelsius(value2); + var tolerance = TemperatureDelta.FromDegreesCelsius(toleranceValue); + + var result = temperature1.Equals(temperature2, tolerance); + + Assert.Equal(expected, result); + } + + [Fact] + public void Equals_WithToleranceAtTheLimit_ReturnsTrue() + { + var quantity = Temperature.FromDegreesCelsius(1); + var otherQuantity = Temperature.FromMillidegreesCelsius(999); + var tolerance = TemperatureDelta.FromMillidegreesCelsius(1); + + Assert.Multiple(() => + { + Assert.True(quantity.Equals(otherQuantity, tolerance), "Difference == Tolerance"); + Assert.True(quantity.Equals(otherQuantity, tolerance * 2), "Difference < Tolerance"); + Assert.False(quantity.Equals(otherQuantity, tolerance / 2), "Difference > Tolerance"); + }, + () => + { + Assert.True(otherQuantity.Equals(quantity, tolerance), "Difference == Tolerance"); + Assert.True(otherQuantity.Equals(quantity, tolerance * 2), "Difference < Tolerance"); + Assert.False(otherQuantity.Equals(quantity, tolerance / 2), "Difference > Tolerance"); + }); + } + + [Fact] + public void Equals_Temperature_TemperatureDelta_ThrowsArgumentOutOfRangeException_ForNegativeTolerance() + { + var temperature1 = Temperature.FromDegreesCelsius(25.0); + var temperature2 = Temperature.FromDegreesCelsius(25.0); + var negativeTolerance = TemperatureDelta.FromDegreesCelsius(-0.1); + + Assert.Throws(() => temperature1.Equals(temperature2, negativeTolerance)); + } + + [Theory] + [InlineData(25.0, 25.0, 0.1, true)] // Equal values + [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 + public void Equals_Temperature_IQuantity(double value1, double value2, double toleranceValue, bool expected) + { + var temperature1 = Temperature.FromDegreesCelsius(value1); + IQuantity temperature2 = Temperature.FromDegreesCelsius(value2); + var tolerance = TemperatureDelta.FromDegreesCelsius(toleranceValue); + + var result = temperature1.Equals(temperature2, tolerance); + + Assert.Equal(expected, result); + } + + [Fact] + public void Equals_Temperature_IQuantity_WithDifferentType_ReturnsFalse() + { + var temperature1 = Temperature.FromDegreesCelsius(25.0); + IQuantity length = Length.From(QuantityValue.One, LengthUnit.Meter); + var tolerance = TemperatureDelta.FromDegreesCelsius(1); + + var result = temperature1.Equals(length, tolerance); + + Assert.False(result); + } + + [Fact] + public void Equals_WithNullOther_ReturnsFalse() + { + var quantity = Temperature.FromDegreesCelsius(25); + IQuantity? other = null; + var tolerance = TemperatureDelta.FromDegreesCelsius(25); + + var result = quantity.Equals(other, tolerance); + + Assert.False(result); + } + + [Fact] + public void Equals_IQuantity_WithNullOther_ReturnsFalse() + { + var quantity = Temperature.FromDegreesCelsius(25.0); + var tolerance = TemperatureDelta.FromDegreesCelsius(25.0); + + var result = quantity.Equals(null, tolerance); + + Assert.False(result); + } + + [Theory] + [InlineData(25.0, 25.0, 0.1, true)] // Equal values + [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 + public void EqualsAbsolute_Temperature_TemperatureDelta(double value1, double value2, double toleranceValue, bool expected) + { + var temperature1 = Temperature.FromDegreesCelsius(value1); + var temperature2 = Temperature.FromDegreesCelsius(value2); + var tolerance = TemperatureDelta.FromDegreesCelsius(toleranceValue); + + var result = temperature1.EqualsAbsolute(temperature2, tolerance); + + Assert.Equal(expected, result); + } + + [Fact] + public void EqualsAbsolute_Temperature_TemperatureDelta_ThrowsArgumentOutOfRangeException_ForNegativeTolerance() + { + var temperature1 = Temperature.FromDegreesCelsius(25.0); + var temperature2 = Temperature.FromDegreesCelsius(25.0); + var negativeTolerance = TemperatureDelta.FromDegreesCelsius(-0.1); + + Assert.Throws(() => temperature1.EqualsAbsolute(temperature2, negativeTolerance)); + } + + [Theory] + [InlineData(new[] { 25.0, 30.0, 35.0 }, 30.0)] // Average of three values + [InlineData(new[] { 25.0 }, 25.0)] // Single value + public void Average_Temperature(double[] values, double expectedAverage) + { + Temperature[] temperatures = Array.ConvertAll(values, value => Temperature.FromDegreesCelsius(value)); + + Temperature result = temperatures.Average(); + + Assert.Equal(expectedAverage, result.Value); + Assert.Equal(TemperatureUnit.DegreeCelsius, result.Unit); + } + + [Fact] + public void Average_TemperaturesWithDifferentUnits() + { + Temperature[] temperatures = + [ + Temperature.FromDegreesCelsius(25.0), + Temperature.FromDegreesFahrenheit(77.0), // equivalent to 25.0°C + Temperature.FromKelvins(298.15) // equivalent to 25.0°C + ]; + + Temperature result = temperatures.Average(); + + Assert.Equal(25, result.Value); + Assert.Equal(TemperatureUnit.DegreeCelsius, result.Unit); + } + + [Fact] + public void Average_Temperature_ThrowsArgumentNullException_ForNullCollection() + { + IEnumerable temperatures = null!; + + Assert.Throws(() => temperatures.Average()); + } + + [Fact] + public void Average_Temperature_ThrowsInvalidOperationException_ForEmptyCollection() + { + Temperature[] temperatures = []; + + Assert.Throws(() => temperatures.Average()); + } + + [Theory] + [InlineData(new[] { 25.0, 30.0, 35.0 }, TemperatureUnit.DegreeCelsius, 30.0)] // Average in Celsius + [InlineData(new[] { 77.0, 86.0, 95.0 }, TemperatureUnit.DegreeFahrenheit, 86.0)] // Average in Fahrenheit + public void Average_Temperature_WithUnit(double[] values, TemperatureUnit unit, double expectedAverage) + { + Temperature[] temperatures = Array.ConvertAll(values, value => Temperature.From(value, unit)); + + Temperature result = temperatures.Average(unit); + + Assert.Equal(expectedAverage, result.Value); + Assert.Equal(unit, result.Unit); + } + + [Fact] + public void Average_TemperaturesWithDifferentUnits_WithTargetUnit() + { + Temperature[] temperatures = + [ + Temperature.FromKelvins(298.15), // equivalent to 25.0°C + Temperature.FromDegreesCelsius(25.0), + Temperature.FromDegreesFahrenheit(77.0) // equivalent to 25.0°C + ]; + + Temperature result = temperatures.Average(TemperatureUnit.DegreeCelsius); + + Assert.Equal(25, result.Value); + Assert.Equal(TemperatureUnit.DegreeCelsius, result.Unit); + } + + [Fact] + public void Average_Temperature_WithUnit_ThrowsArgumentNullException_ForNullCollection() + { + IEnumerable temperatures = null!; + + Assert.Throws(() => temperatures.Average(TemperatureUnit.DegreeCelsius)); + } + + [Fact] + public void Average_Temperature_WithUnit_ThrowsInvalidOperationException_ForEmptyCollection() + { + Assert.Throws(() => Array.Empty().Average(TemperatureUnit.DegreeCelsius)); + } +} 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 d36a8a2a3e..eede946ab7 100644 --- a/UnitsNet.Tests/CustomCode/PressureTests.cs +++ b/UnitsNet.Tests/CustomCode/PressureTests.cs @@ -283,16 +283,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..d9a6c3c6d0 --- /dev/null +++ b/UnitsNet.Tests/CustomCode/QuantityInfos/Builder/QuantityInfoBuilderExtensionsTest.cs @@ -0,0 +1,96 @@ +// 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 System.Linq; +using UnitsNet.Units; +using Xunit; + +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 40dbd962f7..b17ff726b4 100644 --- a/UnitsNet.Tests/CustomCode/TemperatureTests.cs +++ b/UnitsNet.Tests/CustomCode/TemperatureTests.cs @@ -2,7 +2,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; +using UnitsNet.Units; using Xunit; namespace UnitsNet.Tests @@ -35,103 +35,118 @@ public void AllBaseQuantityUnitsAreBaseUnits() Assert.All(Temperature.Info.UnitInfos, unitInfo => Assert.Equal(new BaseUnits(temperature: unitInfo.Value), unitInfo.BaseUnits)); } - public static IEnumerable DividedByTemperatureDeltaEqualsTemperatureData { get; } = - new List + public static IEnumerable DividedByTemperatureDeltaEqualsTemperatureData { get; } = new[] { - new object[] { Temperature.FromDegreesCelsius(10), 1, Temperature.FromDegreesCelsius(10) }, - new object[] { Temperature.FromDegreesCelsius(10), 5, Temperature.FromDegreesCelsius(2) }, - new object[] { Temperature.FromDegreesCelsius(10), -10, Temperature.FromDegreesCelsius(-1) }, - new object[] { Temperature.FromDegreesFahrenheit(10), 1, Temperature.FromDegreesFahrenheit(10) }, - new object[] { Temperature.FromDegreesFahrenheit(10), 5, Temperature.FromDegreesFahrenheit(2) }, - new object[] { Temperature.FromDegreesFahrenheit(10), -10, Temperature.FromDegreesFahrenheit(-1) } + new object[] { (10m, TemperatureUnit.DegreeCelsius), 1, (10m, TemperatureUnit.DegreeCelsius) }, + new object[] { (10m, TemperatureUnit.DegreeCelsius), 5, (2m, TemperatureUnit.DegreeCelsius) }, + new object[] { (10m, TemperatureUnit.DegreeCelsius), -10, (-1m, TemperatureUnit.DegreeCelsius) }, + new object[] { (10m, TemperatureUnit.DegreeFahrenheit), 1, (10m, TemperatureUnit.DegreeFahrenheit) }, + new object[] { (10m, TemperatureUnit.DegreeFahrenheit), 5, (2m, TemperatureUnit.DegreeFahrenheit) }, + new object[] { (10m, TemperatureUnit.DegreeFahrenheit), -10, (-1m, TemperatureUnit.DegreeFahrenheit) } }; - [SuppressMessage("ReSharper", "ImpureMethodCallOnReadonlyValueField", - Justification = "R# incorrectly identifies method as impure, due to internal method calls.")] [Theory] [MemberData(nameof(DividedByTemperatureDeltaEqualsTemperatureData))] - public void DividedByTemperatureDeltaEqualsTemperature(Temperature temperature, int divisor, Temperature expected) + public void DividedByTemperatureDeltaEqualsTemperature((decimal Value, TemperatureUnit Unit) temperature, decimal divisor, + (decimal Value, TemperatureUnit Unit) expected) { - Temperature resultTemp = temperature.Divide(divisor, temperature.Unit); - Assert.True(expected.Equals(resultTemp, 1e-5, ComparisonType.Absolute)); + var temp = new Temperature(temperature.Value, temperature.Unit); + Temperature result = temp.Divide(divisor, temperature.Unit); + Assert.Equal(expected.Value, result.Value); + Assert.Equal(expected.Unit, result.Unit); } - public static IEnumerable MultiplyByTemperatureDeltaEqualsTemperatureData { get; } = - new List + public static IEnumerable MultiplyByTemperatureDeltaEqualsTemperatureData { get; } = new[] { - new object[] { Temperature.FromDegreesCelsius(10), 0, Temperature.FromDegreesCelsius(0) }, - new object[] { Temperature.FromDegreesCelsius(10), 5, Temperature.FromDegreesCelsius(50) }, - new object[] { Temperature.FromDegreesCelsius(10), -5, Temperature.FromDegreesCelsius(-50) }, - new object[] { Temperature.FromDegreesFahrenheit(10), 0, Temperature.FromDegreesFahrenheit(0) }, - new object[] { Temperature.FromDegreesFahrenheit(10), 5, Temperature.FromDegreesFahrenheit(50) }, - new object[] { Temperature.FromDegreesFahrenheit(10), -5, Temperature.FromDegreesFahrenheit(-50) } + new object[] { (10m, TemperatureUnit.DegreeCelsius), 0, (0m, TemperatureUnit.DegreeCelsius) }, + new object[] { (10m, TemperatureUnit.DegreeCelsius), 5, (50m, TemperatureUnit.DegreeCelsius) }, + new object[] { (10m, TemperatureUnit.DegreeCelsius), -5, (-50m, TemperatureUnit.DegreeCelsius) }, + new object[] { (10m, TemperatureUnit.DegreeFahrenheit), 0, (0m, TemperatureUnit.DegreeFahrenheit) }, + new object[] { (10m, TemperatureUnit.DegreeFahrenheit), 5, (50m, TemperatureUnit.DegreeFahrenheit) }, + new object[] { (10m, TemperatureUnit.DegreeFahrenheit), -5, (-50m, TemperatureUnit.DegreeFahrenheit) } }; - [SuppressMessage("ReSharper", "ImpureMethodCallOnReadonlyValueField", - Justification = "R# incorrectly identifies method as impure, due to internal method calls.")] [Theory] [MemberData(nameof(MultiplyByTemperatureDeltaEqualsTemperatureData))] - public void MultiplyByTemperatureDeltaEqualsTemperature(Temperature temperature, int factor, Temperature expected) + public void MultiplyByTemperatureDeltaEqualsTemperature((decimal Value, TemperatureUnit Unit) temperature, decimal factor, + (decimal Value, TemperatureUnit Unit) expected) { - Temperature resultTemp = temperature.Multiply(factor, temperature.Unit); - Assert.True(expected.Equals(resultTemp, 1e-5, ComparisonType.Absolute)); + var temp = new Temperature(temperature.Value, temperature.Unit); + var result = temp.Multiply(factor, temperature.Unit);; + Assert.Equal(expected.Value, result.Value); + Assert.Equal(expected.Unit, result.Unit); } - public static IEnumerable TemperatureDeltaPlusTemperatureEqualsTemperatureData { get; } = - new List + public static IEnumerable TemperatureDeltaPlusTemperatureEqualsTemperatureData { get; } = new[] { - new object[] { Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(0), Temperature.FromDegreesCelsius(-10) }, - new object[] { Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(10), Temperature.FromDegreesCelsius(0) }, - new object[] { Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(20), Temperature.FromDegreesCelsius(10) }, - new object[] { Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(0), Temperature.FromDegreesFahrenheit(-10) }, - new object[] { Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(10), Temperature.FromDegreesFahrenheit(0) }, - new object[] { Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(20), Temperature.FromDegreesFahrenheit(10) } + new object[] { -10m, TemperatureUnit.DegreeCelsius, 0m, TemperatureDeltaUnit.DegreeCelsius, -10m, TemperatureUnit.DegreeCelsius }, + new object[] { -10m, TemperatureUnit.DegreeCelsius, 10m, TemperatureDeltaUnit.DegreeCelsius, 0m, TemperatureUnit.DegreeCelsius }, + new object[] { -10m, TemperatureUnit.DegreeCelsius, 20m, TemperatureDeltaUnit.DegreeCelsius, 10m, TemperatureUnit.DegreeCelsius }, + new object[] { -10m, TemperatureUnit.DegreeFahrenheit, 0m, TemperatureDeltaUnit.DegreeFahrenheit, -10m, TemperatureUnit.DegreeFahrenheit }, + new object[] { -10m, TemperatureUnit.DegreeFahrenheit, 10m, TemperatureDeltaUnit.DegreeFahrenheit, 0m, TemperatureUnit.DegreeFahrenheit }, + new object[] { -10m, TemperatureUnit.DegreeFahrenheit, 20m, TemperatureDeltaUnit.DegreeFahrenheit, 10m, TemperatureUnit.DegreeFahrenheit } }; [Theory] [MemberData(nameof(TemperatureDeltaPlusTemperatureEqualsTemperatureData))] - public void TemperatureDeltaPlusTemperatureEqualsTemperature(Temperature temperature, TemperatureDelta delta, Temperature expected) + public void TemperatureDeltaPlusTemperatureEqualsTemperature(decimal temperatureValue, TemperatureUnit temperatureUnit, decimal deltaValue, + TemperatureDeltaUnit deltaUnit, decimal expectedValue, TemperatureUnit expectedUnit) { - Temperature resultTemp = delta + temperature; - Assert.True(expected.Equals(resultTemp, 1e-5, ComparisonType.Absolute)); + var temperature = new Temperature(temperatureValue, temperatureUnit); + var temperatureDelta = new TemperatureDelta(deltaValue, deltaUnit); + var expectedTemperature = new Temperature(expectedValue, expectedUnit); + + Temperature result = temperature + temperatureDelta; + + Assert.Equal(expectedTemperature, result); } - public static IEnumerable TemperatureMinusTemperatureDeltaEqualsTemperatureData { get; } = - new List + public static IEnumerable TemperatureMinusTemperatureDeltaEqualsTemperatureData { get; } = new[] { - new object[] { Temperature.FromDegreesCelsius(20), TemperatureDelta.FromDegreesCelsius(10), Temperature.FromDegreesCelsius(10) }, - new object[] { Temperature.FromDegreesCelsius(20), TemperatureDelta.FromDegreesCelsius(20), Temperature.FromDegreesCelsius(0) }, - new object[] { Temperature.FromDegreesCelsius(20), TemperatureDelta.FromDegreesCelsius(30), Temperature.FromDegreesCelsius(-10) }, - new object[] { Temperature.FromDegreesFahrenheit(20), TemperatureDelta.FromDegreesFahrenheit(10), Temperature.FromDegreesFahrenheit(10) }, - new object[] { Temperature.FromDegreesFahrenheit(20), TemperatureDelta.FromDegreesFahrenheit(20), Temperature.FromDegreesFahrenheit(0) }, - new object[] { Temperature.FromDegreesFahrenheit(20), TemperatureDelta.FromDegreesFahrenheit(30), Temperature.FromDegreesFahrenheit(-10) } + new object[] { 20m, TemperatureUnit.DegreeCelsius, 10m, TemperatureDeltaUnit.DegreeCelsius, 10m, TemperatureUnit.DegreeCelsius }, + new object[] { 20m, TemperatureUnit.DegreeCelsius, 20m, TemperatureDeltaUnit.DegreeCelsius, 0m, TemperatureUnit.DegreeCelsius }, + new object[] { 20m, TemperatureUnit.DegreeCelsius, 30m, TemperatureDeltaUnit.DegreeCelsius, -10m, TemperatureUnit.DegreeCelsius }, + new object[] { 20m, TemperatureUnit.DegreeFahrenheit, 10m, TemperatureDeltaUnit.DegreeFahrenheit, 10m, TemperatureUnit.DegreeFahrenheit }, + new object[] { 20m, TemperatureUnit.DegreeFahrenheit, 20m, TemperatureDeltaUnit.DegreeFahrenheit, 0m, TemperatureUnit.DegreeFahrenheit }, + new object[] { 20m, TemperatureUnit.DegreeFahrenheit, 30m, TemperatureDeltaUnit.DegreeFahrenheit, -10m, TemperatureUnit.DegreeFahrenheit } }; [Theory] [MemberData(nameof(TemperatureMinusTemperatureDeltaEqualsTemperatureData))] - public void TemperatureMinusTemperatureDeltaEqualsTemperature(Temperature temperature, TemperatureDelta delta, Temperature expected) + public void TemperatureMinusTemperatureDeltaEqualsTemperature(decimal temperatureValue, TemperatureUnit temperatureUnit, decimal deltaValue, + TemperatureDeltaUnit deltaUnit, decimal expectedValue, TemperatureUnit expectedUnit) { - Temperature resultTemp = temperature - delta; - Assert.True(expected.Equals(resultTemp, 1e-5, ComparisonType.Absolute)); + var temp = new Temperature(temperatureValue, temperatureUnit); + var delta = new TemperatureDelta(deltaValue, deltaUnit); + var expectedTemperature = new Temperature(expectedValue, expectedUnit); + + Temperature result = temp - delta; + + Assert.Equal(expectedTemperature, result); } - public static IEnumerable TemperaturePlusTemperatureDeltaEqualsTemperatureData { get; } = - new List + public static IEnumerable TemperaturePlusTemperatureDeltaEqualsTemperatureData { get; } = new[] { - new object[] { Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(0), Temperature.FromDegreesCelsius(-10) }, - new object[] { Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(10), Temperature.FromDegreesCelsius(0) }, - new object[] { Temperature.FromDegreesCelsius(-10), TemperatureDelta.FromDegreesCelsius(20), Temperature.FromDegreesCelsius(10) }, - new object[] { Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(0), Temperature.FromDegreesFahrenheit(-10) }, - new object[] { Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(10), Temperature.FromDegreesFahrenheit(0) }, - new object[] { Temperature.FromDegreesFahrenheit(-10), TemperatureDelta.FromDegreesFahrenheit(20), Temperature.FromDegreesFahrenheit(10) } + new object[] { -10m, TemperatureUnit.DegreeCelsius, 0m, TemperatureDeltaUnit.DegreeCelsius, -10m, TemperatureUnit.DegreeCelsius }, + new object[] { -10m, TemperatureUnit.DegreeCelsius, 10m, TemperatureDeltaUnit.DegreeCelsius, 0m, TemperatureUnit.DegreeCelsius }, + new object[] { -10m, TemperatureUnit.DegreeCelsius, 20m, TemperatureDeltaUnit.DegreeCelsius, 10m, TemperatureUnit.DegreeCelsius }, + new object[] { -10m, TemperatureUnit.DegreeFahrenheit, 0m, TemperatureDeltaUnit.DegreeFahrenheit, -10m, TemperatureUnit.DegreeFahrenheit }, + new object[] { -10m, TemperatureUnit.DegreeFahrenheit, 10m, TemperatureDeltaUnit.DegreeFahrenheit, 0m, TemperatureUnit.DegreeFahrenheit }, + new object[] { -10m, TemperatureUnit.DegreeFahrenheit, 20m, TemperatureDeltaUnit.DegreeFahrenheit, 10m, TemperatureUnit.DegreeFahrenheit } }; [Theory] [MemberData(nameof(TemperaturePlusTemperatureDeltaEqualsTemperatureData))] - public void TemperaturePlusTemperatureDeltaEqualsTemperature(Temperature temperature, TemperatureDelta delta, Temperature expected) + public void TemperaturePlusTemperatureDeltaEqualsTemperature(decimal temperatureValue, TemperatureUnit temperatureUnit, decimal deltaValue, + TemperatureDeltaUnit deltaUnit, decimal expectedValue, TemperatureUnit expectedUnit) { - Temperature resultTemp = temperature + delta; - Assert.True(expected.Equals(resultTemp, 1e-5, ComparisonType.Absolute)); + var temp = new Temperature(temperatureValue, temperatureUnit); + var delta = new TemperatureDelta(deltaValue, deltaUnit); + var expectedTemperature = new Temperature(expectedValue, expectedUnit); + + Temperature result = temp + delta; + + Assert.Equal(expectedTemperature, result); } } } diff --git a/UnitsNet.Tests/CustomCode/ThermalInsulanceTests.cs b/UnitsNet.Tests/CustomCode/ThermalInsulanceTests.cs index f40e9cbd70..e9ae31e72f 100644 --- a/UnitsNet.Tests/CustomCode/ThermalInsulanceTests.cs +++ b/UnitsNet.Tests/CustomCode/ThermalInsulanceTests.cs @@ -31,6 +31,15 @@ public class ThermalInsulanceTests : ThermalInsulanceTestsBase protected override double SquareMeterKelvinsPerKilowattInOneSquareMeterKelvinPerKilowatt => 1; protected override double SquareMeterKelvinsPerWattInOneSquareMeterKelvinPerKilowatt => 0.001; + // 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 233c97b1f1..be4b0c14da 100644 --- a/UnitsNet.Tests/CustomQuantities/HowMuch.cs +++ b/UnitsNet.Tests/CustomQuantities/HowMuch.cs @@ -1,4 +1,5 @@ using System; +using UnitsNet.Units; namespace UnitsNet.Tests.CustomQuantities { @@ -6,55 +7,111 @@ namespace UnitsNet.Tests.CustomQuantities /// /// Example of a custom/third-party quantity implementation, for plugging in quantities and units at runtime. /// - public readonly struct HowMuch : IQuantity + 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(QuantityValue value, HowMuchUnit unit) + { + return new HowMuch(value, unit); + } - public bool Equals(IQuantity? other, IQuantity tolerance) => throw new NotImplementedException(); - - Enum IQuantity.Unit => Unit; public HowMuchUnit Unit { get; } - public double Value { get; } + public QuantityValue Value { get; } - #region IQuantity - - private static readonly HowMuch Zero = new HowMuch(0, HowMuchUnit.Some); - public BaseDimensions Dimensions => BaseDimensions.Dimensionless; + #region IQuantity - public QuantityInfo QuantityInfo => new( + public static readonly QuantityInfo Info = new( nameof(HowMuch), - typeof(HowMuchUnit), - new UnitInfo[] + HowMuchUnit.Some, + new UnitDefinition[] { - new UnitInfo(HowMuchUnit.Some, "Some", BaseUnits.Undefined, nameof(HowMuch)), - new UnitInfo(HowMuchUnit.ATon, "Tons", BaseUnits.Undefined, nameof(HowMuch)), - new UnitInfo(HowMuchUnit.AShitTon, "ShitTons", BaseUnits.Undefined, nameof(HowMuch)), + new(HowMuchUnit.Some, "Some", 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)) }, - HowMuchUnit.Some, - Zero, - BaseDimensions.Dimensionless); + 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; + } + + QuantityInfo IQuantity.QuantityInfo + { + get => Info; + } + + QuantityInfo IQuantity.QuantityInfo + { + get => Info; + } + + UnitKey IQuantity.UnitKey + { + get => UnitKey.ForUnit(Unit); + } - public double As(Enum unit) => Convert.ToDouble(unit); + public override string ToString() + { + 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 IQuantityInstance.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(UnitSystem unitSystem) => throw new NotImplementedException(); + Enum IQuantity.Unit + { + get => Unit; + } + + // all of these are now marked as obsolete + + QuantityValue IQuantity.As(Enum unit) + { + return UnitConverter.Default.ConvertValue(this, unit); + } + + IQuantity IQuantity.ToUnit(Enum unit) + { + return UnitConverter.Default.ConvertTo(this, unit); + } + + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) + { + return this.ToUnit(unitSystem); + } + + IQuantity IQuantity.ToUnit(HowMuchUnit unit) + { + return this.ToUnit(unit); + } + + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) + { + return this.ToUnit(unitSystem); + } - public override string ToString() => $"{Value} {Unit}"; - public string ToString(string? format, IFormatProvider? formatProvider) => $"HowMuch ({format}, {formatProvider})"; - public string ToString(IFormatProvider? provider) => $"HowMuch ({provider})"; +#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/DummyIQuantity.cs b/UnitsNet.Tests/DummyIQuantity.cs deleted file mode 100644 index cc15ec1af4..0000000000 --- a/UnitsNet.Tests/DummyIQuantity.cs +++ /dev/null @@ -1,34 +0,0 @@ -#nullable enable -using System; - -namespace UnitsNet.Tests -{ - internal class DummyIQuantity : IQuantity - { - public BaseDimensions Dimensions => throw new NotImplementedException(); - - public QuantityInfo QuantityInfo => throw new NotImplementedException(); - - bool IQuantity.Equals(IQuantity? other, IQuantity tolerance) => throw new NotImplementedException(); - - public Enum Unit => throw new NotImplementedException(); - - public double Value => throw new NotImplementedException(); - - public double As(Enum unit ) => throw new NotImplementedException(); - - public double As(UnitSystem unitSystem ) => throw new NotImplementedException(); - - public bool Equals(IQuantity? other, double tolerance, ComparisonType comparisonType) => throw new NotImplementedException(); - - public string ToString(IFormatProvider? provider) => throw new NotImplementedException(); - - public string ToString(string? format, IFormatProvider? formatProvider) => throw new NotImplementedException(); - - public IQuantity ToUnit(Enum unit, UnitConverter unitConverter) => throw new NotImplementedException(); - - public IQuantity ToUnit(Enum unit ) => throw new NotImplementedException(); - - public IQuantity ToUnit(UnitSystem unitSystem ) => throw new NotImplementedException(); - } -} diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AbsorbedDoseOfIonizingRadiationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AbsorbedDoseOfIonizingRadiationTestsBase.g.cs index 54fe5270cc..48310377da 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AbsorbedDoseOfIonizingRadiationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AbsorbedDoseOfIonizingRadiationTestsBase.g.cs @@ -156,7 +156,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new AbsorbedDoseOfIonizingRadiation(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -169,15 +169,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void AbsorbedDoseOfIonizingRadiation_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + AbsorbedDoseOfIonizingRadiationUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new AbsorbedDoseOfIonizingRadiation(1, AbsorbedDoseOfIonizingRadiationUnit.Gray); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(AbsorbedDoseOfIonizingRadiation.Zero, quantityInfo.Zero); Assert.Equal("AbsorbedDoseOfIonizingRadiation", quantityInfo.Name); + Assert.Equal(AbsorbedDoseOfIonizingRadiation.Zero, quantityInfo.Zero); + Assert.Equal(AbsorbedDoseOfIonizingRadiation.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(AbsorbedDoseOfIonizingRadiation.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + [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] @@ -206,67 +224,67 @@ public void GrayToAbsorbedDoseOfIonizingRadiationUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = AbsorbedDoseOfIonizingRadiation.From(1, AbsorbedDoseOfIonizingRadiationUnit.Centigray); - AssertEx.EqualTolerance(1, quantity00.Centigrays, CentigraysTolerance); + Assert.Equal(1, quantity00.Centigrays); Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Centigray, quantity00.Unit); var quantity01 = AbsorbedDoseOfIonizingRadiation.From(1, AbsorbedDoseOfIonizingRadiationUnit.Femtogray); - AssertEx.EqualTolerance(1, quantity01.Femtograys, FemtograysTolerance); + Assert.Equal(1, quantity01.Femtograys); Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Femtogray, quantity01.Unit); var quantity02 = AbsorbedDoseOfIonizingRadiation.From(1, AbsorbedDoseOfIonizingRadiationUnit.Gigagray); - AssertEx.EqualTolerance(1, quantity02.Gigagrays, GigagraysTolerance); + Assert.Equal(1, quantity02.Gigagrays); Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Gigagray, quantity02.Unit); var quantity03 = AbsorbedDoseOfIonizingRadiation.From(1, AbsorbedDoseOfIonizingRadiationUnit.Gray); - AssertEx.EqualTolerance(1, quantity03.Grays, GraysTolerance); + Assert.Equal(1, quantity03.Grays); Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Gray, quantity03.Unit); var quantity04 = AbsorbedDoseOfIonizingRadiation.From(1, AbsorbedDoseOfIonizingRadiationUnit.Kilogray); - AssertEx.EqualTolerance(1, quantity04.Kilograys, KilograysTolerance); + Assert.Equal(1, quantity04.Kilograys); Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Kilogray, quantity04.Unit); var quantity05 = AbsorbedDoseOfIonizingRadiation.From(1, AbsorbedDoseOfIonizingRadiationUnit.Kilorad); - AssertEx.EqualTolerance(1, quantity05.Kilorads, KiloradsTolerance); + Assert.Equal(1, quantity05.Kilorads); Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Kilorad, quantity05.Unit); var quantity06 = AbsorbedDoseOfIonizingRadiation.From(1, AbsorbedDoseOfIonizingRadiationUnit.Megagray); - AssertEx.EqualTolerance(1, quantity06.Megagrays, MegagraysTolerance); + Assert.Equal(1, quantity06.Megagrays); Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Megagray, quantity06.Unit); var quantity07 = AbsorbedDoseOfIonizingRadiation.From(1, AbsorbedDoseOfIonizingRadiationUnit.Megarad); - AssertEx.EqualTolerance(1, quantity07.Megarads, MegaradsTolerance); + Assert.Equal(1, quantity07.Megarads); Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Megarad, quantity07.Unit); var quantity08 = AbsorbedDoseOfIonizingRadiation.From(1, AbsorbedDoseOfIonizingRadiationUnit.Microgray); - AssertEx.EqualTolerance(1, quantity08.Micrograys, MicrograysTolerance); + Assert.Equal(1, quantity08.Micrograys); Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Microgray, quantity08.Unit); var quantity09 = AbsorbedDoseOfIonizingRadiation.From(1, AbsorbedDoseOfIonizingRadiationUnit.Milligray); - AssertEx.EqualTolerance(1, quantity09.Milligrays, MilligraysTolerance); + Assert.Equal(1, quantity09.Milligrays); Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Milligray, quantity09.Unit); var quantity10 = AbsorbedDoseOfIonizingRadiation.From(1, AbsorbedDoseOfIonizingRadiationUnit.Millirad); - AssertEx.EqualTolerance(1, quantity10.Millirads, MilliradsTolerance); + Assert.Equal(1, quantity10.Millirads); Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Millirad, quantity10.Unit); var quantity11 = AbsorbedDoseOfIonizingRadiation.From(1, AbsorbedDoseOfIonizingRadiationUnit.Nanogray); - AssertEx.EqualTolerance(1, quantity11.Nanograys, NanograysTolerance); + Assert.Equal(1, quantity11.Nanograys); Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Nanogray, quantity11.Unit); var quantity12 = AbsorbedDoseOfIonizingRadiation.From(1, AbsorbedDoseOfIonizingRadiationUnit.Petagray); - AssertEx.EqualTolerance(1, quantity12.Petagrays, PetagraysTolerance); + Assert.Equal(1, quantity12.Petagrays); Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Petagray, quantity12.Unit); var quantity13 = AbsorbedDoseOfIonizingRadiation.From(1, AbsorbedDoseOfIonizingRadiationUnit.Picogray); - AssertEx.EqualTolerance(1, quantity13.Picograys, PicograysTolerance); + Assert.Equal(1, quantity13.Picograys); Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Picogray, quantity13.Unit); var quantity14 = AbsorbedDoseOfIonizingRadiation.From(1, AbsorbedDoseOfIonizingRadiationUnit.Rad); - AssertEx.EqualTolerance(1, quantity14.Rads, RadsTolerance); + Assert.Equal(1, quantity14.Rads); Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Rad, quantity14.Unit); var quantity15 = AbsorbedDoseOfIonizingRadiation.From(1, AbsorbedDoseOfIonizingRadiationUnit.Teragray); - AssertEx.EqualTolerance(1, quantity15.Teragrays, TeragraysTolerance); + Assert.Equal(1, quantity15.Teragrays); Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Teragray, quantity15.Unit); } @@ -417,358 +435,86 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 cGy", AbsorbedDoseOfIonizingRadiationUnit.Centigray, 4.2)] + [InlineData("en-US", "4.2 fGy", AbsorbedDoseOfIonizingRadiationUnit.Femtogray, 4.2)] + [InlineData("en-US", "4.2 GGy", AbsorbedDoseOfIonizingRadiationUnit.Gigagray, 4.2)] + [InlineData("en-US", "4.2 Gy", AbsorbedDoseOfIonizingRadiationUnit.Gray, 4.2)] + [InlineData("en-US", "4.2 kGy", AbsorbedDoseOfIonizingRadiationUnit.Kilogray, 4.2)] + [InlineData("en-US", "4.2 krad", AbsorbedDoseOfIonizingRadiationUnit.Kilorad, 4.2)] + [InlineData("en-US", "4.2 MGy", AbsorbedDoseOfIonizingRadiationUnit.Megagray, 4.2)] + [InlineData("en-US", "4.2 Mrad", AbsorbedDoseOfIonizingRadiationUnit.Megarad, 4.2)] + [InlineData("en-US", "4.2 µGy", AbsorbedDoseOfIonizingRadiationUnit.Microgray, 4.2)] + [InlineData("en-US", "4.2 mGy", AbsorbedDoseOfIonizingRadiationUnit.Milligray, 4.2)] + [InlineData("en-US", "4.2 mrad", AbsorbedDoseOfIonizingRadiationUnit.Millirad, 4.2)] + [InlineData("en-US", "4.2 nGy", AbsorbedDoseOfIonizingRadiationUnit.Nanogray, 4.2)] + [InlineData("en-US", "4.2 PGy", AbsorbedDoseOfIonizingRadiationUnit.Petagray, 4.2)] + [InlineData("en-US", "4.2 pGy", AbsorbedDoseOfIonizingRadiationUnit.Picogray, 4.2)] + [InlineData("en-US", "4.2 rad", AbsorbedDoseOfIonizingRadiationUnit.Rad, 4.2)] + [InlineData("en-US", "4.2 TGy", AbsorbedDoseOfIonizingRadiationUnit.Teragray, 4.2)] + [InlineData("ru-RU", "4,2 сГр", AbsorbedDoseOfIonizingRadiationUnit.Centigray, 4.2)] + [InlineData("ru-RU", "4,2 фГр", AbsorbedDoseOfIonizingRadiationUnit.Femtogray, 4.2)] + [InlineData("ru-RU", "4,2 ГГр", AbsorbedDoseOfIonizingRadiationUnit.Gigagray, 4.2)] + [InlineData("ru-RU", "4,2 Гр", AbsorbedDoseOfIonizingRadiationUnit.Gray, 4.2)] + [InlineData("ru-RU", "4,2 кГр", AbsorbedDoseOfIonizingRadiationUnit.Kilogray, 4.2)] + [InlineData("ru-RU", "4,2 крад", AbsorbedDoseOfIonizingRadiationUnit.Kilorad, 4.2)] + [InlineData("ru-RU", "4,2 МГр", AbsorbedDoseOfIonizingRadiationUnit.Megagray, 4.2)] + [InlineData("ru-RU", "4,2 Мрад", AbsorbedDoseOfIonizingRadiationUnit.Megarad, 4.2)] + [InlineData("ru-RU", "4,2 мкГр", AbsorbedDoseOfIonizingRadiationUnit.Microgray, 4.2)] + [InlineData("ru-RU", "4,2 мГр", AbsorbedDoseOfIonizingRadiationUnit.Milligray, 4.2)] + [InlineData("ru-RU", "4,2 мрад", AbsorbedDoseOfIonizingRadiationUnit.Millirad, 4.2)] + [InlineData("ru-RU", "4,2 нГр", AbsorbedDoseOfIonizingRadiationUnit.Nanogray, 4.2)] + [InlineData("ru-RU", "4,2 ПГр", AbsorbedDoseOfIonizingRadiationUnit.Petagray, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 cGy", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Centigrays, CentigraysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Centigray, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 сГр", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Centigrays, CentigraysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Centigray, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 fGy", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Femtograys, FemtograysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Femtogray, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 фГр", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Femtograys, FemtograysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Femtogray, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 GGy", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Gigagrays, GigagraysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Gigagray, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 ГГр", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Gigagrays, GigagraysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Gigagray, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 Gy", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Grays, GraysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Gray, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 Гр", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Grays, GraysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Gray, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 kGy", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilograys, KilograysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Kilogray, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 кГр", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Kilograys, KilograysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Kilogray, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 krad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilorads, KiloradsTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Kilorad, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 крад", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Kilorads, KiloradsTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Kilorad, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 MGy", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megagrays, MegagraysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Megagray, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 МГр", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Megagrays, MegagraysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Megagray, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 Mrad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megarads, MegaradsTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Megarad, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 Мрад", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Megarads, MegaradsTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Megarad, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 µGy", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Micrograys, MicrograysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Microgray, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 мкГр", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Micrograys, MicrograysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Microgray, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 mGy", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Milligrays, MilligraysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Milligray, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 мГр", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Milligrays, MilligraysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Milligray, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 mrad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millirads, MilliradsTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Millirad, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 мрад", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Millirads, MilliradsTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Millirad, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 nGy", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanograys, NanograysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Nanogray, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 нГр", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Nanograys, NanograysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Nanogray, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 PGy", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Petagrays, PetagraysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Petagray, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 ПГр", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Petagrays, PetagraysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Petagray, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 pGy", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Picograys, PicograysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Picogray, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 пГр", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Picograys, PicograysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Picogray, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 rad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Rads, RadsTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Rad, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 рад", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Rads, RadsTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Rad, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 TGy", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Teragrays, TeragraysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Teragray, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AbsorbedDoseOfIonizingRadiation.Parse("1 ТГр", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Teragrays, TeragraysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Teragray, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = AbsorbedDoseOfIonizingRadiation.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 cGy", AbsorbedDoseOfIonizingRadiationUnit.Centigray, 4.2)] + [InlineData("en-US", "4.2 fGy", AbsorbedDoseOfIonizingRadiationUnit.Femtogray, 4.2)] + [InlineData("en-US", "4.2 GGy", AbsorbedDoseOfIonizingRadiationUnit.Gigagray, 4.2)] + [InlineData("en-US", "4.2 Gy", AbsorbedDoseOfIonizingRadiationUnit.Gray, 4.2)] + [InlineData("en-US", "4.2 kGy", AbsorbedDoseOfIonizingRadiationUnit.Kilogray, 4.2)] + [InlineData("en-US", "4.2 krad", AbsorbedDoseOfIonizingRadiationUnit.Kilorad, 4.2)] + [InlineData("en-US", "4.2 MGy", AbsorbedDoseOfIonizingRadiationUnit.Megagray, 4.2)] + [InlineData("en-US", "4.2 Mrad", AbsorbedDoseOfIonizingRadiationUnit.Megarad, 4.2)] + [InlineData("en-US", "4.2 µGy", AbsorbedDoseOfIonizingRadiationUnit.Microgray, 4.2)] + [InlineData("en-US", "4.2 mGy", AbsorbedDoseOfIonizingRadiationUnit.Milligray, 4.2)] + [InlineData("en-US", "4.2 mrad", AbsorbedDoseOfIonizingRadiationUnit.Millirad, 4.2)] + [InlineData("en-US", "4.2 nGy", AbsorbedDoseOfIonizingRadiationUnit.Nanogray, 4.2)] + [InlineData("en-US", "4.2 PGy", AbsorbedDoseOfIonizingRadiationUnit.Petagray, 4.2)] + [InlineData("en-US", "4.2 pGy", AbsorbedDoseOfIonizingRadiationUnit.Picogray, 4.2)] + [InlineData("en-US", "4.2 rad", AbsorbedDoseOfIonizingRadiationUnit.Rad, 4.2)] + [InlineData("en-US", "4.2 TGy", AbsorbedDoseOfIonizingRadiationUnit.Teragray, 4.2)] + [InlineData("ru-RU", "4,2 сГр", AbsorbedDoseOfIonizingRadiationUnit.Centigray, 4.2)] + [InlineData("ru-RU", "4,2 фГр", AbsorbedDoseOfIonizingRadiationUnit.Femtogray, 4.2)] + [InlineData("ru-RU", "4,2 ГГр", AbsorbedDoseOfIonizingRadiationUnit.Gigagray, 4.2)] + [InlineData("ru-RU", "4,2 Гр", AbsorbedDoseOfIonizingRadiationUnit.Gray, 4.2)] + [InlineData("ru-RU", "4,2 кГр", AbsorbedDoseOfIonizingRadiationUnit.Kilogray, 4.2)] + [InlineData("ru-RU", "4,2 крад", AbsorbedDoseOfIonizingRadiationUnit.Kilorad, 4.2)] + [InlineData("ru-RU", "4,2 МГр", AbsorbedDoseOfIonizingRadiationUnit.Megagray, 4.2)] + [InlineData("ru-RU", "4,2 Мрад", AbsorbedDoseOfIonizingRadiationUnit.Megarad, 4.2)] + [InlineData("ru-RU", "4,2 мкГр", AbsorbedDoseOfIonizingRadiationUnit.Microgray, 4.2)] + [InlineData("ru-RU", "4,2 мГр", AbsorbedDoseOfIonizingRadiationUnit.Milligray, 4.2)] + [InlineData("ru-RU", "4,2 мрад", AbsorbedDoseOfIonizingRadiationUnit.Millirad, 4.2)] + [InlineData("ru-RU", "4,2 нГр", AbsorbedDoseOfIonizingRadiationUnit.Nanogray, 4.2)] + [InlineData("ru-RU", "4,2 ПГр", AbsorbedDoseOfIonizingRadiationUnit.Petagray, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(AbsorbedDoseOfIonizingRadiation.TryParse("1 cGy", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Centigrays, CentigraysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Centigray, parsed.Unit); - } - - { - Assert.True(AbsorbedDoseOfIonizingRadiation.TryParse("1 сГр", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Centigrays, CentigraysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Centigray, parsed.Unit); - } - - { - Assert.True(AbsorbedDoseOfIonizingRadiation.TryParse("1 fGy", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Femtograys, FemtograysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Femtogray, parsed.Unit); - } - - { - Assert.True(AbsorbedDoseOfIonizingRadiation.TryParse("1 фГр", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Femtograys, FemtograysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Femtogray, parsed.Unit); - } - - { - Assert.True(AbsorbedDoseOfIonizingRadiation.TryParse("1 GGy", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gigagrays, GigagraysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Gigagray, parsed.Unit); - } - - { - Assert.True(AbsorbedDoseOfIonizingRadiation.TryParse("1 ГГр", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gigagrays, GigagraysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Gigagray, parsed.Unit); - } - - { - Assert.True(AbsorbedDoseOfIonizingRadiation.TryParse("1 Gy", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Grays, GraysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Gray, parsed.Unit); - } - - { - Assert.True(AbsorbedDoseOfIonizingRadiation.TryParse("1 Гр", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Grays, GraysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Gray, parsed.Unit); - } - - { - Assert.True(AbsorbedDoseOfIonizingRadiation.TryParse("1 kGy", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilograys, KilograysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Kilogray, parsed.Unit); - } - - { - Assert.True(AbsorbedDoseOfIonizingRadiation.TryParse("1 кГр", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilograys, KilograysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Kilogray, parsed.Unit); - } - - { - Assert.True(AbsorbedDoseOfIonizingRadiation.TryParse("1 krad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilorads, KiloradsTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Kilorad, parsed.Unit); - } - - { - Assert.True(AbsorbedDoseOfIonizingRadiation.TryParse("1 крад", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilorads, KiloradsTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Kilorad, parsed.Unit); - } - - { - Assert.True(AbsorbedDoseOfIonizingRadiation.TryParse("1 µGy", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Micrograys, MicrograysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Microgray, parsed.Unit); - } - - { - Assert.True(AbsorbedDoseOfIonizingRadiation.TryParse("1 мкГр", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Micrograys, MicrograysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Microgray, parsed.Unit); - } - - { - Assert.True(AbsorbedDoseOfIonizingRadiation.TryParse("1 nGy", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanograys, NanograysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Nanogray, parsed.Unit); - } - - { - Assert.True(AbsorbedDoseOfIonizingRadiation.TryParse("1 нГр", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanograys, NanograysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Nanogray, parsed.Unit); - } - - { - Assert.True(AbsorbedDoseOfIonizingRadiation.TryParse("1 rad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Rads, RadsTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Rad, parsed.Unit); - } - - { - Assert.True(AbsorbedDoseOfIonizingRadiation.TryParse("1 рад", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Rads, RadsTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Rad, parsed.Unit); - } - - { - Assert.True(AbsorbedDoseOfIonizingRadiation.TryParse("1 TGy", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Teragrays, TeragraysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Teragray, parsed.Unit); - } - - { - Assert.True(AbsorbedDoseOfIonizingRadiation.TryParse("1 ТГр", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Teragrays, TeragraysTolerance); - Assert.Equal(AbsorbedDoseOfIonizingRadiationUnit.Teragray, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(AbsorbedDoseOfIonizingRadiation.TryParse(quantityString, out AbsorbedDoseOfIonizingRadiation parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -1029,6 +775,58 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Absorb Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", AbsorbedDoseOfIonizingRadiationUnit.Centigray, "cGy")] + [InlineData("en-US", AbsorbedDoseOfIonizingRadiationUnit.Femtogray, "fGy")] + [InlineData("en-US", AbsorbedDoseOfIonizingRadiationUnit.Gigagray, "GGy")] + [InlineData("en-US", AbsorbedDoseOfIonizingRadiationUnit.Gray, "Gy")] + [InlineData("en-US", AbsorbedDoseOfIonizingRadiationUnit.Kilogray, "kGy")] + [InlineData("en-US", AbsorbedDoseOfIonizingRadiationUnit.Kilorad, "krad")] + [InlineData("en-US", AbsorbedDoseOfIonizingRadiationUnit.Megagray, "MGy")] + [InlineData("en-US", AbsorbedDoseOfIonizingRadiationUnit.Megarad, "Mrad")] + [InlineData("en-US", AbsorbedDoseOfIonizingRadiationUnit.Microgray, "µGy")] + [InlineData("en-US", AbsorbedDoseOfIonizingRadiationUnit.Milligray, "mGy")] + [InlineData("en-US", AbsorbedDoseOfIonizingRadiationUnit.Millirad, "mrad")] + [InlineData("en-US", AbsorbedDoseOfIonizingRadiationUnit.Nanogray, "nGy")] + [InlineData("en-US", AbsorbedDoseOfIonizingRadiationUnit.Petagray, "PGy")] + [InlineData("en-US", AbsorbedDoseOfIonizingRadiationUnit.Picogray, "pGy")] + [InlineData("en-US", AbsorbedDoseOfIonizingRadiationUnit.Rad, "rad")] + [InlineData("en-US", AbsorbedDoseOfIonizingRadiationUnit.Teragray, "TGy")] + [InlineData("ru-RU", AbsorbedDoseOfIonizingRadiationUnit.Centigray, "сГр")] + [InlineData("ru-RU", AbsorbedDoseOfIonizingRadiationUnit.Femtogray, "фГр")] + [InlineData("ru-RU", AbsorbedDoseOfIonizingRadiationUnit.Gigagray, "ГГр")] + [InlineData("ru-RU", AbsorbedDoseOfIonizingRadiationUnit.Gray, "Гр")] + [InlineData("ru-RU", AbsorbedDoseOfIonizingRadiationUnit.Kilogray, "кГр")] + [InlineData("ru-RU", AbsorbedDoseOfIonizingRadiationUnit.Kilorad, "крад")] + [InlineData("ru-RU", AbsorbedDoseOfIonizingRadiationUnit.Megagray, "МГр")] + [InlineData("ru-RU", AbsorbedDoseOfIonizingRadiationUnit.Megarad, "Мрад")] + [InlineData("ru-RU", AbsorbedDoseOfIonizingRadiationUnit.Microgray, "мкГр")] + [InlineData("ru-RU", AbsorbedDoseOfIonizingRadiationUnit.Milligray, "мГр")] + [InlineData("ru-RU", AbsorbedDoseOfIonizingRadiationUnit.Millirad, "мрад")] + [InlineData("ru-RU", AbsorbedDoseOfIonizingRadiationUnit.Nanogray, "нГр")] + [InlineData("ru-RU", AbsorbedDoseOfIonizingRadiationUnit.Petagray, "ПГр")] + [InlineData("ru-RU", AbsorbedDoseOfIonizingRadiationUnit.Picogray, "пГр")] + [InlineData("ru-RU", AbsorbedDoseOfIonizingRadiationUnit.Rad, "рад")] + [InlineData("ru-RU", AbsorbedDoseOfIonizingRadiationUnit.Teragray, "ТГр")] + public void GetAbbreviationForCulture(string culture, AbsorbedDoseOfIonizingRadiationUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = AbsorbedDoseOfIonizingRadiation.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(AbsorbedDoseOfIonizingRadiation.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = AbsorbedDoseOfIonizingRadiation.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(AbsorbedDoseOfIonizingRadiationUnit unit) @@ -1059,6 +857,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); }); } @@ -1082,47 +881,49 @@ 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.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.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] @@ -1168,8 +969,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); @@ -1206,23 +1005,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = AbsorbedDoseOfIonizingRadiation.FromGrays(1); - Assert.True(v.Equals(AbsorbedDoseOfIonizingRadiation.FromGrays(1), GraysTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(AbsorbedDoseOfIonizingRadiation.Zero, GraysTolerance, ComparisonType.Relative)); - Assert.True(AbsorbedDoseOfIonizingRadiation.FromGrays(100).Equals(AbsorbedDoseOfIonizingRadiation.FromGrays(120), 0.3, ComparisonType.Relative)); - Assert.False(AbsorbedDoseOfIonizingRadiation.FromGrays(100).Equals(AbsorbedDoseOfIonizingRadiation.FromGrays(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = AbsorbedDoseOfIonizingRadiation.FromGrays(1); - Assert.Throws(() => v.Equals(AbsorbedDoseOfIonizingRadiation.FromGrays(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1237,6 +1019,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(gray.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = AbsorbedDoseOfIonizingRadiation.FromGrays(1); + var negativeTolerance = AbsorbedDoseOfIonizingRadiation.FromGrays(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1253,6 +1061,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() { @@ -1341,158 +1161,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = AbsorbedDoseOfIonizingRadiation.FromGrays(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = AbsorbedDoseOfIonizingRadiation.FromGrays(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = AbsorbedDoseOfIonizingRadiation.FromGrays(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = AbsorbedDoseOfIonizingRadiation.FromGrays(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = AbsorbedDoseOfIonizingRadiation.FromGrays(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = AbsorbedDoseOfIonizingRadiation.FromGrays(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = AbsorbedDoseOfIonizingRadiation.FromGrays(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = AbsorbedDoseOfIonizingRadiation.FromGrays(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = AbsorbedDoseOfIonizingRadiation.FromGrays(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = AbsorbedDoseOfIonizingRadiation.FromGrays(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = AbsorbedDoseOfIonizingRadiation.FromGrays(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = AbsorbedDoseOfIonizingRadiation.FromGrays(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = AbsorbedDoseOfIonizingRadiation.FromGrays(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = AbsorbedDoseOfIonizingRadiation.FromGrays(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = AbsorbedDoseOfIonizingRadiation.FromGrays(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = AbsorbedDoseOfIonizingRadiation.FromGrays(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(AbsorbedDoseOfIonizingRadiation))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = AbsorbedDoseOfIonizingRadiation.FromGrays(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(AbsorbedDoseOfIonizingRadiationUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = AbsorbedDoseOfIonizingRadiation.FromGrays(1.0); - Assert.Equal(AbsorbedDoseOfIonizingRadiation.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = AbsorbedDoseOfIonizingRadiation.FromGrays(1.0); - Assert.Equal(AbsorbedDoseOfIonizingRadiation.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = AbsorbedDoseOfIonizingRadiation.FromGrays(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = AbsorbedDoseOfIonizingRadiation.FromGrays(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = AbsorbedDoseOfIonizingRadiation.FromGrays(1.0); - Assert.Equal(new {AbsorbedDoseOfIonizingRadiation.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 7ac9d92590..b7cbe1baa6 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AccelerationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AccelerationTestsBase.g.cs @@ -148,7 +148,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Acceleration(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -161,15 +161,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Acceleration_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + AccelerationUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Acceleration(1, AccelerationUnit.MeterPerSecondSquared); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Acceleration.Zero, quantityInfo.Zero); Assert.Equal("Acceleration", quantityInfo.Name); + Assert.Equal(Acceleration.Zero, quantityInfo.Zero); + Assert.Equal(Acceleration.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Acceleration.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -196,59 +214,59 @@ public void MeterPerSecondSquaredToAccelerationUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Acceleration.From(1, AccelerationUnit.CentimeterPerSecondSquared); - AssertEx.EqualTolerance(1, quantity00.CentimetersPerSecondSquared, CentimetersPerSecondSquaredTolerance); + Assert.Equal(1, quantity00.CentimetersPerSecondSquared); Assert.Equal(AccelerationUnit.CentimeterPerSecondSquared, quantity00.Unit); var quantity01 = Acceleration.From(1, AccelerationUnit.DecimeterPerSecondSquared); - AssertEx.EqualTolerance(1, quantity01.DecimetersPerSecondSquared, DecimetersPerSecondSquaredTolerance); + Assert.Equal(1, quantity01.DecimetersPerSecondSquared); Assert.Equal(AccelerationUnit.DecimeterPerSecondSquared, quantity01.Unit); var quantity02 = Acceleration.From(1, AccelerationUnit.FootPerSecondSquared); - AssertEx.EqualTolerance(1, quantity02.FeetPerSecondSquared, FeetPerSecondSquaredTolerance); + Assert.Equal(1, quantity02.FeetPerSecondSquared); Assert.Equal(AccelerationUnit.FootPerSecondSquared, quantity02.Unit); var quantity03 = Acceleration.From(1, AccelerationUnit.InchPerSecondSquared); - AssertEx.EqualTolerance(1, quantity03.InchesPerSecondSquared, InchesPerSecondSquaredTolerance); + Assert.Equal(1, quantity03.InchesPerSecondSquared); Assert.Equal(AccelerationUnit.InchPerSecondSquared, quantity03.Unit); var quantity04 = Acceleration.From(1, AccelerationUnit.KilometerPerSecondSquared); - AssertEx.EqualTolerance(1, quantity04.KilometersPerSecondSquared, KilometersPerSecondSquaredTolerance); + Assert.Equal(1, quantity04.KilometersPerSecondSquared); Assert.Equal(AccelerationUnit.KilometerPerSecondSquared, quantity04.Unit); var quantity05 = Acceleration.From(1, AccelerationUnit.KnotPerHour); - AssertEx.EqualTolerance(1, quantity05.KnotsPerHour, KnotsPerHourTolerance); + Assert.Equal(1, quantity05.KnotsPerHour); Assert.Equal(AccelerationUnit.KnotPerHour, quantity05.Unit); var quantity06 = Acceleration.From(1, AccelerationUnit.KnotPerMinute); - AssertEx.EqualTolerance(1, quantity06.KnotsPerMinute, KnotsPerMinuteTolerance); + Assert.Equal(1, quantity06.KnotsPerMinute); Assert.Equal(AccelerationUnit.KnotPerMinute, quantity06.Unit); var quantity07 = Acceleration.From(1, AccelerationUnit.KnotPerSecond); - AssertEx.EqualTolerance(1, quantity07.KnotsPerSecond, KnotsPerSecondTolerance); + Assert.Equal(1, quantity07.KnotsPerSecond); Assert.Equal(AccelerationUnit.KnotPerSecond, quantity07.Unit); var quantity08 = Acceleration.From(1, AccelerationUnit.MeterPerSecondSquared); - AssertEx.EqualTolerance(1, quantity08.MetersPerSecondSquared, MetersPerSecondSquaredTolerance); + Assert.Equal(1, quantity08.MetersPerSecondSquared); Assert.Equal(AccelerationUnit.MeterPerSecondSquared, quantity08.Unit); var quantity09 = Acceleration.From(1, AccelerationUnit.MicrometerPerSecondSquared); - AssertEx.EqualTolerance(1, quantity09.MicrometersPerSecondSquared, MicrometersPerSecondSquaredTolerance); + Assert.Equal(1, quantity09.MicrometersPerSecondSquared); Assert.Equal(AccelerationUnit.MicrometerPerSecondSquared, quantity09.Unit); var quantity10 = Acceleration.From(1, AccelerationUnit.MillimeterPerSecondSquared); - AssertEx.EqualTolerance(1, quantity10.MillimetersPerSecondSquared, MillimetersPerSecondSquaredTolerance); + Assert.Equal(1, quantity10.MillimetersPerSecondSquared); Assert.Equal(AccelerationUnit.MillimeterPerSecondSquared, quantity10.Unit); var quantity11 = Acceleration.From(1, AccelerationUnit.MillistandardGravity); - AssertEx.EqualTolerance(1, quantity11.MillistandardGravity, MillistandardGravityTolerance); + Assert.Equal(1, quantity11.MillistandardGravity); Assert.Equal(AccelerationUnit.MillistandardGravity, quantity11.Unit); var quantity12 = Acceleration.From(1, AccelerationUnit.NanometerPerSecondSquared); - AssertEx.EqualTolerance(1, quantity12.NanometersPerSecondSquared, NanometersPerSecondSquaredTolerance); + Assert.Equal(1, quantity12.NanometersPerSecondSquared); Assert.Equal(AccelerationUnit.NanometerPerSecondSquared, quantity12.Unit); var quantity13 = Acceleration.From(1, AccelerationUnit.StandardGravity); - AssertEx.EqualTolerance(1, quantity13.StandardGravity, StandardGravityTolerance); + Assert.Equal(1, quantity13.StandardGravity); Assert.Equal(AccelerationUnit.StandardGravity, quantity13.Unit); } @@ -397,378 +415,78 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 cm/s²", AccelerationUnit.CentimeterPerSecondSquared, 4.2)] + [InlineData("en-US", "4.2 dm/s²", AccelerationUnit.DecimeterPerSecondSquared, 4.2)] + [InlineData("en-US", "4.2 ft/s²", AccelerationUnit.FootPerSecondSquared, 4.2)] + [InlineData("en-US", "4.2 in/s²", AccelerationUnit.InchPerSecondSquared, 4.2)] + [InlineData("en-US", "4.2 km/s²", AccelerationUnit.KilometerPerSecondSquared, 4.2)] + [InlineData("en-US", "4.2 kn/h", AccelerationUnit.KnotPerHour, 4.2)] + [InlineData("en-US", "4.2 kn/min", AccelerationUnit.KnotPerMinute, 4.2)] + [InlineData("en-US", "4.2 kn/s", AccelerationUnit.KnotPerSecond, 4.2)] + [InlineData("en-US", "4.2 m/s²", AccelerationUnit.MeterPerSecondSquared, 4.2)] + [InlineData("en-US", "4.2 µm/s²", AccelerationUnit.MicrometerPerSecondSquared, 4.2)] + [InlineData("en-US", "4.2 mm/s²", AccelerationUnit.MillimeterPerSecondSquared, 4.2)] + [InlineData("en-US", "4.2 mg", AccelerationUnit.MillistandardGravity, 4.2)] + [InlineData("en-US", "4.2 nm/s²", AccelerationUnit.NanometerPerSecondSquared, 4.2)] + [InlineData("en-US", "4.2 g", AccelerationUnit.StandardGravity, 4.2)] + [InlineData("ru-RU", "4,2 см/с²", AccelerationUnit.CentimeterPerSecondSquared, 4.2)] + [InlineData("ru-RU", "4,2 дм/с²", AccelerationUnit.DecimeterPerSecondSquared, 4.2)] + [InlineData("ru-RU", "4,2 фут/с²", AccelerationUnit.FootPerSecondSquared, 4.2)] + [InlineData("ru-RU", "4,2 дюйм/с²", AccelerationUnit.InchPerSecondSquared, 4.2)] + [InlineData("ru-RU", "4,2 км/с²", AccelerationUnit.KilometerPerSecondSquared, 4.2)] + [InlineData("ru-RU", "4,2 узел/час", AccelerationUnit.KnotPerHour, 4.2)] + [InlineData("ru-RU", "4,2 узел/мин", AccelerationUnit.KnotPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 узел/с", AccelerationUnit.KnotPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 м/с²", AccelerationUnit.MeterPerSecondSquared, 4.2)] + [InlineData("ru-RU", "4,2 мкм/с²", AccelerationUnit.MicrometerPerSecondSquared, 4.2)] + [InlineData("ru-RU", "4,2 мм/с²", AccelerationUnit.MillimeterPerSecondSquared, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = Acceleration.Parse("1 cm/s²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentimetersPerSecondSquared, CentimetersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.CentimeterPerSecondSquared, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Acceleration.Parse("1 см/с²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CentimetersPerSecondSquared, CentimetersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.CentimeterPerSecondSquared, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Acceleration.Parse("1 dm/s²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecimetersPerSecondSquared, DecimetersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.DecimeterPerSecondSquared, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Acceleration.Parse("1 дм/с²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.DecimetersPerSecondSquared, DecimetersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.DecimeterPerSecondSquared, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Acceleration.Parse("1 ft/s²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.FeetPerSecondSquared, FeetPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.FootPerSecondSquared, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Acceleration.Parse("1 фут/с²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.FeetPerSecondSquared, FeetPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.FootPerSecondSquared, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Acceleration.Parse("1 in/s²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InchesPerSecondSquared, InchesPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.InchPerSecondSquared, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Acceleration.Parse("1 дюйм/с²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.InchesPerSecondSquared, InchesPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.InchPerSecondSquared, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Acceleration.Parse("1 km/s²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilometersPerSecondSquared, KilometersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.KilometerPerSecondSquared, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Acceleration.Parse("1 км/с²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilometersPerSecondSquared, KilometersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.KilometerPerSecondSquared, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Acceleration.Parse("1 kn/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KnotsPerHour, KnotsPerHourTolerance); - Assert.Equal(AccelerationUnit.KnotPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Acceleration.Parse("1 узел/час", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KnotsPerHour, KnotsPerHourTolerance); - Assert.Equal(AccelerationUnit.KnotPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Acceleration.Parse("1 kn/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KnotsPerMinute, KnotsPerMinuteTolerance); - Assert.Equal(AccelerationUnit.KnotPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Acceleration.Parse("1 узел/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KnotsPerMinute, KnotsPerMinuteTolerance); - Assert.Equal(AccelerationUnit.KnotPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Acceleration.Parse("1 kn/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KnotsPerSecond, KnotsPerSecondTolerance); - Assert.Equal(AccelerationUnit.KnotPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Acceleration.Parse("1 узел/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KnotsPerSecond, KnotsPerSecondTolerance); - Assert.Equal(AccelerationUnit.KnotPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Acceleration.Parse("1 m/s²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MetersPerSecondSquared, MetersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.MeterPerSecondSquared, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Acceleration.Parse("1 м/с²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MetersPerSecondSquared, MetersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.MeterPerSecondSquared, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Acceleration.Parse("1 µm/s²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrometersPerSecondSquared, MicrometersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.MicrometerPerSecondSquared, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Acceleration.Parse("1 мкм/с²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MicrometersPerSecondSquared, MicrometersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.MicrometerPerSecondSquared, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Acceleration.Parse("1 mm/s²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillimetersPerSecondSquared, MillimetersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.MillimeterPerSecondSquared, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Acceleration.Parse("1 мм/с²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MillimetersPerSecondSquared, MillimetersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.MillimeterPerSecondSquared, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Acceleration.Parse("1 mg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillistandardGravity, MillistandardGravityTolerance); - Assert.Equal(AccelerationUnit.MillistandardGravity, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Acceleration.Parse("1 мg", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MillistandardGravity, MillistandardGravityTolerance); - Assert.Equal(AccelerationUnit.MillistandardGravity, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Acceleration.Parse("1 nm/s²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanometersPerSecondSquared, NanometersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.NanometerPerSecondSquared, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Acceleration.Parse("1 нм/с²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.NanometersPerSecondSquared, NanometersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.NanometerPerSecondSquared, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Acceleration.Parse("1 g", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.StandardGravity, StandardGravityTolerance); - Assert.Equal(AccelerationUnit.StandardGravity, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Acceleration.Parse("1 g", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.StandardGravity, StandardGravityTolerance); - Assert.Equal(AccelerationUnit.StandardGravity, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Acceleration.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 cm/s²", AccelerationUnit.CentimeterPerSecondSquared, 4.2)] + [InlineData("en-US", "4.2 dm/s²", AccelerationUnit.DecimeterPerSecondSquared, 4.2)] + [InlineData("en-US", "4.2 ft/s²", AccelerationUnit.FootPerSecondSquared, 4.2)] + [InlineData("en-US", "4.2 in/s²", AccelerationUnit.InchPerSecondSquared, 4.2)] + [InlineData("en-US", "4.2 km/s²", AccelerationUnit.KilometerPerSecondSquared, 4.2)] + [InlineData("en-US", "4.2 kn/h", AccelerationUnit.KnotPerHour, 4.2)] + [InlineData("en-US", "4.2 kn/min", AccelerationUnit.KnotPerMinute, 4.2)] + [InlineData("en-US", "4.2 kn/s", AccelerationUnit.KnotPerSecond, 4.2)] + [InlineData("en-US", "4.2 m/s²", AccelerationUnit.MeterPerSecondSquared, 4.2)] + [InlineData("en-US", "4.2 µm/s²", AccelerationUnit.MicrometerPerSecondSquared, 4.2)] + [InlineData("en-US", "4.2 mm/s²", AccelerationUnit.MillimeterPerSecondSquared, 4.2)] + [InlineData("en-US", "4.2 mg", AccelerationUnit.MillistandardGravity, 4.2)] + [InlineData("en-US", "4.2 nm/s²", AccelerationUnit.NanometerPerSecondSquared, 4.2)] + [InlineData("en-US", "4.2 g", AccelerationUnit.StandardGravity, 4.2)] + [InlineData("ru-RU", "4,2 см/с²", AccelerationUnit.CentimeterPerSecondSquared, 4.2)] + [InlineData("ru-RU", "4,2 дм/с²", AccelerationUnit.DecimeterPerSecondSquared, 4.2)] + [InlineData("ru-RU", "4,2 фут/с²", AccelerationUnit.FootPerSecondSquared, 4.2)] + [InlineData("ru-RU", "4,2 дюйм/с²", AccelerationUnit.InchPerSecondSquared, 4.2)] + [InlineData("ru-RU", "4,2 км/с²", AccelerationUnit.KilometerPerSecondSquared, 4.2)] + [InlineData("ru-RU", "4,2 узел/час", AccelerationUnit.KnotPerHour, 4.2)] + [InlineData("ru-RU", "4,2 узел/мин", AccelerationUnit.KnotPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 узел/с", AccelerationUnit.KnotPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 м/с²", AccelerationUnit.MeterPerSecondSquared, 4.2)] + [InlineData("ru-RU", "4,2 мкм/с²", AccelerationUnit.MicrometerPerSecondSquared, 4.2)] + [InlineData("ru-RU", "4,2 мм/с²", AccelerationUnit.MillimeterPerSecondSquared, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(Acceleration.TryParse("1 cm/s²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentimetersPerSecondSquared, CentimetersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.CentimeterPerSecondSquared, parsed.Unit); - } - - { - Assert.True(Acceleration.TryParse("1 см/с²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentimetersPerSecondSquared, CentimetersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.CentimeterPerSecondSquared, parsed.Unit); - } - - { - Assert.True(Acceleration.TryParse("1 dm/s²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecimetersPerSecondSquared, DecimetersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.DecimeterPerSecondSquared, parsed.Unit); - } - - { - Assert.True(Acceleration.TryParse("1 дм/с²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecimetersPerSecondSquared, DecimetersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.DecimeterPerSecondSquared, parsed.Unit); - } - - { - Assert.True(Acceleration.TryParse("1 ft/s²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.FeetPerSecondSquared, FeetPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.FootPerSecondSquared, parsed.Unit); - } - - { - Assert.True(Acceleration.TryParse("1 фут/с²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.FeetPerSecondSquared, FeetPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.FootPerSecondSquared, parsed.Unit); - } - - { - Assert.True(Acceleration.TryParse("1 in/s²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InchesPerSecondSquared, InchesPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.InchPerSecondSquared, parsed.Unit); - } - - { - Assert.True(Acceleration.TryParse("1 дюйм/с²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InchesPerSecondSquared, InchesPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.InchPerSecondSquared, parsed.Unit); - } - - { - Assert.True(Acceleration.TryParse("1 km/s²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilometersPerSecondSquared, KilometersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.KilometerPerSecondSquared, parsed.Unit); - } - - { - Assert.True(Acceleration.TryParse("1 км/с²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilometersPerSecondSquared, KilometersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.KilometerPerSecondSquared, parsed.Unit); - } - - { - Assert.True(Acceleration.TryParse("1 kn/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KnotsPerHour, KnotsPerHourTolerance); - Assert.Equal(AccelerationUnit.KnotPerHour, parsed.Unit); - } - - { - Assert.True(Acceleration.TryParse("1 узел/час", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KnotsPerHour, KnotsPerHourTolerance); - Assert.Equal(AccelerationUnit.KnotPerHour, parsed.Unit); - } - - { - Assert.True(Acceleration.TryParse("1 kn/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KnotsPerMinute, KnotsPerMinuteTolerance); - Assert.Equal(AccelerationUnit.KnotPerMinute, parsed.Unit); - } - - { - Assert.True(Acceleration.TryParse("1 узел/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KnotsPerMinute, KnotsPerMinuteTolerance); - Assert.Equal(AccelerationUnit.KnotPerMinute, parsed.Unit); - } - - { - Assert.True(Acceleration.TryParse("1 kn/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KnotsPerSecond, KnotsPerSecondTolerance); - Assert.Equal(AccelerationUnit.KnotPerSecond, parsed.Unit); - } - - { - Assert.True(Acceleration.TryParse("1 узел/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KnotsPerSecond, KnotsPerSecondTolerance); - Assert.Equal(AccelerationUnit.KnotPerSecond, parsed.Unit); - } - - { - Assert.True(Acceleration.TryParse("1 m/s²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetersPerSecondSquared, MetersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.MeterPerSecondSquared, parsed.Unit); - } - - { - Assert.True(Acceleration.TryParse("1 м/с²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetersPerSecondSquared, MetersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.MeterPerSecondSquared, parsed.Unit); - } - - { - Assert.True(Acceleration.TryParse("1 µm/s²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrometersPerSecondSquared, MicrometersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.MicrometerPerSecondSquared, parsed.Unit); - } - - { - Assert.True(Acceleration.TryParse("1 мкм/с²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrometersPerSecondSquared, MicrometersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.MicrometerPerSecondSquared, parsed.Unit); - } - - { - Assert.True(Acceleration.TryParse("1 mm/s²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimetersPerSecondSquared, MillimetersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.MillimeterPerSecondSquared, parsed.Unit); - } - - { - Assert.True(Acceleration.TryParse("1 мм/с²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimetersPerSecondSquared, MillimetersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.MillimeterPerSecondSquared, parsed.Unit); - } - - { - Assert.True(Acceleration.TryParse("1 mg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillistandardGravity, MillistandardGravityTolerance); - Assert.Equal(AccelerationUnit.MillistandardGravity, parsed.Unit); - } - - { - Assert.True(Acceleration.TryParse("1 мg", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillistandardGravity, MillistandardGravityTolerance); - Assert.Equal(AccelerationUnit.MillistandardGravity, parsed.Unit); - } - - { - Assert.True(Acceleration.TryParse("1 nm/s²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanometersPerSecondSquared, NanometersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.NanometerPerSecondSquared, parsed.Unit); - } - - { - Assert.True(Acceleration.TryParse("1 нм/с²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanometersPerSecondSquared, NanometersPerSecondSquaredTolerance); - Assert.Equal(AccelerationUnit.NanometerPerSecondSquared, parsed.Unit); - } - - { - Assert.True(Acceleration.TryParse("1 g", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.StandardGravity, StandardGravityTolerance); - Assert.Equal(AccelerationUnit.StandardGravity, parsed.Unit); - } - - { - Assert.True(Acceleration.TryParse("1 g", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.StandardGravity, StandardGravityTolerance); - Assert.Equal(AccelerationUnit.StandardGravity, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Acceleration.TryParse(quantityString, out Acceleration parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -1005,6 +723,54 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Accele Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", AccelerationUnit.CentimeterPerSecondSquared, "cm/s²")] + [InlineData("en-US", AccelerationUnit.DecimeterPerSecondSquared, "dm/s²")] + [InlineData("en-US", AccelerationUnit.FootPerSecondSquared, "ft/s²")] + [InlineData("en-US", AccelerationUnit.InchPerSecondSquared, "in/s²")] + [InlineData("en-US", AccelerationUnit.KilometerPerSecondSquared, "km/s²")] + [InlineData("en-US", AccelerationUnit.KnotPerHour, "kn/h")] + [InlineData("en-US", AccelerationUnit.KnotPerMinute, "kn/min")] + [InlineData("en-US", AccelerationUnit.KnotPerSecond, "kn/s")] + [InlineData("en-US", AccelerationUnit.MeterPerSecondSquared, "m/s²")] + [InlineData("en-US", AccelerationUnit.MicrometerPerSecondSquared, "µm/s²")] + [InlineData("en-US", AccelerationUnit.MillimeterPerSecondSquared, "mm/s²")] + [InlineData("en-US", AccelerationUnit.MillistandardGravity, "mg")] + [InlineData("en-US", AccelerationUnit.NanometerPerSecondSquared, "nm/s²")] + [InlineData("en-US", AccelerationUnit.StandardGravity, "g")] + [InlineData("ru-RU", AccelerationUnit.CentimeterPerSecondSquared, "см/с²")] + [InlineData("ru-RU", AccelerationUnit.DecimeterPerSecondSquared, "дм/с²")] + [InlineData("ru-RU", AccelerationUnit.FootPerSecondSquared, "фут/с²")] + [InlineData("ru-RU", AccelerationUnit.InchPerSecondSquared, "дюйм/с²")] + [InlineData("ru-RU", AccelerationUnit.KilometerPerSecondSquared, "км/с²")] + [InlineData("ru-RU", AccelerationUnit.KnotPerHour, "узел/час")] + [InlineData("ru-RU", AccelerationUnit.KnotPerMinute, "узел/мин")] + [InlineData("ru-RU", AccelerationUnit.KnotPerSecond, "узел/с")] + [InlineData("ru-RU", AccelerationUnit.MeterPerSecondSquared, "м/с²")] + [InlineData("ru-RU", AccelerationUnit.MicrometerPerSecondSquared, "мкм/с²")] + [InlineData("ru-RU", AccelerationUnit.MillimeterPerSecondSquared, "мм/с²")] + [InlineData("ru-RU", AccelerationUnit.MillistandardGravity, "мg")] + [InlineData("ru-RU", AccelerationUnit.NanometerPerSecondSquared, "нм/с²")] + [InlineData("ru-RU", AccelerationUnit.StandardGravity, "g")] + public void GetAbbreviationForCulture(string culture, AccelerationUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Acceleration.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Acceleration.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Acceleration.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(AccelerationUnit unit) @@ -1035,6 +801,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); }); } @@ -1058,45 +825,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] @@ -1142,8 +911,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); @@ -1180,23 +947,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = Acceleration.FromMetersPerSecondSquared(1); - Assert.True(v.Equals(Acceleration.FromMetersPerSecondSquared(1), MetersPerSecondSquaredTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Acceleration.Zero, MetersPerSecondSquaredTolerance, ComparisonType.Relative)); - Assert.True(Acceleration.FromMetersPerSecondSquared(100).Equals(Acceleration.FromMetersPerSecondSquared(120), 0.3, ComparisonType.Relative)); - Assert.False(Acceleration.FromMetersPerSecondSquared(100).Equals(Acceleration.FromMetersPerSecondSquared(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = Acceleration.FromMetersPerSecondSquared(1); - Assert.Throws(() => v.Equals(Acceleration.FromMetersPerSecondSquared(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1211,6 +961,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(meterpersecondsquared.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = Acceleration.FromMetersPerSecondSquared(1); + var negativeTolerance = Acceleration.FromMetersPerSecondSquared(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1227,6 +1003,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() { @@ -1311,158 +1099,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Acceleration))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(AccelerationUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal(Acceleration.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal(Acceleration.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal(new {Acceleration.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 8175331fbe..8058666d82 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AmountOfSubstanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AmountOfSubstanceTestsBase.g.cs @@ -160,7 +160,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new AmountOfSubstance(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -173,15 +173,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void AmountOfSubstance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + AmountOfSubstanceUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new AmountOfSubstance(1, AmountOfSubstanceUnit.Mole); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(AmountOfSubstance.Zero, quantityInfo.Zero); Assert.Equal("AmountOfSubstance", quantityInfo.Name); + Assert.Equal(AmountOfSubstance.Zero, quantityInfo.Zero); + Assert.Equal(AmountOfSubstance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(AmountOfSubstance.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void AmountOfSubstanceInfo_CreateWithCustomUnitInfos() + { + AmountOfSubstanceUnit[] expectedUnits = [AmountOfSubstanceUnit.Mole]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -211,71 +229,71 @@ public void MoleToAmountOfSubstanceUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = AmountOfSubstance.From(1, AmountOfSubstanceUnit.Centimole); - AssertEx.EqualTolerance(1, quantity00.Centimoles, CentimolesTolerance); + Assert.Equal(1, quantity00.Centimoles); Assert.Equal(AmountOfSubstanceUnit.Centimole, quantity00.Unit); var quantity01 = AmountOfSubstance.From(1, AmountOfSubstanceUnit.CentipoundMole); - AssertEx.EqualTolerance(1, quantity01.CentipoundMoles, CentipoundMolesTolerance); + Assert.Equal(1, quantity01.CentipoundMoles); Assert.Equal(AmountOfSubstanceUnit.CentipoundMole, quantity01.Unit); var quantity02 = AmountOfSubstance.From(1, AmountOfSubstanceUnit.Decimole); - AssertEx.EqualTolerance(1, quantity02.Decimoles, DecimolesTolerance); + Assert.Equal(1, quantity02.Decimoles); Assert.Equal(AmountOfSubstanceUnit.Decimole, quantity02.Unit); var quantity03 = AmountOfSubstance.From(1, AmountOfSubstanceUnit.DecipoundMole); - AssertEx.EqualTolerance(1, quantity03.DecipoundMoles, DecipoundMolesTolerance); + Assert.Equal(1, quantity03.DecipoundMoles); Assert.Equal(AmountOfSubstanceUnit.DecipoundMole, quantity03.Unit); var quantity04 = AmountOfSubstance.From(1, AmountOfSubstanceUnit.Femtomole); - AssertEx.EqualTolerance(1, quantity04.Femtomoles, FemtomolesTolerance); + Assert.Equal(1, quantity04.Femtomoles); Assert.Equal(AmountOfSubstanceUnit.Femtomole, quantity04.Unit); var quantity05 = AmountOfSubstance.From(1, AmountOfSubstanceUnit.Kilomole); - AssertEx.EqualTolerance(1, quantity05.Kilomoles, KilomolesTolerance); + Assert.Equal(1, quantity05.Kilomoles); Assert.Equal(AmountOfSubstanceUnit.Kilomole, quantity05.Unit); var quantity06 = AmountOfSubstance.From(1, AmountOfSubstanceUnit.KilopoundMole); - AssertEx.EqualTolerance(1, quantity06.KilopoundMoles, KilopoundMolesTolerance); + Assert.Equal(1, quantity06.KilopoundMoles); Assert.Equal(AmountOfSubstanceUnit.KilopoundMole, quantity06.Unit); var quantity07 = AmountOfSubstance.From(1, AmountOfSubstanceUnit.Megamole); - AssertEx.EqualTolerance(1, quantity07.Megamoles, MegamolesTolerance); + Assert.Equal(1, quantity07.Megamoles); Assert.Equal(AmountOfSubstanceUnit.Megamole, quantity07.Unit); var quantity08 = AmountOfSubstance.From(1, AmountOfSubstanceUnit.Micromole); - AssertEx.EqualTolerance(1, quantity08.Micromoles, MicromolesTolerance); + Assert.Equal(1, quantity08.Micromoles); Assert.Equal(AmountOfSubstanceUnit.Micromole, quantity08.Unit); var quantity09 = AmountOfSubstance.From(1, AmountOfSubstanceUnit.MicropoundMole); - AssertEx.EqualTolerance(1, quantity09.MicropoundMoles, MicropoundMolesTolerance); + Assert.Equal(1, quantity09.MicropoundMoles); Assert.Equal(AmountOfSubstanceUnit.MicropoundMole, quantity09.Unit); var quantity10 = AmountOfSubstance.From(1, AmountOfSubstanceUnit.Millimole); - AssertEx.EqualTolerance(1, quantity10.Millimoles, MillimolesTolerance); + Assert.Equal(1, quantity10.Millimoles); Assert.Equal(AmountOfSubstanceUnit.Millimole, quantity10.Unit); var quantity11 = AmountOfSubstance.From(1, AmountOfSubstanceUnit.MillipoundMole); - AssertEx.EqualTolerance(1, quantity11.MillipoundMoles, MillipoundMolesTolerance); + Assert.Equal(1, quantity11.MillipoundMoles); Assert.Equal(AmountOfSubstanceUnit.MillipoundMole, quantity11.Unit); var quantity12 = AmountOfSubstance.From(1, AmountOfSubstanceUnit.Mole); - AssertEx.EqualTolerance(1, quantity12.Moles, MolesTolerance); + Assert.Equal(1, quantity12.Moles); Assert.Equal(AmountOfSubstanceUnit.Mole, quantity12.Unit); var quantity13 = AmountOfSubstance.From(1, AmountOfSubstanceUnit.Nanomole); - AssertEx.EqualTolerance(1, quantity13.Nanomoles, NanomolesTolerance); + Assert.Equal(1, quantity13.Nanomoles); Assert.Equal(AmountOfSubstanceUnit.Nanomole, quantity13.Unit); var quantity14 = AmountOfSubstance.From(1, AmountOfSubstanceUnit.NanopoundMole); - AssertEx.EqualTolerance(1, quantity14.NanopoundMoles, NanopoundMolesTolerance); + Assert.Equal(1, quantity14.NanopoundMoles); Assert.Equal(AmountOfSubstanceUnit.NanopoundMole, quantity14.Unit); var quantity15 = AmountOfSubstance.From(1, AmountOfSubstanceUnit.Picomole); - AssertEx.EqualTolerance(1, quantity15.Picomoles, PicomolesTolerance); + Assert.Equal(1, quantity15.Picomoles); Assert.Equal(AmountOfSubstanceUnit.Picomole, quantity15.Unit); var quantity16 = AmountOfSubstance.From(1, AmountOfSubstanceUnit.PoundMole); - AssertEx.EqualTolerance(1, quantity16.PoundMoles, PoundMolesTolerance); + Assert.Equal(1, quantity16.PoundMoles); Assert.Equal(AmountOfSubstanceUnit.PoundMole, quantity16.Unit); } @@ -427,223 +445,56 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 cmol", AmountOfSubstanceUnit.Centimole, 4.2)] + [InlineData("en-US", "4.2 clbmol", AmountOfSubstanceUnit.CentipoundMole, 4.2)] + [InlineData("en-US", "4.2 dmol", AmountOfSubstanceUnit.Decimole, 4.2)] + [InlineData("en-US", "4.2 dlbmol", AmountOfSubstanceUnit.DecipoundMole, 4.2)] + [InlineData("en-US", "4.2 fmol", AmountOfSubstanceUnit.Femtomole, 4.2)] + [InlineData("en-US", "4.2 kmol", AmountOfSubstanceUnit.Kilomole, 4.2)] + [InlineData("en-US", "4.2 klbmol", AmountOfSubstanceUnit.KilopoundMole, 4.2)] + [InlineData("en-US", "4.2 Mmol", AmountOfSubstanceUnit.Megamole, 4.2)] + [InlineData("en-US", "4.2 µmol", AmountOfSubstanceUnit.Micromole, 4.2)] + [InlineData("en-US", "4.2 µlbmol", AmountOfSubstanceUnit.MicropoundMole, 4.2)] + [InlineData("en-US", "4.2 mmol", AmountOfSubstanceUnit.Millimole, 4.2)] + [InlineData("en-US", "4.2 mlbmol", AmountOfSubstanceUnit.MillipoundMole, 4.2)] + [InlineData("en-US", "4.2 mol", AmountOfSubstanceUnit.Mole, 4.2)] + [InlineData("en-US", "4.2 nmol", AmountOfSubstanceUnit.Nanomole, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = AmountOfSubstance.Parse("1 cmol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Centimoles, CentimolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Centimole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AmountOfSubstance.Parse("1 clbmol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentipoundMoles, CentipoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.CentipoundMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AmountOfSubstance.Parse("1 dmol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Decimoles, DecimolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Decimole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AmountOfSubstance.Parse("1 dlbmol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecipoundMoles, DecipoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.DecipoundMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AmountOfSubstance.Parse("1 fmol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Femtomoles, FemtomolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Femtomole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AmountOfSubstance.Parse("1 kmol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilomoles, KilomolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Kilomole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AmountOfSubstance.Parse("1 klbmol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundMoles, KilopoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.KilopoundMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AmountOfSubstance.Parse("1 Mmol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megamoles, MegamolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Megamole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AmountOfSubstance.Parse("1 µmol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Micromoles, MicromolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Micromole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AmountOfSubstance.Parse("1 µlbmol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicropoundMoles, MicropoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.MicropoundMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AmountOfSubstance.Parse("1 mmol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millimoles, MillimolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Millimole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AmountOfSubstance.Parse("1 mlbmol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillipoundMoles, MillipoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.MillipoundMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AmountOfSubstance.Parse("1 mol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Moles, MolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Mole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AmountOfSubstance.Parse("1 nmol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanomoles, NanomolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Nanomole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AmountOfSubstance.Parse("1 nlbmol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanopoundMoles, NanopoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.NanopoundMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AmountOfSubstance.Parse("1 pmol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Picomoles, PicomolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Picomole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AmountOfSubstance.Parse("1 lbmol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundMoles, PoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.PoundMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = AmountOfSubstance.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 cmol", AmountOfSubstanceUnit.Centimole, 4.2)] + [InlineData("en-US", "4.2 clbmol", AmountOfSubstanceUnit.CentipoundMole, 4.2)] + [InlineData("en-US", "4.2 dmol", AmountOfSubstanceUnit.Decimole, 4.2)] + [InlineData("en-US", "4.2 dlbmol", AmountOfSubstanceUnit.DecipoundMole, 4.2)] + [InlineData("en-US", "4.2 fmol", AmountOfSubstanceUnit.Femtomole, 4.2)] + [InlineData("en-US", "4.2 kmol", AmountOfSubstanceUnit.Kilomole, 4.2)] + [InlineData("en-US", "4.2 klbmol", AmountOfSubstanceUnit.KilopoundMole, 4.2)] + [InlineData("en-US", "4.2 Mmol", AmountOfSubstanceUnit.Megamole, 4.2)] + [InlineData("en-US", "4.2 µmol", AmountOfSubstanceUnit.Micromole, 4.2)] + [InlineData("en-US", "4.2 µlbmol", AmountOfSubstanceUnit.MicropoundMole, 4.2)] + [InlineData("en-US", "4.2 mmol", AmountOfSubstanceUnit.Millimole, 4.2)] + [InlineData("en-US", "4.2 mlbmol", AmountOfSubstanceUnit.MillipoundMole, 4.2)] + [InlineData("en-US", "4.2 mol", AmountOfSubstanceUnit.Mole, 4.2)] + [InlineData("en-US", "4.2 nmol", AmountOfSubstanceUnit.Nanomole, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(AmountOfSubstance.TryParse("1 cmol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Centimoles, CentimolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Centimole, parsed.Unit); - } - - { - Assert.True(AmountOfSubstance.TryParse("1 clbmol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentipoundMoles, CentipoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.CentipoundMole, parsed.Unit); - } - - { - Assert.True(AmountOfSubstance.TryParse("1 dmol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Decimoles, DecimolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Decimole, parsed.Unit); - } - - { - Assert.True(AmountOfSubstance.TryParse("1 dlbmol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecipoundMoles, DecipoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.DecipoundMole, parsed.Unit); - } - - { - Assert.True(AmountOfSubstance.TryParse("1 fmol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Femtomoles, FemtomolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Femtomole, parsed.Unit); - } - - { - Assert.True(AmountOfSubstance.TryParse("1 kmol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilomoles, KilomolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Kilomole, parsed.Unit); - } - - { - Assert.True(AmountOfSubstance.TryParse("1 klbmol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundMoles, KilopoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.KilopoundMole, parsed.Unit); - } - - { - Assert.True(AmountOfSubstance.TryParse("1 µmol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Micromoles, MicromolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Micromole, parsed.Unit); - } - - { - Assert.True(AmountOfSubstance.TryParse("1 µlbmol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicropoundMoles, MicropoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.MicropoundMole, parsed.Unit); - } - - { - Assert.True(AmountOfSubstance.TryParse("1 mlbmol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillipoundMoles, MillipoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.MillipoundMole, parsed.Unit); - } - - { - Assert.True(AmountOfSubstance.TryParse("1 mol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Moles, MolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Mole, parsed.Unit); - } - - { - Assert.True(AmountOfSubstance.TryParse("1 nmol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanomoles, NanomolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Nanomole, parsed.Unit); - } - - { - Assert.True(AmountOfSubstance.TryParse("1 nlbmol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanopoundMoles, NanopoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.NanopoundMole, parsed.Unit); - } - - { - Assert.True(AmountOfSubstance.TryParse("1 pmol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Picomoles, PicomolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.Picomole, parsed.Unit); - } - - { - Assert.True(AmountOfSubstance.TryParse("1 lbmol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundMoles, PoundMolesTolerance); - Assert.Equal(AmountOfSubstanceUnit.PoundMole, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(AmountOfSubstance.TryParse(quantityString, out AmountOfSubstance parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -848,6 +699,43 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Amount Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", AmountOfSubstanceUnit.Centimole, "cmol")] + [InlineData("en-US", AmountOfSubstanceUnit.CentipoundMole, "clbmol")] + [InlineData("en-US", AmountOfSubstanceUnit.Decimole, "dmol")] + [InlineData("en-US", AmountOfSubstanceUnit.DecipoundMole, "dlbmol")] + [InlineData("en-US", AmountOfSubstanceUnit.Femtomole, "fmol")] + [InlineData("en-US", AmountOfSubstanceUnit.Kilomole, "kmol")] + [InlineData("en-US", AmountOfSubstanceUnit.KilopoundMole, "klbmol")] + [InlineData("en-US", AmountOfSubstanceUnit.Megamole, "Mmol")] + [InlineData("en-US", AmountOfSubstanceUnit.Micromole, "µmol")] + [InlineData("en-US", AmountOfSubstanceUnit.MicropoundMole, "µlbmol")] + [InlineData("en-US", AmountOfSubstanceUnit.Millimole, "mmol")] + [InlineData("en-US", AmountOfSubstanceUnit.MillipoundMole, "mlbmol")] + [InlineData("en-US", AmountOfSubstanceUnit.Mole, "mol")] + [InlineData("en-US", AmountOfSubstanceUnit.Nanomole, "nmol")] + [InlineData("en-US", AmountOfSubstanceUnit.NanopoundMole, "nlbmol")] + [InlineData("en-US", AmountOfSubstanceUnit.Picomole, "pmol")] + [InlineData("en-US", AmountOfSubstanceUnit.PoundMole, "lbmol")] + public void GetAbbreviationForCulture(string culture, AmountOfSubstanceUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = AmountOfSubstance.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(AmountOfSubstance.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = AmountOfSubstance.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(AmountOfSubstanceUnit unit) @@ -878,6 +766,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); }); } @@ -901,48 +790,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] @@ -988,8 +879,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); @@ -1026,23 +915,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = AmountOfSubstance.FromMoles(1); - Assert.True(v.Equals(AmountOfSubstance.FromMoles(1), MolesTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(AmountOfSubstance.Zero, MolesTolerance, ComparisonType.Relative)); - Assert.True(AmountOfSubstance.FromMoles(100).Equals(AmountOfSubstance.FromMoles(120), 0.3, ComparisonType.Relative)); - Assert.False(AmountOfSubstance.FromMoles(100).Equals(AmountOfSubstance.FromMoles(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = AmountOfSubstance.FromMoles(1); - Assert.Throws(() => v.Equals(AmountOfSubstance.FromMoles(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1057,6 +929,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(mole.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = AmountOfSubstance.FromMoles(1); + var negativeTolerance = AmountOfSubstance.FromMoles(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1073,6 +971,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() { @@ -1163,158 +1073,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(AmountOfSubstance))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(AmountOfSubstanceUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal(AmountOfSubstance.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal(AmountOfSubstance.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal(new {AmountOfSubstance.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 b754916549..fb0f9da4ad 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AmplitudeRatioTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AmplitudeRatioTestsBase.g.cs @@ -100,15 +100,33 @@ public void Ctor_WithNaNValue_DoNotThrowsArgumentException() [Fact] public void AmplitudeRatio_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + AmplitudeRatioUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new AmplitudeRatio(1, AmplitudeRatioUnit.DecibelVolt); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(AmplitudeRatio.Zero, quantityInfo.Zero); Assert.Equal("AmplitudeRatio", quantityInfo.Name); + Assert.Equal(AmplitudeRatio.Zero, quantityInfo.Zero); + Assert.Equal(AmplitudeRatio.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(AmplitudeRatio.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void AmplitudeRatioInfo_CreateWithCustomUnitInfos() + { + AmplitudeRatioUnit[] expectedUnits = [AmplitudeRatioUnit.DecibelVolt]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -125,19 +143,19 @@ public void DecibelVoltToAmplitudeRatioUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = AmplitudeRatio.From(1, AmplitudeRatioUnit.DecibelMicrovolt); - AssertEx.EqualTolerance(1, quantity00.DecibelMicrovolts, DecibelMicrovoltsTolerance); + Assert.Equal(1, quantity00.DecibelMicrovolts); Assert.Equal(AmplitudeRatioUnit.DecibelMicrovolt, quantity00.Unit); var quantity01 = AmplitudeRatio.From(1, AmplitudeRatioUnit.DecibelMillivolt); - AssertEx.EqualTolerance(1, quantity01.DecibelMillivolts, DecibelMillivoltsTolerance); + Assert.Equal(1, quantity01.DecibelMillivolts); Assert.Equal(AmplitudeRatioUnit.DecibelMillivolt, quantity01.Unit); var quantity02 = AmplitudeRatio.From(1, AmplitudeRatioUnit.DecibelUnloaded); - AssertEx.EqualTolerance(1, quantity02.DecibelsUnloaded, DecibelsUnloadedTolerance); + Assert.Equal(1, quantity02.DecibelsUnloaded); Assert.Equal(AmplitudeRatioUnit.DecibelUnloaded, quantity02.Unit); var quantity03 = AmplitudeRatio.From(1, AmplitudeRatioUnit.DecibelVolt); - AssertEx.EqualTolerance(1, quantity03.DecibelVolts, DecibelVoltsTolerance); + Assert.Equal(1, quantity03.DecibelVolts); Assert.Equal(AmplitudeRatioUnit.DecibelVolt, quantity03.Unit); } @@ -237,66 +255,30 @@ public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 dBµV", AmplitudeRatioUnit.DecibelMicrovolt, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = AmplitudeRatio.Parse("1 dBµV", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecibelMicrovolts, DecibelMicrovoltsTolerance); - Assert.Equal(AmplitudeRatioUnit.DecibelMicrovolt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AmplitudeRatio.Parse("1 dBmV", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecibelMillivolts, DecibelMillivoltsTolerance); - Assert.Equal(AmplitudeRatioUnit.DecibelMillivolt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AmplitudeRatio.Parse("1 dBu", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecibelsUnloaded, DecibelsUnloadedTolerance); - Assert.Equal(AmplitudeRatioUnit.DecibelUnloaded, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AmplitudeRatio.Parse("1 dBV", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecibelVolts, DecibelVoltsTolerance); - Assert.Equal(AmplitudeRatioUnit.DecibelVolt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = AmplitudeRatio.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 dBµV", AmplitudeRatioUnit.DecibelMicrovolt, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(AmplitudeRatio.TryParse("1 dBµV", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecibelMicrovolts, DecibelMicrovoltsTolerance); - Assert.Equal(AmplitudeRatioUnit.DecibelMicrovolt, parsed.Unit); - } - - { - Assert.True(AmplitudeRatio.TryParse("1 dBmV", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecibelMillivolts, DecibelMillivoltsTolerance); - Assert.Equal(AmplitudeRatioUnit.DecibelMillivolt, parsed.Unit); - } - - { - Assert.True(AmplitudeRatio.TryParse("1 dBu", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecibelsUnloaded, DecibelsUnloadedTolerance); - Assert.Equal(AmplitudeRatioUnit.DecibelUnloaded, parsed.Unit); - } - - { - Assert.True(AmplitudeRatio.TryParse("1 dBV", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecibelVolts, DecibelVoltsTolerance); - Assert.Equal(AmplitudeRatioUnit.DecibelVolt, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(AmplitudeRatio.TryParse(quantityString, out AmplitudeRatio parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -397,6 +379,30 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Amplit Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", AmplitudeRatioUnit.DecibelMicrovolt, "dBµV")] + [InlineData("en-US", AmplitudeRatioUnit.DecibelMillivolt, "dBmV")] + [InlineData("en-US", AmplitudeRatioUnit.DecibelUnloaded, "dBu")] + [InlineData("en-US", AmplitudeRatioUnit.DecibelVolt, "dBV")] + public void GetAbbreviationForCulture(string culture, AmplitudeRatioUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = AmplitudeRatio.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(AmplitudeRatio.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = AmplitudeRatio.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(AmplitudeRatioUnit unit) @@ -427,6 +433,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); }); } @@ -450,35 +457,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(); @@ -528,8 +537,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); @@ -567,34 +574,45 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = AmplitudeRatio.FromDecibelVolts(1); - Assert.True(v.Equals(AmplitudeRatio.FromDecibelVolts(1), DecibelVoltsTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(AmplitudeRatio.Zero, DecibelVoltsTolerance, ComparisonType.Relative)); - Assert.True(AmplitudeRatio.FromDecibelVolts(100).Equals(AmplitudeRatio.FromDecibelVolts(120), 0.3, ComparisonType.Relative)); - Assert.False(AmplitudeRatio.FromDecibelVolts(100).Equals(AmplitudeRatio.FromDecibelVolts(120), 0.1, ComparisonType.Relative)); + AmplitudeRatio decibelvolt = AmplitudeRatio.FromDecibelVolts(1); + Assert.False(decibelvolt.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = AmplitudeRatio.FromDecibelVolts(1); - Assert.Throws(() => v.Equals(AmplitudeRatio.FromDecibelVolts(1), -1, ComparisonType.Relative)); + AmplitudeRatio decibelvolt = AmplitudeRatio.FromDecibelVolts(1); + Assert.False(decibelvolt.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - AmplitudeRatio decibelvolt = AmplitudeRatio.FromDecibelVolts(1); - Assert.False(decibelvolt.Equals(new object())); + var quantity = AmplitudeRatio.FromDecibelVolts(firstValue); + var otherQuantity = AmplitudeRatio.FromDecibelVolts(secondValue); + AmplitudeRatio maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + // note: it's currently not possible to test this due to the rounding error from (quantity - otherQuantity) + // Assert.True(quantity.Equals(otherQuantity, maxTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_DoesNotThrowArgumentOutOfRangeException() { - AmplitudeRatio decibelvolt = AmplitudeRatio.FromDecibelVolts(1); - Assert.False(decibelvolt.Equals(null)); + // note: unlike with vector quantities- a small tolerance maybe positive in one unit and negative in another + var quantity = AmplitudeRatio.FromDecibelVolts(1); + var negativeTolerance = AmplitudeRatio.FromDecibelVolts(-1); + Assert.True(quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -613,6 +631,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() { @@ -677,158 +707,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(AmplitudeRatio))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(AmplitudeRatioUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal(AmplitudeRatio.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal(AmplitudeRatio.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal(new {AmplitudeRatio.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 79d9a3c444..038baf0568 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AngleTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AngleTestsBase.g.cs @@ -144,15 +144,33 @@ public void Ctor_WithNaNValue_DoNotThrowsArgumentException() [Fact] public void Angle_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + AngleUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Angle(1, AngleUnit.Radian); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Angle.Zero, quantityInfo.Zero); Assert.Equal("Angle", quantityInfo.Name); + Assert.Equal(Angle.Zero, quantityInfo.Zero); + Assert.Equal(Angle.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Angle.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void AngleInfo_CreateWithCustomUnitInfos() + { + AngleUnit[] expectedUnits = [AngleUnit.Radian]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -180,63 +198,63 @@ public void RadianToAngleUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Angle.From(1, AngleUnit.Arcminute); - AssertEx.EqualTolerance(1, quantity00.Arcminutes, ArcminutesTolerance); + Assert.Equal(1, quantity00.Arcminutes); Assert.Equal(AngleUnit.Arcminute, quantity00.Unit); var quantity01 = Angle.From(1, AngleUnit.Arcsecond); - AssertEx.EqualTolerance(1, quantity01.Arcseconds, ArcsecondsTolerance); + Assert.Equal(1, quantity01.Arcseconds); Assert.Equal(AngleUnit.Arcsecond, quantity01.Unit); var quantity02 = Angle.From(1, AngleUnit.Centiradian); - AssertEx.EqualTolerance(1, quantity02.Centiradians, CentiradiansTolerance); + Assert.Equal(1, quantity02.Centiradians); Assert.Equal(AngleUnit.Centiradian, quantity02.Unit); var quantity03 = Angle.From(1, AngleUnit.Deciradian); - AssertEx.EqualTolerance(1, quantity03.Deciradians, DeciradiansTolerance); + Assert.Equal(1, quantity03.Deciradians); Assert.Equal(AngleUnit.Deciradian, quantity03.Unit); var quantity04 = Angle.From(1, AngleUnit.Degree); - AssertEx.EqualTolerance(1, quantity04.Degrees, DegreesTolerance); + Assert.Equal(1, quantity04.Degrees); Assert.Equal(AngleUnit.Degree, quantity04.Unit); var quantity05 = Angle.From(1, AngleUnit.Gradian); - AssertEx.EqualTolerance(1, quantity05.Gradians, GradiansTolerance); + Assert.Equal(1, quantity05.Gradians); Assert.Equal(AngleUnit.Gradian, quantity05.Unit); var quantity06 = Angle.From(1, AngleUnit.Microdegree); - AssertEx.EqualTolerance(1, quantity06.Microdegrees, MicrodegreesTolerance); + Assert.Equal(1, quantity06.Microdegrees); Assert.Equal(AngleUnit.Microdegree, quantity06.Unit); var quantity07 = Angle.From(1, AngleUnit.Microradian); - AssertEx.EqualTolerance(1, quantity07.Microradians, MicroradiansTolerance); + Assert.Equal(1, quantity07.Microradians); Assert.Equal(AngleUnit.Microradian, quantity07.Unit); var quantity08 = Angle.From(1, AngleUnit.Millidegree); - AssertEx.EqualTolerance(1, quantity08.Millidegrees, MillidegreesTolerance); + Assert.Equal(1, quantity08.Millidegrees); Assert.Equal(AngleUnit.Millidegree, quantity08.Unit); var quantity09 = Angle.From(1, AngleUnit.Milliradian); - AssertEx.EqualTolerance(1, quantity09.Milliradians, MilliradiansTolerance); + Assert.Equal(1, quantity09.Milliradians); Assert.Equal(AngleUnit.Milliradian, quantity09.Unit); var quantity10 = Angle.From(1, AngleUnit.Nanodegree); - AssertEx.EqualTolerance(1, quantity10.Nanodegrees, NanodegreesTolerance); + Assert.Equal(1, quantity10.Nanodegrees); Assert.Equal(AngleUnit.Nanodegree, quantity10.Unit); var quantity11 = Angle.From(1, AngleUnit.Nanoradian); - AssertEx.EqualTolerance(1, quantity11.Nanoradians, NanoradiansTolerance); + Assert.Equal(1, quantity11.Nanoradians); Assert.Equal(AngleUnit.Nanoradian, quantity11.Unit); var quantity12 = Angle.From(1, AngleUnit.NatoMil); - AssertEx.EqualTolerance(1, quantity12.NatoMils, NatoMilsTolerance); + Assert.Equal(1, quantity12.NatoMils); Assert.Equal(AngleUnit.NatoMil, quantity12.Unit); var quantity13 = Angle.From(1, AngleUnit.Radian); - AssertEx.EqualTolerance(1, quantity13.Radians, RadiansTolerance); + Assert.Equal(1, quantity13.Radians); Assert.Equal(AngleUnit.Radian, quantity13.Unit); var quantity14 = Angle.From(1, AngleUnit.Revolution); - AssertEx.EqualTolerance(1, quantity14.Revolutions, RevolutionsTolerance); + Assert.Equal(1, quantity14.Revolutions); Assert.Equal(AngleUnit.Revolution, quantity14.Unit); } @@ -347,495 +365,96 @@ public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 '", AngleUnit.Arcminute, 4.2)] + [InlineData("en-US", "4.2 arcmin", AngleUnit.Arcminute, 4.2)] + [InlineData("en-US", "4.2 amin", AngleUnit.Arcminute, 4.2)] + [InlineData("en-US", "4.2 min", AngleUnit.Arcminute, 4.2)] + [InlineData("en-US", "4.2 ″", AngleUnit.Arcsecond, 4.2)] + [InlineData("en-US", "4.2 arcsec", AngleUnit.Arcsecond, 4.2)] + [InlineData("en-US", "4.2 asec", AngleUnit.Arcsecond, 4.2)] + [InlineData("en-US", "4.2 sec", AngleUnit.Arcsecond, 4.2)] + [InlineData("en-US", "4.2 crad", AngleUnit.Centiradian, 4.2)] + [InlineData("en-US", "4.2 drad", AngleUnit.Deciradian, 4.2)] + [InlineData("en-US", "4.2 °", AngleUnit.Degree, 4.2)] + [InlineData("en-US", "4.2 deg", AngleUnit.Degree, 4.2)] + [InlineData("en-US", "4.2 g", AngleUnit.Gradian, 4.2)] + [InlineData("en-US", "4.2 µ°", AngleUnit.Microdegree, 4.2)] + [InlineData("en-US", "4.2 µdeg", AngleUnit.Microdegree, 4.2)] + [InlineData("en-US", "4.2 µrad", AngleUnit.Microradian, 4.2)] + [InlineData("en-US", "4.2 m°", AngleUnit.Millidegree, 4.2)] + [InlineData("en-US", "4.2 mdeg", AngleUnit.Millidegree, 4.2)] + [InlineData("en-US", "4.2 mrad", AngleUnit.Milliradian, 4.2)] + [InlineData("en-US", "4.2 n°", AngleUnit.Nanodegree, 4.2)] + [InlineData("en-US", "4.2 ndeg", AngleUnit.Nanodegree, 4.2)] + [InlineData("en-US", "4.2 nrad", AngleUnit.Nanoradian, 4.2)] + [InlineData("en-US", "4.2 mil", AngleUnit.NatoMil, 4.2)] + [InlineData("en-US", "4.2 rad", AngleUnit.Radian, 4.2)] + [InlineData("en-US", "4.2 r", AngleUnit.Revolution, 4.2)] + [InlineData("ru-RU", "4,2 срад", AngleUnit.Centiradian, 4.2)] + [InlineData("ru-RU", "4,2 драд", AngleUnit.Deciradian, 4.2)] + [InlineData("ru-RU", "4,2 °", AngleUnit.Degree, 4.2)] + [InlineData("ru-RU", "4,2 g", AngleUnit.Gradian, 4.2)] + [InlineData("ru-RU", "4,2 мк°", AngleUnit.Microdegree, 4.2)] + [InlineData("ru-RU", "4,2 мкрад", AngleUnit.Microradian, 4.2)] + [InlineData("ru-RU", "4,2 м°", AngleUnit.Millidegree, 4.2)] + [InlineData("ru-RU", "4,2 мрад", AngleUnit.Milliradian, 4.2)] + [InlineData("ru-RU", "4,2 н°", AngleUnit.Nanodegree, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = Angle.Parse("1 '", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Arcminutes, ArcminutesTolerance); - Assert.Equal(AngleUnit.Arcminute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 arcmin", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Arcminutes, ArcminutesTolerance); - Assert.Equal(AngleUnit.Arcminute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 amin", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Arcminutes, ArcminutesTolerance); - Assert.Equal(AngleUnit.Arcminute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Arcminutes, ArcminutesTolerance); - Assert.Equal(AngleUnit.Arcminute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 ″", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Arcseconds, ArcsecondsTolerance); - Assert.Equal(AngleUnit.Arcsecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 arcsec", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Arcseconds, ArcsecondsTolerance); - Assert.Equal(AngleUnit.Arcsecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 asec", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Arcseconds, ArcsecondsTolerance); - Assert.Equal(AngleUnit.Arcsecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 sec", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Arcseconds, ArcsecondsTolerance); - Assert.Equal(AngleUnit.Arcsecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 crad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Centiradians, CentiradiansTolerance); - Assert.Equal(AngleUnit.Centiradian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 срад", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Centiradians, CentiradiansTolerance); - Assert.Equal(AngleUnit.Centiradian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 drad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Deciradians, DeciradiansTolerance); - Assert.Equal(AngleUnit.Deciradian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 драд", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Deciradians, DeciradiansTolerance); - Assert.Equal(AngleUnit.Deciradian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 °", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Degrees, DegreesTolerance); - Assert.Equal(AngleUnit.Degree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Degrees, DegreesTolerance); - Assert.Equal(AngleUnit.Degree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 °", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Degrees, DegreesTolerance); - Assert.Equal(AngleUnit.Degree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 g", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Gradians, GradiansTolerance); - Assert.Equal(AngleUnit.Gradian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 g", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Gradians, GradiansTolerance); - Assert.Equal(AngleUnit.Gradian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 µ°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microdegrees, MicrodegreesTolerance); - Assert.Equal(AngleUnit.Microdegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 µdeg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microdegrees, MicrodegreesTolerance); - Assert.Equal(AngleUnit.Microdegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 мк°", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Microdegrees, MicrodegreesTolerance); - Assert.Equal(AngleUnit.Microdegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 µrad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microradians, MicroradiansTolerance); - Assert.Equal(AngleUnit.Microradian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 мкрад", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Microradians, MicroradiansTolerance); - Assert.Equal(AngleUnit.Microradian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 m°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millidegrees, MillidegreesTolerance); - Assert.Equal(AngleUnit.Millidegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 mdeg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millidegrees, MillidegreesTolerance); - Assert.Equal(AngleUnit.Millidegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 м°", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Millidegrees, MillidegreesTolerance); - Assert.Equal(AngleUnit.Millidegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 mrad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Milliradians, MilliradiansTolerance); - Assert.Equal(AngleUnit.Milliradian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 мрад", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Milliradians, MilliradiansTolerance); - Assert.Equal(AngleUnit.Milliradian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 n°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanodegrees, NanodegreesTolerance); - Assert.Equal(AngleUnit.Nanodegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 ndeg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanodegrees, NanodegreesTolerance); - Assert.Equal(AngleUnit.Nanodegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 н°", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Nanodegrees, NanodegreesTolerance); - Assert.Equal(AngleUnit.Nanodegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 nrad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanoradians, NanoradiansTolerance); - Assert.Equal(AngleUnit.Nanoradian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 нрад", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Nanoradians, NanoradiansTolerance); - Assert.Equal(AngleUnit.Nanoradian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 mil", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NatoMils, NatoMilsTolerance); - Assert.Equal(AngleUnit.NatoMil, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 rad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Radians, RadiansTolerance); - Assert.Equal(AngleUnit.Radian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 рад", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Radians, RadiansTolerance); - Assert.Equal(AngleUnit.Radian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 r", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Revolutions, RevolutionsTolerance); - Assert.Equal(AngleUnit.Revolution, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Angle.Parse("1 r", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Revolutions, RevolutionsTolerance); - Assert.Equal(AngleUnit.Revolution, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Angle.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 '", AngleUnit.Arcminute, 4.2)] + [InlineData("en-US", "4.2 arcmin", AngleUnit.Arcminute, 4.2)] + [InlineData("en-US", "4.2 amin", AngleUnit.Arcminute, 4.2)] + [InlineData("en-US", "4.2 min", AngleUnit.Arcminute, 4.2)] + [InlineData("en-US", "4.2 ″", AngleUnit.Arcsecond, 4.2)] + [InlineData("en-US", "4.2 arcsec", AngleUnit.Arcsecond, 4.2)] + [InlineData("en-US", "4.2 asec", AngleUnit.Arcsecond, 4.2)] + [InlineData("en-US", "4.2 sec", AngleUnit.Arcsecond, 4.2)] + [InlineData("en-US", "4.2 crad", AngleUnit.Centiradian, 4.2)] + [InlineData("en-US", "4.2 drad", AngleUnit.Deciradian, 4.2)] + [InlineData("en-US", "4.2 °", AngleUnit.Degree, 4.2)] + [InlineData("en-US", "4.2 deg", AngleUnit.Degree, 4.2)] + [InlineData("en-US", "4.2 g", AngleUnit.Gradian, 4.2)] + [InlineData("en-US", "4.2 µ°", AngleUnit.Microdegree, 4.2)] + [InlineData("en-US", "4.2 µdeg", AngleUnit.Microdegree, 4.2)] + [InlineData("en-US", "4.2 µrad", AngleUnit.Microradian, 4.2)] + [InlineData("en-US", "4.2 m°", AngleUnit.Millidegree, 4.2)] + [InlineData("en-US", "4.2 mdeg", AngleUnit.Millidegree, 4.2)] + [InlineData("en-US", "4.2 mrad", AngleUnit.Milliradian, 4.2)] + [InlineData("en-US", "4.2 n°", AngleUnit.Nanodegree, 4.2)] + [InlineData("en-US", "4.2 ndeg", AngleUnit.Nanodegree, 4.2)] + [InlineData("en-US", "4.2 nrad", AngleUnit.Nanoradian, 4.2)] + [InlineData("en-US", "4.2 mil", AngleUnit.NatoMil, 4.2)] + [InlineData("en-US", "4.2 rad", AngleUnit.Radian, 4.2)] + [InlineData("en-US", "4.2 r", AngleUnit.Revolution, 4.2)] + [InlineData("ru-RU", "4,2 срад", AngleUnit.Centiradian, 4.2)] + [InlineData("ru-RU", "4,2 драд", AngleUnit.Deciradian, 4.2)] + [InlineData("ru-RU", "4,2 °", AngleUnit.Degree, 4.2)] + [InlineData("ru-RU", "4,2 g", AngleUnit.Gradian, 4.2)] + [InlineData("ru-RU", "4,2 мк°", AngleUnit.Microdegree, 4.2)] + [InlineData("ru-RU", "4,2 мкрад", AngleUnit.Microradian, 4.2)] + [InlineData("ru-RU", "4,2 м°", AngleUnit.Millidegree, 4.2)] + [InlineData("ru-RU", "4,2 мрад", AngleUnit.Milliradian, 4.2)] + [InlineData("ru-RU", "4,2 н°", AngleUnit.Nanodegree, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(Angle.TryParse("1 '", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Arcminutes, ArcminutesTolerance); - Assert.Equal(AngleUnit.Arcminute, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 arcmin", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Arcminutes, ArcminutesTolerance); - Assert.Equal(AngleUnit.Arcminute, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 amin", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Arcminutes, ArcminutesTolerance); - Assert.Equal(AngleUnit.Arcminute, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Arcminutes, ArcminutesTolerance); - Assert.Equal(AngleUnit.Arcminute, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 ″", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Arcseconds, ArcsecondsTolerance); - Assert.Equal(AngleUnit.Arcsecond, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 arcsec", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Arcseconds, ArcsecondsTolerance); - Assert.Equal(AngleUnit.Arcsecond, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 asec", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Arcseconds, ArcsecondsTolerance); - Assert.Equal(AngleUnit.Arcsecond, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 sec", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Arcseconds, ArcsecondsTolerance); - Assert.Equal(AngleUnit.Arcsecond, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 crad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Centiradians, CentiradiansTolerance); - Assert.Equal(AngleUnit.Centiradian, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 срад", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Centiradians, CentiradiansTolerance); - Assert.Equal(AngleUnit.Centiradian, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 drad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Deciradians, DeciradiansTolerance); - Assert.Equal(AngleUnit.Deciradian, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 драд", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Deciradians, DeciradiansTolerance); - Assert.Equal(AngleUnit.Deciradian, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 °", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Degrees, DegreesTolerance); - Assert.Equal(AngleUnit.Degree, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Degrees, DegreesTolerance); - Assert.Equal(AngleUnit.Degree, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 °", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Degrees, DegreesTolerance); - Assert.Equal(AngleUnit.Degree, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 g", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gradians, GradiansTolerance); - Assert.Equal(AngleUnit.Gradian, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 g", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gradians, GradiansTolerance); - Assert.Equal(AngleUnit.Gradian, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 µ°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microdegrees, MicrodegreesTolerance); - Assert.Equal(AngleUnit.Microdegree, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 µdeg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microdegrees, MicrodegreesTolerance); - Assert.Equal(AngleUnit.Microdegree, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 мк°", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microdegrees, MicrodegreesTolerance); - Assert.Equal(AngleUnit.Microdegree, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 µrad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microradians, MicroradiansTolerance); - Assert.Equal(AngleUnit.Microradian, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 мкрад", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microradians, MicroradiansTolerance); - Assert.Equal(AngleUnit.Microradian, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 m°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Millidegrees, MillidegreesTolerance); - Assert.Equal(AngleUnit.Millidegree, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 mdeg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Millidegrees, MillidegreesTolerance); - Assert.Equal(AngleUnit.Millidegree, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 м°", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Millidegrees, MillidegreesTolerance); - Assert.Equal(AngleUnit.Millidegree, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 mrad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Milliradians, MilliradiansTolerance); - Assert.Equal(AngleUnit.Milliradian, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 мрад", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Milliradians, MilliradiansTolerance); - Assert.Equal(AngleUnit.Milliradian, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 n°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanodegrees, NanodegreesTolerance); - Assert.Equal(AngleUnit.Nanodegree, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 ndeg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanodegrees, NanodegreesTolerance); - Assert.Equal(AngleUnit.Nanodegree, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 н°", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanodegrees, NanodegreesTolerance); - Assert.Equal(AngleUnit.Nanodegree, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 nrad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanoradians, NanoradiansTolerance); - Assert.Equal(AngleUnit.Nanoradian, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 нрад", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanoradians, NanoradiansTolerance); - Assert.Equal(AngleUnit.Nanoradian, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 mil", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NatoMils, NatoMilsTolerance); - Assert.Equal(AngleUnit.NatoMil, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 rad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Radians, RadiansTolerance); - Assert.Equal(AngleUnit.Radian, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 рад", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Radians, RadiansTolerance); - Assert.Equal(AngleUnit.Radian, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 r", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Revolutions, RevolutionsTolerance); - Assert.Equal(AngleUnit.Revolution, parsed.Unit); - } - - { - Assert.True(Angle.TryParse("1 r", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Revolutions, RevolutionsTolerance); - Assert.Equal(AngleUnit.Revolution, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Angle.TryParse(quantityString, out Angle parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -1152,6 +771,53 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, AngleU Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", AngleUnit.Arcminute, "'")] + [InlineData("en-US", AngleUnit.Arcsecond, "″")] + [InlineData("en-US", AngleUnit.Centiradian, "crad")] + [InlineData("en-US", AngleUnit.Deciradian, "drad")] + [InlineData("en-US", AngleUnit.Degree, "°")] + [InlineData("en-US", AngleUnit.Gradian, "g")] + [InlineData("en-US", AngleUnit.Microdegree, "µ°")] + [InlineData("en-US", AngleUnit.Microradian, "µrad")] + [InlineData("en-US", AngleUnit.Millidegree, "m°")] + [InlineData("en-US", AngleUnit.Milliradian, "mrad")] + [InlineData("en-US", AngleUnit.Nanodegree, "n°")] + [InlineData("en-US", AngleUnit.Nanoradian, "nrad")] + [InlineData("en-US", AngleUnit.NatoMil, "mil")] + [InlineData("en-US", AngleUnit.Radian, "rad")] + [InlineData("en-US", AngleUnit.Revolution, "r")] + [InlineData("ru-RU", AngleUnit.Centiradian, "срад")] + [InlineData("ru-RU", AngleUnit.Deciradian, "драд")] + [InlineData("ru-RU", AngleUnit.Degree, "°")] + [InlineData("ru-RU", AngleUnit.Gradian, "g")] + [InlineData("ru-RU", AngleUnit.Microdegree, "мк°")] + [InlineData("ru-RU", AngleUnit.Microradian, "мкрад")] + [InlineData("ru-RU", AngleUnit.Millidegree, "м°")] + [InlineData("ru-RU", AngleUnit.Milliradian, "мрад")] + [InlineData("ru-RU", AngleUnit.Nanodegree, "н°")] + [InlineData("ru-RU", AngleUnit.Nanoradian, "нрад")] + [InlineData("ru-RU", AngleUnit.Radian, "рад")] + [InlineData("ru-RU", AngleUnit.Revolution, "r")] + public void GetAbbreviationForCulture(string culture, AngleUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Angle.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Angle.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Angle.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(AngleUnit unit) @@ -1182,6 +848,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); }); } @@ -1205,46 +872,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] @@ -1290,8 +959,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); @@ -1328,23 +995,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = Angle.FromRadians(1); - Assert.True(v.Equals(Angle.FromRadians(1), RadiansTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Angle.Zero, RadiansTolerance, ComparisonType.Relative)); - Assert.True(Angle.FromRadians(100).Equals(Angle.FromRadians(120), 0.3, ComparisonType.Relative)); - Assert.False(Angle.FromRadians(100).Equals(Angle.FromRadians(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = Angle.FromRadians(1); - Assert.Throws(() => v.Equals(Angle.FromRadians(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1359,6 +1009,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(radian.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = Angle.FromRadians(1); + var negativeTolerance = Angle.FromRadians(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1375,6 +1051,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() { @@ -1461,158 +1149,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Angle.FromRadians(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Angle.FromRadians(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Angle.FromRadians(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Angle.FromRadians(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Angle.FromRadians(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Angle.FromRadians(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Angle.FromRadians(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Angle.FromRadians(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Angle.FromRadians(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Angle.FromRadians(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Angle.FromRadians(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Angle.FromRadians(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Angle.FromRadians(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Angle.FromRadians(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Angle.FromRadians(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Angle.FromRadians(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Angle))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Angle.FromRadians(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(AngleUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Angle.FromRadians(1.0); - Assert.Equal(Angle.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Angle.FromRadians(1.0); - Assert.Equal(Angle.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Angle.FromRadians(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Angle.FromRadians(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Angle.FromRadians(1.0); - Assert.Equal(new {Angle.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 62011ec129..bbfe0d02ac 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AreaDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AreaDensityTestsBase.g.cs @@ -104,7 +104,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new AreaDensity(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -117,15 +117,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void AreaDensity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + AreaDensityUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new AreaDensity(1, AreaDensityUnit.KilogramPerSquareMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(AreaDensity.Zero, quantityInfo.Zero); Assert.Equal("AreaDensity", quantityInfo.Name); + Assert.Equal(AreaDensity.Zero, quantityInfo.Zero); + Assert.Equal(AreaDensity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(AreaDensity.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void AreaDensityInfo_CreateWithCustomUnitInfos() + { + AreaDensityUnit[] expectedUnits = [AreaDensityUnit.KilogramPerSquareMeter]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -141,15 +159,15 @@ public void KilogramPerSquareMeterToAreaDensityUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = AreaDensity.From(1, AreaDensityUnit.GramPerSquareMeter); - AssertEx.EqualTolerance(1, quantity00.GramsPerSquareMeter, GramsPerSquareMeterTolerance); + Assert.Equal(1, quantity00.GramsPerSquareMeter); Assert.Equal(AreaDensityUnit.GramPerSquareMeter, quantity00.Unit); var quantity01 = AreaDensity.From(1, AreaDensityUnit.KilogramPerSquareMeter); - AssertEx.EqualTolerance(1, quantity01.KilogramsPerSquareMeter, KilogramsPerSquareMeterTolerance); + Assert.Equal(1, quantity01.KilogramsPerSquareMeter); Assert.Equal(AreaDensityUnit.KilogramPerSquareMeter, quantity01.Unit); var quantity02 = AreaDensity.From(1, AreaDensityUnit.MilligramPerSquareMeter); - AssertEx.EqualTolerance(1, quantity02.MilligramsPerSquareMeter, MilligramsPerSquareMeterTolerance); + Assert.Equal(1, quantity02.MilligramsPerSquareMeter); Assert.Equal(AreaDensityUnit.MilligramPerSquareMeter, quantity02.Unit); } @@ -287,66 +305,30 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 g/m²", AreaDensityUnit.GramPerSquareMeter, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = AreaDensity.Parse("1 g/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerSquareMeter, GramsPerSquareMeterTolerance); - Assert.Equal(AreaDensityUnit.GramPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AreaDensity.Parse("1 gsm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerSquareMeter, GramsPerSquareMeterTolerance); - Assert.Equal(AreaDensityUnit.GramPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AreaDensity.Parse("1 kg/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerSquareMeter, KilogramsPerSquareMeterTolerance); - Assert.Equal(AreaDensityUnit.KilogramPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AreaDensity.Parse("1 mg/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligramsPerSquareMeter, MilligramsPerSquareMeterTolerance); - Assert.Equal(AreaDensityUnit.MilligramPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = AreaDensity.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 g/m²", AreaDensityUnit.GramPerSquareMeter, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(AreaDensity.TryParse("1 g/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerSquareMeter, GramsPerSquareMeterTolerance); - Assert.Equal(AreaDensityUnit.GramPerSquareMeter, parsed.Unit); - } - - { - Assert.True(AreaDensity.TryParse("1 gsm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerSquareMeter, GramsPerSquareMeterTolerance); - Assert.Equal(AreaDensityUnit.GramPerSquareMeter, parsed.Unit); - } - - { - Assert.True(AreaDensity.TryParse("1 kg/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerSquareMeter, KilogramsPerSquareMeterTolerance); - Assert.Equal(AreaDensityUnit.KilogramPerSquareMeter, parsed.Unit); - } - - { - Assert.True(AreaDensity.TryParse("1 mg/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligramsPerSquareMeter, MilligramsPerSquareMeterTolerance); - Assert.Equal(AreaDensityUnit.MilligramPerSquareMeter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(AreaDensity.TryParse(quantityString, out AreaDensity parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -447,6 +429,29 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, AreaDe Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", AreaDensityUnit.GramPerSquareMeter, "g/m²")] + [InlineData("en-US", AreaDensityUnit.KilogramPerSquareMeter, "kg/m²")] + [InlineData("en-US", AreaDensityUnit.MilligramPerSquareMeter, "mg/m²")] + public void GetAbbreviationForCulture(string culture, AreaDensityUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = AreaDensity.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(AreaDensity.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = AreaDensity.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(AreaDensityUnit unit) @@ -477,6 +482,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); }); } @@ -500,34 +506,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] @@ -573,8 +581,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); @@ -612,34 +618,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = AreaDensity.FromKilogramsPerSquareMeter(1); - Assert.True(v.Equals(AreaDensity.FromKilogramsPerSquareMeter(1), KilogramsPerSquareMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(AreaDensity.Zero, KilogramsPerSquareMeterTolerance, ComparisonType.Relative)); - Assert.True(AreaDensity.FromKilogramsPerSquareMeter(100).Equals(AreaDensity.FromKilogramsPerSquareMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(AreaDensity.FromKilogramsPerSquareMeter(100).Equals(AreaDensity.FromKilogramsPerSquareMeter(120), 0.1, ComparisonType.Relative)); + AreaDensity kilogrampersquaremeter = AreaDensity.FromKilogramsPerSquareMeter(1); + Assert.False(kilogrampersquaremeter.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = AreaDensity.FromKilogramsPerSquareMeter(1); - Assert.Throws(() => v.Equals(AreaDensity.FromKilogramsPerSquareMeter(1), -1, ComparisonType.Relative)); + AreaDensity kilogrampersquaremeter = AreaDensity.FromKilogramsPerSquareMeter(1); + Assert.False(kilogrampersquaremeter.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - AreaDensity kilogrampersquaremeter = AreaDensity.FromKilogramsPerSquareMeter(1); - Assert.False(kilogrampersquaremeter.Equals(new object())); + var quantity = AreaDensity.FromKilogramsPerSquareMeter(firstValue); + var otherQuantity = AreaDensity.FromKilogramsPerSquareMeter(secondValue); + AreaDensity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - AreaDensity kilogrampersquaremeter = AreaDensity.FromKilogramsPerSquareMeter(1); - Assert.False(kilogrampersquaremeter.Equals(null)); + var quantity = AreaDensity.FromKilogramsPerSquareMeter(1); + var negativeTolerance = AreaDensity.FromKilogramsPerSquareMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -658,6 +673,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() { @@ -720,158 +747,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(AreaDensity))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(AreaDensityUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal(AreaDensity.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal(AreaDensity.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal(new {AreaDensity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 dce2428e62..979c943cc7 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AreaMomentOfInertiaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AreaMomentOfInertiaTestsBase.g.cs @@ -116,7 +116,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new AreaMomentOfInertia(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -129,15 +129,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void AreaMomentOfInertia_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + AreaMomentOfInertiaUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new AreaMomentOfInertia(1, AreaMomentOfInertiaUnit.MeterToTheFourth); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(AreaMomentOfInertia.Zero, quantityInfo.Zero); Assert.Equal("AreaMomentOfInertia", quantityInfo.Name); + Assert.Equal(AreaMomentOfInertia.Zero, quantityInfo.Zero); + Assert.Equal(AreaMomentOfInertia.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(AreaMomentOfInertia.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void AreaMomentOfInertiaInfo_CreateWithCustomUnitInfos() + { + AreaMomentOfInertiaUnit[] expectedUnits = [AreaMomentOfInertiaUnit.MeterToTheFourth]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -156,27 +174,27 @@ public void MeterToTheFourthToAreaMomentOfInertiaUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = AreaMomentOfInertia.From(1, AreaMomentOfInertiaUnit.CentimeterToTheFourth); - AssertEx.EqualTolerance(1, quantity00.CentimetersToTheFourth, CentimetersToTheFourthTolerance); + Assert.Equal(1, quantity00.CentimetersToTheFourth); Assert.Equal(AreaMomentOfInertiaUnit.CentimeterToTheFourth, quantity00.Unit); var quantity01 = AreaMomentOfInertia.From(1, AreaMomentOfInertiaUnit.DecimeterToTheFourth); - AssertEx.EqualTolerance(1, quantity01.DecimetersToTheFourth, DecimetersToTheFourthTolerance); + Assert.Equal(1, quantity01.DecimetersToTheFourth); Assert.Equal(AreaMomentOfInertiaUnit.DecimeterToTheFourth, quantity01.Unit); var quantity02 = AreaMomentOfInertia.From(1, AreaMomentOfInertiaUnit.FootToTheFourth); - AssertEx.EqualTolerance(1, quantity02.FeetToTheFourth, FeetToTheFourthTolerance); + Assert.Equal(1, quantity02.FeetToTheFourth); Assert.Equal(AreaMomentOfInertiaUnit.FootToTheFourth, quantity02.Unit); var quantity03 = AreaMomentOfInertia.From(1, AreaMomentOfInertiaUnit.InchToTheFourth); - AssertEx.EqualTolerance(1, quantity03.InchesToTheFourth, InchesToTheFourthTolerance); + Assert.Equal(1, quantity03.InchesToTheFourth); Assert.Equal(AreaMomentOfInertiaUnit.InchToTheFourth, quantity03.Unit); var quantity04 = AreaMomentOfInertia.From(1, AreaMomentOfInertiaUnit.MeterToTheFourth); - AssertEx.EqualTolerance(1, quantity04.MetersToTheFourth, MetersToTheFourthTolerance); + Assert.Equal(1, quantity04.MetersToTheFourth); Assert.Equal(AreaMomentOfInertiaUnit.MeterToTheFourth, quantity04.Unit); var quantity05 = AreaMomentOfInertia.From(1, AreaMomentOfInertiaUnit.MillimeterToTheFourth); - AssertEx.EqualTolerance(1, quantity05.MillimetersToTheFourth, MillimetersToTheFourthTolerance); + Assert.Equal(1, quantity05.MillimetersToTheFourth); Assert.Equal(AreaMomentOfInertiaUnit.MillimeterToTheFourth, quantity05.Unit); } @@ -317,92 +335,34 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 cm⁴", AreaMomentOfInertiaUnit.CentimeterToTheFourth, 4.2)] + [InlineData("en-US", "4.2 dm⁴", AreaMomentOfInertiaUnit.DecimeterToTheFourth, 4.2)] + [InlineData("en-US", "4.2 ft⁴", AreaMomentOfInertiaUnit.FootToTheFourth, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = AreaMomentOfInertia.Parse("1 cm⁴", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentimetersToTheFourth, CentimetersToTheFourthTolerance); - Assert.Equal(AreaMomentOfInertiaUnit.CentimeterToTheFourth, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AreaMomentOfInertia.Parse("1 dm⁴", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecimetersToTheFourth, DecimetersToTheFourthTolerance); - Assert.Equal(AreaMomentOfInertiaUnit.DecimeterToTheFourth, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AreaMomentOfInertia.Parse("1 ft⁴", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.FeetToTheFourth, FeetToTheFourthTolerance); - Assert.Equal(AreaMomentOfInertiaUnit.FootToTheFourth, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AreaMomentOfInertia.Parse("1 in⁴", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InchesToTheFourth, InchesToTheFourthTolerance); - Assert.Equal(AreaMomentOfInertiaUnit.InchToTheFourth, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AreaMomentOfInertia.Parse("1 m⁴", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MetersToTheFourth, MetersToTheFourthTolerance); - Assert.Equal(AreaMomentOfInertiaUnit.MeterToTheFourth, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = AreaMomentOfInertia.Parse("1 mm⁴", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillimetersToTheFourth, MillimetersToTheFourthTolerance); - Assert.Equal(AreaMomentOfInertiaUnit.MillimeterToTheFourth, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = AreaMomentOfInertia.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 cm⁴", AreaMomentOfInertiaUnit.CentimeterToTheFourth, 4.2)] + [InlineData("en-US", "4.2 dm⁴", AreaMomentOfInertiaUnit.DecimeterToTheFourth, 4.2)] + [InlineData("en-US", "4.2 ft⁴", AreaMomentOfInertiaUnit.FootToTheFourth, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(AreaMomentOfInertia.TryParse("1 cm⁴", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentimetersToTheFourth, CentimetersToTheFourthTolerance); - Assert.Equal(AreaMomentOfInertiaUnit.CentimeterToTheFourth, parsed.Unit); - } - - { - Assert.True(AreaMomentOfInertia.TryParse("1 dm⁴", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecimetersToTheFourth, DecimetersToTheFourthTolerance); - Assert.Equal(AreaMomentOfInertiaUnit.DecimeterToTheFourth, parsed.Unit); - } - - { - Assert.True(AreaMomentOfInertia.TryParse("1 ft⁴", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.FeetToTheFourth, FeetToTheFourthTolerance); - Assert.Equal(AreaMomentOfInertiaUnit.FootToTheFourth, parsed.Unit); - } - - { - Assert.True(AreaMomentOfInertia.TryParse("1 in⁴", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InchesToTheFourth, InchesToTheFourthTolerance); - Assert.Equal(AreaMomentOfInertiaUnit.InchToTheFourth, parsed.Unit); - } - - { - Assert.True(AreaMomentOfInertia.TryParse("1 m⁴", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetersToTheFourth, MetersToTheFourthTolerance); - Assert.Equal(AreaMomentOfInertiaUnit.MeterToTheFourth, parsed.Unit); - } - - { - Assert.True(AreaMomentOfInertia.TryParse("1 mm⁴", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimetersToTheFourth, MillimetersToTheFourthTolerance); - Assert.Equal(AreaMomentOfInertiaUnit.MillimeterToTheFourth, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(AreaMomentOfInertia.TryParse(quantityString, out AreaMomentOfInertia parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -519,6 +479,32 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, AreaMo Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", AreaMomentOfInertiaUnit.CentimeterToTheFourth, "cm⁴")] + [InlineData("en-US", AreaMomentOfInertiaUnit.DecimeterToTheFourth, "dm⁴")] + [InlineData("en-US", AreaMomentOfInertiaUnit.FootToTheFourth, "ft⁴")] + [InlineData("en-US", AreaMomentOfInertiaUnit.InchToTheFourth, "in⁴")] + [InlineData("en-US", AreaMomentOfInertiaUnit.MeterToTheFourth, "m⁴")] + [InlineData("en-US", AreaMomentOfInertiaUnit.MillimeterToTheFourth, "mm⁴")] + public void GetAbbreviationForCulture(string culture, AreaMomentOfInertiaUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = AreaMomentOfInertia.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(AreaMomentOfInertia.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = AreaMomentOfInertia.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(AreaMomentOfInertiaUnit unit) @@ -549,6 +535,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); }); } @@ -572,37 +559,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] @@ -648,8 +637,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); @@ -687,34 +674,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = AreaMomentOfInertia.FromMetersToTheFourth(1); - Assert.True(v.Equals(AreaMomentOfInertia.FromMetersToTheFourth(1), MetersToTheFourthTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(AreaMomentOfInertia.Zero, MetersToTheFourthTolerance, ComparisonType.Relative)); - Assert.True(AreaMomentOfInertia.FromMetersToTheFourth(100).Equals(AreaMomentOfInertia.FromMetersToTheFourth(120), 0.3, ComparisonType.Relative)); - Assert.False(AreaMomentOfInertia.FromMetersToTheFourth(100).Equals(AreaMomentOfInertia.FromMetersToTheFourth(120), 0.1, ComparisonType.Relative)); + AreaMomentOfInertia metertothefourth = AreaMomentOfInertia.FromMetersToTheFourth(1); + Assert.False(metertothefourth.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = AreaMomentOfInertia.FromMetersToTheFourth(1); - Assert.Throws(() => v.Equals(AreaMomentOfInertia.FromMetersToTheFourth(1), -1, ComparisonType.Relative)); + AreaMomentOfInertia metertothefourth = AreaMomentOfInertia.FromMetersToTheFourth(1); + Assert.False(metertothefourth.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - AreaMomentOfInertia metertothefourth = AreaMomentOfInertia.FromMetersToTheFourth(1); - Assert.False(metertothefourth.Equals(new object())); + var quantity = AreaMomentOfInertia.FromMetersToTheFourth(firstValue); + var otherQuantity = AreaMomentOfInertia.FromMetersToTheFourth(secondValue); + AreaMomentOfInertia maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - AreaMomentOfInertia metertothefourth = AreaMomentOfInertia.FromMetersToTheFourth(1); - Assert.False(metertothefourth.Equals(null)); + var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1); + var negativeTolerance = AreaMomentOfInertia.FromMetersToTheFourth(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -733,6 +729,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() { @@ -801,158 +809,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(AreaMomentOfInertia))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(AreaMomentOfInertiaUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal(AreaMomentOfInertia.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal(AreaMomentOfInertia.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal(new {AreaMomentOfInertia.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 2af6f384b2..709b436743 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AreaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AreaTestsBase.g.cs @@ -148,7 +148,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Area(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -161,15 +161,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Area_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + AreaUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Area(1, AreaUnit.SquareMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Area.Zero, quantityInfo.Zero); Assert.Equal("Area", quantityInfo.Name); + Assert.Equal(Area.Zero, quantityInfo.Zero); + Assert.Equal(Area.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Area.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void AreaInfo_CreateWithCustomUnitInfos() + { + AreaUnit[] expectedUnits = [AreaUnit.SquareMeter]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -196,59 +214,59 @@ public void SquareMeterToAreaUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Area.From(1, AreaUnit.Acre); - AssertEx.EqualTolerance(1, quantity00.Acres, AcresTolerance); + Assert.Equal(1, quantity00.Acres); Assert.Equal(AreaUnit.Acre, quantity00.Unit); var quantity01 = Area.From(1, AreaUnit.Hectare); - AssertEx.EqualTolerance(1, quantity01.Hectares, HectaresTolerance); + Assert.Equal(1, quantity01.Hectares); Assert.Equal(AreaUnit.Hectare, quantity01.Unit); var quantity02 = Area.From(1, AreaUnit.SquareCentimeter); - AssertEx.EqualTolerance(1, quantity02.SquareCentimeters, SquareCentimetersTolerance); + Assert.Equal(1, quantity02.SquareCentimeters); Assert.Equal(AreaUnit.SquareCentimeter, quantity02.Unit); var quantity03 = Area.From(1, AreaUnit.SquareDecimeter); - AssertEx.EqualTolerance(1, quantity03.SquareDecimeters, SquareDecimetersTolerance); + Assert.Equal(1, quantity03.SquareDecimeters); Assert.Equal(AreaUnit.SquareDecimeter, quantity03.Unit); var quantity04 = Area.From(1, AreaUnit.SquareFoot); - AssertEx.EqualTolerance(1, quantity04.SquareFeet, SquareFeetTolerance); + Assert.Equal(1, quantity04.SquareFeet); Assert.Equal(AreaUnit.SquareFoot, quantity04.Unit); var quantity05 = Area.From(1, AreaUnit.SquareInch); - AssertEx.EqualTolerance(1, quantity05.SquareInches, SquareInchesTolerance); + Assert.Equal(1, quantity05.SquareInches); Assert.Equal(AreaUnit.SquareInch, quantity05.Unit); var quantity06 = Area.From(1, AreaUnit.SquareKilometer); - AssertEx.EqualTolerance(1, quantity06.SquareKilometers, SquareKilometersTolerance); + Assert.Equal(1, quantity06.SquareKilometers); Assert.Equal(AreaUnit.SquareKilometer, quantity06.Unit); var quantity07 = Area.From(1, AreaUnit.SquareMeter); - AssertEx.EqualTolerance(1, quantity07.SquareMeters, SquareMetersTolerance); + Assert.Equal(1, quantity07.SquareMeters); Assert.Equal(AreaUnit.SquareMeter, quantity07.Unit); var quantity08 = Area.From(1, AreaUnit.SquareMicrometer); - AssertEx.EqualTolerance(1, quantity08.SquareMicrometers, SquareMicrometersTolerance); + Assert.Equal(1, quantity08.SquareMicrometers); Assert.Equal(AreaUnit.SquareMicrometer, quantity08.Unit); var quantity09 = Area.From(1, AreaUnit.SquareMile); - AssertEx.EqualTolerance(1, quantity09.SquareMiles, SquareMilesTolerance); + Assert.Equal(1, quantity09.SquareMiles); Assert.Equal(AreaUnit.SquareMile, quantity09.Unit); var quantity10 = Area.From(1, AreaUnit.SquareMillimeter); - AssertEx.EqualTolerance(1, quantity10.SquareMillimeters, SquareMillimetersTolerance); + Assert.Equal(1, quantity10.SquareMillimeters); Assert.Equal(AreaUnit.SquareMillimeter, quantity10.Unit); var quantity11 = Area.From(1, AreaUnit.SquareNauticalMile); - AssertEx.EqualTolerance(1, quantity11.SquareNauticalMiles, SquareNauticalMilesTolerance); + Assert.Equal(1, quantity11.SquareNauticalMiles); Assert.Equal(AreaUnit.SquareNauticalMile, quantity11.Unit); var quantity12 = Area.From(1, AreaUnit.SquareYard); - AssertEx.EqualTolerance(1, quantity12.SquareYards, SquareYardsTolerance); + Assert.Equal(1, quantity12.SquareYards); Assert.Equal(AreaUnit.SquareYard, quantity12.Unit); var quantity13 = Area.From(1, AreaUnit.UsSurveySquareFoot); - AssertEx.EqualTolerance(1, quantity13.UsSurveySquareFeet, UsSurveySquareFeetTolerance); + Assert.Equal(1, quantity13.UsSurveySquareFeet); Assert.Equal(AreaUnit.UsSurveySquareFoot, quantity13.Unit); } @@ -397,535 +415,114 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 ac", AreaUnit.Acre, 4.2)] + [InlineData("en-US", "4.2 ha", AreaUnit.Hectare, 4.2)] + [InlineData("en-US", "4.2 cm²", AreaUnit.SquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 dm²", AreaUnit.SquareDecimeter, 4.2)] + [InlineData("en-US", "4.2 ft²", AreaUnit.SquareFoot, 4.2)] + [InlineData("en-US", "4.2 in²", AreaUnit.SquareInch, 4.2)] + [InlineData("en-US", "4.2 km²", AreaUnit.SquareKilometer, 4.2)] + [InlineData("en-US", "4.2 m²", AreaUnit.SquareMeter, 4.2)] + [InlineData("en-US", "4.2 µm²", AreaUnit.SquareMicrometer, 4.2)] + [InlineData("en-US", "4.2 mi²", AreaUnit.SquareMile, 4.2)] + [InlineData("en-US", "4.2 mm²", AreaUnit.SquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 nmi²", AreaUnit.SquareNauticalMile, 4.2)] + [InlineData("en-US", "4.2 yd²", AreaUnit.SquareYard, 4.2)] + [InlineData("en-US", "4.2 ft² (US)", AreaUnit.UsSurveySquareFoot, 4.2)] + [InlineData("ru-RU", "4,2 акр", AreaUnit.Acre, 4.2)] + [InlineData("ru-RU", "4,2 га", AreaUnit.Hectare, 4.2)] + [InlineData("ru-RU", "4,2 см²", AreaUnit.SquareCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 дм²", AreaUnit.SquareDecimeter, 4.2)] + [InlineData("ru-RU", "4,2 фут²", AreaUnit.SquareFoot, 4.2)] + [InlineData("ru-RU", "4,2 дюйм²", AreaUnit.SquareInch, 4.2)] + [InlineData("ru-RU", "4,2 км²", AreaUnit.SquareKilometer, 4.2)] + [InlineData("ru-RU", "4,2 м²", AreaUnit.SquareMeter, 4.2)] + [InlineData("ru-RU", "4,2 мкм²", AreaUnit.SquareMicrometer, 4.2)] + [InlineData("ru-RU", "4,2 миля²", AreaUnit.SquareMile, 4.2)] + [InlineData("ru-RU", "4,2 мм²", AreaUnit.SquareMillimeter, 4.2)] + [InlineData("ru-RU", "4,2 морск.миля²", AreaUnit.SquareNauticalMile, 4.2)] + [InlineData("ru-RU", "4,2 ярд²", AreaUnit.SquareYard, 4.2)] + [InlineData("ru-RU", "4,2 фут² (US)", AreaUnit.UsSurveySquareFoot, 4.2)] + [InlineData("zh-CN", "4.2 平方厘米", AreaUnit.SquareCentimeter, 4.2)] + [InlineData("zh-CN", "4.2 平方分米", AreaUnit.SquareDecimeter, 4.2)] + [InlineData("zh-CN", "4.2 平方英尺", AreaUnit.SquareFoot, 4.2)] + [InlineData("zh-CN", "4.2 平方英寸", AreaUnit.SquareInch, 4.2)] + [InlineData("zh-CN", "4.2 平方公里", AreaUnit.SquareKilometer, 4.2)] + [InlineData("zh-CN", "4.2 平方米", AreaUnit.SquareMeter, 4.2)] + [InlineData("zh-CN", "4.2 平方微米", AreaUnit.SquareMicrometer, 4.2)] + [InlineData("zh-CN", "4.2 平方英里", AreaUnit.SquareMile, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = Area.Parse("1 ac", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Acres, AcresTolerance); - Assert.Equal(AreaUnit.Acre, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 акр", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Acres, AcresTolerance); - Assert.Equal(AreaUnit.Acre, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 英亩", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Acres, AcresTolerance); - Assert.Equal(AreaUnit.Acre, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 ha", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Hectares, HectaresTolerance); - Assert.Equal(AreaUnit.Hectare, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 га", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Hectares, HectaresTolerance); - Assert.Equal(AreaUnit.Hectare, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 英亩", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Hectares, HectaresTolerance); - Assert.Equal(AreaUnit.Hectare, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SquareCentimeters, SquareCentimetersTolerance); - Assert.Equal(AreaUnit.SquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 см²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.SquareCentimeters, SquareCentimetersTolerance); - Assert.Equal(AreaUnit.SquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 平方厘米", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.SquareCentimeters, SquareCentimetersTolerance); - Assert.Equal(AreaUnit.SquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 dm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SquareDecimeters, SquareDecimetersTolerance); - Assert.Equal(AreaUnit.SquareDecimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 дм²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.SquareDecimeters, SquareDecimetersTolerance); - Assert.Equal(AreaUnit.SquareDecimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 平方分米", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.SquareDecimeters, SquareDecimetersTolerance); - Assert.Equal(AreaUnit.SquareDecimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 ft²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SquareFeet, SquareFeetTolerance); - Assert.Equal(AreaUnit.SquareFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 фут²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.SquareFeet, SquareFeetTolerance); - Assert.Equal(AreaUnit.SquareFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 平方英尺", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.SquareFeet, SquareFeetTolerance); - Assert.Equal(AreaUnit.SquareFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 in²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SquareInches, SquareInchesTolerance); - Assert.Equal(AreaUnit.SquareInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 дюйм²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.SquareInches, SquareInchesTolerance); - Assert.Equal(AreaUnit.SquareInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 平方英寸", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.SquareInches, SquareInchesTolerance); - Assert.Equal(AreaUnit.SquareInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 km²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SquareKilometers, SquareKilometersTolerance); - Assert.Equal(AreaUnit.SquareKilometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 км²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.SquareKilometers, SquareKilometersTolerance); - Assert.Equal(AreaUnit.SquareKilometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 平方公里", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.SquareKilometers, SquareKilometersTolerance); - Assert.Equal(AreaUnit.SquareKilometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SquareMeters, SquareMetersTolerance); - Assert.Equal(AreaUnit.SquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 м²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.SquareMeters, SquareMetersTolerance); - Assert.Equal(AreaUnit.SquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 平方米", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.SquareMeters, SquareMetersTolerance); - Assert.Equal(AreaUnit.SquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 µm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SquareMicrometers, SquareMicrometersTolerance); - Assert.Equal(AreaUnit.SquareMicrometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 мкм²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.SquareMicrometers, SquareMicrometersTolerance); - Assert.Equal(AreaUnit.SquareMicrometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 平方微米", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.SquareMicrometers, SquareMicrometersTolerance); - Assert.Equal(AreaUnit.SquareMicrometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 mi²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SquareMiles, SquareMilesTolerance); - Assert.Equal(AreaUnit.SquareMile, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 миля²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.SquareMiles, SquareMilesTolerance); - Assert.Equal(AreaUnit.SquareMile, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 平方英里", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.SquareMiles, SquareMilesTolerance); - Assert.Equal(AreaUnit.SquareMile, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 mm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SquareMillimeters, SquareMillimetersTolerance); - Assert.Equal(AreaUnit.SquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 мм²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.SquareMillimeters, SquareMillimetersTolerance); - Assert.Equal(AreaUnit.SquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 平方毫米", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.SquareMillimeters, SquareMillimetersTolerance); - Assert.Equal(AreaUnit.SquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 nmi²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SquareNauticalMiles, SquareNauticalMilesTolerance); - Assert.Equal(AreaUnit.SquareNauticalMile, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 морск.миля²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.SquareNauticalMiles, SquareNauticalMilesTolerance); - Assert.Equal(AreaUnit.SquareNauticalMile, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 平方海里", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.SquareNauticalMiles, SquareNauticalMilesTolerance); - Assert.Equal(AreaUnit.SquareNauticalMile, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 yd²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SquareYards, SquareYardsTolerance); - Assert.Equal(AreaUnit.SquareYard, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 ярд²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.SquareYards, SquareYardsTolerance); - Assert.Equal(AreaUnit.SquareYard, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 平方码", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.SquareYards, SquareYardsTolerance); - Assert.Equal(AreaUnit.SquareYard, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 ft² (US)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.UsSurveySquareFeet, UsSurveySquareFeetTolerance); - Assert.Equal(AreaUnit.UsSurveySquareFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Area.Parse("1 фут² (US)", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.UsSurveySquareFeet, UsSurveySquareFeetTolerance); - Assert.Equal(AreaUnit.UsSurveySquareFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Area.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("zh-CN", "1 英亩")] // [Acre, Hectare] + public void ParseWithAmbiguousAbbreviation(string culture, string quantityString) { - { - Assert.True(Area.TryParse("1 ac", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Acres, AcresTolerance); - Assert.Equal(AreaUnit.Acre, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 акр", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Acres, AcresTolerance); - Assert.Equal(AreaUnit.Acre, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 ha", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Hectares, HectaresTolerance); - Assert.Equal(AreaUnit.Hectare, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 га", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Hectares, HectaresTolerance); - Assert.Equal(AreaUnit.Hectare, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 cm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareCentimeters, SquareCentimetersTolerance); - Assert.Equal(AreaUnit.SquareCentimeter, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 см²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareCentimeters, SquareCentimetersTolerance); - Assert.Equal(AreaUnit.SquareCentimeter, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 平方厘米", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareCentimeters, SquareCentimetersTolerance); - Assert.Equal(AreaUnit.SquareCentimeter, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 dm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareDecimeters, SquareDecimetersTolerance); - Assert.Equal(AreaUnit.SquareDecimeter, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 дм²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareDecimeters, SquareDecimetersTolerance); - Assert.Equal(AreaUnit.SquareDecimeter, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 平方分米", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareDecimeters, SquareDecimetersTolerance); - Assert.Equal(AreaUnit.SquareDecimeter, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 ft²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareFeet, SquareFeetTolerance); - Assert.Equal(AreaUnit.SquareFoot, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 фут²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareFeet, SquareFeetTolerance); - Assert.Equal(AreaUnit.SquareFoot, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 平方英尺", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareFeet, SquareFeetTolerance); - Assert.Equal(AreaUnit.SquareFoot, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 in²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareInches, SquareInchesTolerance); - Assert.Equal(AreaUnit.SquareInch, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 дюйм²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareInches, SquareInchesTolerance); - Assert.Equal(AreaUnit.SquareInch, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 平方英寸", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareInches, SquareInchesTolerance); - Assert.Equal(AreaUnit.SquareInch, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 km²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareKilometers, SquareKilometersTolerance); - Assert.Equal(AreaUnit.SquareKilometer, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 км²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareKilometers, SquareKilometersTolerance); - Assert.Equal(AreaUnit.SquareKilometer, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 平方公里", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareKilometers, SquareKilometersTolerance); - Assert.Equal(AreaUnit.SquareKilometer, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareMeters, SquareMetersTolerance); - Assert.Equal(AreaUnit.SquareMeter, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 м²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareMeters, SquareMetersTolerance); - Assert.Equal(AreaUnit.SquareMeter, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 平方米", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareMeters, SquareMetersTolerance); - Assert.Equal(AreaUnit.SquareMeter, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 µm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareMicrometers, SquareMicrometersTolerance); - Assert.Equal(AreaUnit.SquareMicrometer, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 мкм²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareMicrometers, SquareMicrometersTolerance); - Assert.Equal(AreaUnit.SquareMicrometer, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 平方微米", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareMicrometers, SquareMicrometersTolerance); - Assert.Equal(AreaUnit.SquareMicrometer, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 mi²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareMiles, SquareMilesTolerance); - Assert.Equal(AreaUnit.SquareMile, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 миля²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareMiles, SquareMilesTolerance); - Assert.Equal(AreaUnit.SquareMile, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 平方英里", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareMiles, SquareMilesTolerance); - Assert.Equal(AreaUnit.SquareMile, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 mm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareMillimeters, SquareMillimetersTolerance); - Assert.Equal(AreaUnit.SquareMillimeter, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 мм²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareMillimeters, SquareMillimetersTolerance); - Assert.Equal(AreaUnit.SquareMillimeter, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 平方毫米", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareMillimeters, SquareMillimetersTolerance); - Assert.Equal(AreaUnit.SquareMillimeter, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 nmi²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareNauticalMiles, SquareNauticalMilesTolerance); - Assert.Equal(AreaUnit.SquareNauticalMile, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 морск.миля²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareNauticalMiles, SquareNauticalMilesTolerance); - Assert.Equal(AreaUnit.SquareNauticalMile, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 平方海里", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareNauticalMiles, SquareNauticalMilesTolerance); - Assert.Equal(AreaUnit.SquareNauticalMile, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 yd²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareYards, SquareYardsTolerance); - Assert.Equal(AreaUnit.SquareYard, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 ярд²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareYards, SquareYardsTolerance); - Assert.Equal(AreaUnit.SquareYard, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 平方码", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareYards, SquareYardsTolerance); - Assert.Equal(AreaUnit.SquareYard, parsed.Unit); - } - - { - Assert.True(Area.TryParse("1 ft² (US)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UsSurveySquareFeet, UsSurveySquareFeetTolerance); - Assert.Equal(AreaUnit.UsSurveySquareFoot, parsed.Unit); - } + Assert.Throws(() => Area.Parse(quantityString, CultureInfo.GetCultureInfo(culture))); + } - { - Assert.True(Area.TryParse("1 фут² (US)", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UsSurveySquareFeet, UsSurveySquareFeetTolerance); - Assert.Equal(AreaUnit.UsSurveySquareFoot, parsed.Unit); - } + [Theory] + [InlineData("en-US", "4.2 ac", AreaUnit.Acre, 4.2)] + [InlineData("en-US", "4.2 ha", AreaUnit.Hectare, 4.2)] + [InlineData("en-US", "4.2 cm²", AreaUnit.SquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 dm²", AreaUnit.SquareDecimeter, 4.2)] + [InlineData("en-US", "4.2 ft²", AreaUnit.SquareFoot, 4.2)] + [InlineData("en-US", "4.2 in²", AreaUnit.SquareInch, 4.2)] + [InlineData("en-US", "4.2 km²", AreaUnit.SquareKilometer, 4.2)] + [InlineData("en-US", "4.2 m²", AreaUnit.SquareMeter, 4.2)] + [InlineData("en-US", "4.2 µm²", AreaUnit.SquareMicrometer, 4.2)] + [InlineData("en-US", "4.2 mi²", AreaUnit.SquareMile, 4.2)] + [InlineData("en-US", "4.2 mm²", AreaUnit.SquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 nmi²", AreaUnit.SquareNauticalMile, 4.2)] + [InlineData("en-US", "4.2 yd²", AreaUnit.SquareYard, 4.2)] + [InlineData("en-US", "4.2 ft² (US)", AreaUnit.UsSurveySquareFoot, 4.2)] + [InlineData("ru-RU", "4,2 акр", AreaUnit.Acre, 4.2)] + [InlineData("ru-RU", "4,2 га", AreaUnit.Hectare, 4.2)] + [InlineData("ru-RU", "4,2 см²", AreaUnit.SquareCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 дм²", AreaUnit.SquareDecimeter, 4.2)] + [InlineData("ru-RU", "4,2 фут²", AreaUnit.SquareFoot, 4.2)] + [InlineData("ru-RU", "4,2 дюйм²", AreaUnit.SquareInch, 4.2)] + [InlineData("ru-RU", "4,2 км²", AreaUnit.SquareKilometer, 4.2)] + [InlineData("ru-RU", "4,2 м²", AreaUnit.SquareMeter, 4.2)] + [InlineData("ru-RU", "4,2 мкм²", AreaUnit.SquareMicrometer, 4.2)] + [InlineData("ru-RU", "4,2 миля²", AreaUnit.SquareMile, 4.2)] + [InlineData("ru-RU", "4,2 мм²", AreaUnit.SquareMillimeter, 4.2)] + [InlineData("ru-RU", "4,2 морск.миля²", AreaUnit.SquareNauticalMile, 4.2)] + [InlineData("ru-RU", "4,2 ярд²", AreaUnit.SquareYard, 4.2)] + [InlineData("ru-RU", "4,2 фут² (US)", AreaUnit.UsSurveySquareFoot, 4.2)] + [InlineData("zh-CN", "4.2 平方厘米", AreaUnit.SquareCentimeter, 4.2)] + [InlineData("zh-CN", "4.2 平方分米", AreaUnit.SquareDecimeter, 4.2)] + [InlineData("zh-CN", "4.2 平方英尺", AreaUnit.SquareFoot, 4.2)] + [InlineData("zh-CN", "4.2 平方英寸", AreaUnit.SquareInch, 4.2)] + [InlineData("zh-CN", "4.2 平方公里", AreaUnit.SquareKilometer, 4.2)] + [InlineData("zh-CN", "4.2 平方米", AreaUnit.SquareMeter, 4.2)] + [InlineData("zh-CN", "4.2 平方微米", AreaUnit.SquareMicrometer, 4.2)] + [InlineData("zh-CN", "4.2 平方英里", AreaUnit.SquareMile, 4.2)] + [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, decimal expectedValue) + { + using var _ = new CultureScope(culture); + Assert.True(Area.TryParse(quantityString, out Area parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); + } + [Theory] + [InlineData("zh-CN", "1 英亩")] // [Acre, Hectare] + public void TryParseWithAmbiguousAbbreviation(string culture, string quantityString) + { + Assert.False(Area.TryParse(quantityString, CultureInfo.GetCultureInfo(culture), out _)); } [Theory] @@ -1220,6 +817,67 @@ public void TryParseUnitWithAmbiguousAbbreviation(string culture, string abbrevi Assert.False(Area.TryParseUnit(abbreviation, CultureInfo.GetCultureInfo(culture), out _)); } + [Theory] + [InlineData("en-US", AreaUnit.Acre, "ac")] + [InlineData("en-US", AreaUnit.Hectare, "ha")] + [InlineData("en-US", AreaUnit.SquareCentimeter, "cm²")] + [InlineData("en-US", AreaUnit.SquareDecimeter, "dm²")] + [InlineData("en-US", AreaUnit.SquareFoot, "ft²")] + [InlineData("en-US", AreaUnit.SquareInch, "in²")] + [InlineData("en-US", AreaUnit.SquareKilometer, "km²")] + [InlineData("en-US", AreaUnit.SquareMeter, "m²")] + [InlineData("en-US", AreaUnit.SquareMicrometer, "µm²")] + [InlineData("en-US", AreaUnit.SquareMile, "mi²")] + [InlineData("en-US", AreaUnit.SquareMillimeter, "mm²")] + [InlineData("en-US", AreaUnit.SquareNauticalMile, "nmi²")] + [InlineData("en-US", AreaUnit.SquareYard, "yd²")] + [InlineData("en-US", AreaUnit.UsSurveySquareFoot, "ft² (US)")] + [InlineData("ru-RU", AreaUnit.Acre, "акр")] + [InlineData("ru-RU", AreaUnit.Hectare, "га")] + [InlineData("ru-RU", AreaUnit.SquareCentimeter, "см²")] + [InlineData("ru-RU", AreaUnit.SquareDecimeter, "дм²")] + [InlineData("ru-RU", AreaUnit.SquareFoot, "фут²")] + [InlineData("ru-RU", AreaUnit.SquareInch, "дюйм²")] + [InlineData("ru-RU", AreaUnit.SquareKilometer, "км²")] + [InlineData("ru-RU", AreaUnit.SquareMeter, "м²")] + [InlineData("ru-RU", AreaUnit.SquareMicrometer, "мкм²")] + [InlineData("ru-RU", AreaUnit.SquareMile, "миля²")] + [InlineData("ru-RU", AreaUnit.SquareMillimeter, "мм²")] + [InlineData("ru-RU", AreaUnit.SquareNauticalMile, "морск.миля²")] + [InlineData("ru-RU", AreaUnit.SquareYard, "ярд²")] + [InlineData("ru-RU", AreaUnit.UsSurveySquareFoot, "фут² (US)")] + [InlineData("zh-CN", AreaUnit.Acre, "英亩")] + [InlineData("zh-CN", AreaUnit.Hectare, "英亩")] + [InlineData("zh-CN", AreaUnit.SquareCentimeter, "平方厘米")] + [InlineData("zh-CN", AreaUnit.SquareDecimeter, "平方分米")] + [InlineData("zh-CN", AreaUnit.SquareFoot, "平方英尺")] + [InlineData("zh-CN", AreaUnit.SquareInch, "平方英寸")] + [InlineData("zh-CN", AreaUnit.SquareKilometer, "平方公里")] + [InlineData("zh-CN", AreaUnit.SquareMeter, "平方米")] + [InlineData("zh-CN", AreaUnit.SquareMicrometer, "平方微米")] + [InlineData("zh-CN", AreaUnit.SquareMile, "平方英里")] + [InlineData("zh-CN", AreaUnit.SquareMillimeter, "平方毫米")] + [InlineData("zh-CN", AreaUnit.SquareNauticalMile, "平方海里")] + [InlineData("zh-CN", AreaUnit.SquareYard, "平方码")] + public void GetAbbreviationForCulture(string culture, AreaUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Area.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Area.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Area.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(AreaUnit unit) @@ -1250,6 +908,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); }); } @@ -1273,45 +932,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] @@ -1357,8 +1018,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); @@ -1395,23 +1054,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = Area.FromSquareMeters(1); - Assert.True(v.Equals(Area.FromSquareMeters(1), SquareMetersTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Area.Zero, SquareMetersTolerance, ComparisonType.Relative)); - Assert.True(Area.FromSquareMeters(100).Equals(Area.FromSquareMeters(120), 0.3, ComparisonType.Relative)); - Assert.False(Area.FromSquareMeters(100).Equals(Area.FromSquareMeters(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = Area.FromSquareMeters(1); - Assert.Throws(() => v.Equals(Area.FromSquareMeters(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1426,6 +1068,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(squaremeter.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = Area.FromSquareMeters(1); + var negativeTolerance = Area.FromSquareMeters(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1442,6 +1110,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() { @@ -1526,158 +1206,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Area.FromSquareMeters(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Area.FromSquareMeters(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Area.FromSquareMeters(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Area.FromSquareMeters(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Area.FromSquareMeters(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Area.FromSquareMeters(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Area.FromSquareMeters(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Area.FromSquareMeters(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Area.FromSquareMeters(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Area.FromSquareMeters(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Area.FromSquareMeters(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Area.FromSquareMeters(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Area.FromSquareMeters(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Area.FromSquareMeters(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Area.FromSquareMeters(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Area.FromSquareMeters(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Area))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Area.FromSquareMeters(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(AreaUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Area.FromSquareMeters(1.0); - Assert.Equal(Area.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Area.FromSquareMeters(1.0); - Assert.Equal(Area.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Area.FromSquareMeters(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Area.FromSquareMeters(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Area.FromSquareMeters(1.0); - Assert.Equal(new {Area.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 430c1f4f32..f9a29acad6 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/BitRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/BitRateTestsBase.g.cs @@ -196,7 +196,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new BitRate(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -209,15 +209,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void BitRate_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + BitRateUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new BitRate(1, BitRateUnit.BitPerSecond); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(BitRate.Zero, quantityInfo.Zero); Assert.Equal("BitRate", quantityInfo.Name); + Assert.Equal(BitRate.Zero, quantityInfo.Zero); + Assert.Equal(BitRate.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(BitRate.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void BitRateInfo_CreateWithCustomUnitInfos() + { + BitRateUnit[] expectedUnits = [BitRateUnit.BitPerSecond]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -256,107 +274,107 @@ public void BitPerSecondToBitRateUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = BitRate.From(1, BitRateUnit.BitPerSecond); - AssertEx.EqualTolerance(1, quantity00.BitsPerSecond, BitsPerSecondTolerance); + Assert.Equal(1, quantity00.BitsPerSecond); Assert.Equal(BitRateUnit.BitPerSecond, quantity00.Unit); var quantity01 = BitRate.From(1, BitRateUnit.BytePerSecond); - AssertEx.EqualTolerance(1, quantity01.BytesPerSecond, BytesPerSecondTolerance); + Assert.Equal(1, quantity01.BytesPerSecond); Assert.Equal(BitRateUnit.BytePerSecond, quantity01.Unit); var quantity02 = BitRate.From(1, BitRateUnit.ExabitPerSecond); - AssertEx.EqualTolerance(1, quantity02.ExabitsPerSecond, ExabitsPerSecondTolerance); + Assert.Equal(1, quantity02.ExabitsPerSecond); Assert.Equal(BitRateUnit.ExabitPerSecond, quantity02.Unit); var quantity03 = BitRate.From(1, BitRateUnit.ExabytePerSecond); - AssertEx.EqualTolerance(1, quantity03.ExabytesPerSecond, ExabytesPerSecondTolerance); + Assert.Equal(1, quantity03.ExabytesPerSecond); Assert.Equal(BitRateUnit.ExabytePerSecond, quantity03.Unit); var quantity04 = BitRate.From(1, BitRateUnit.ExbibitPerSecond); - AssertEx.EqualTolerance(1, quantity04.ExbibitsPerSecond, ExbibitsPerSecondTolerance); + Assert.Equal(1, quantity04.ExbibitsPerSecond); Assert.Equal(BitRateUnit.ExbibitPerSecond, quantity04.Unit); var quantity05 = BitRate.From(1, BitRateUnit.ExbibytePerSecond); - AssertEx.EqualTolerance(1, quantity05.ExbibytesPerSecond, ExbibytesPerSecondTolerance); + Assert.Equal(1, quantity05.ExbibytesPerSecond); Assert.Equal(BitRateUnit.ExbibytePerSecond, quantity05.Unit); var quantity06 = BitRate.From(1, BitRateUnit.GibibitPerSecond); - AssertEx.EqualTolerance(1, quantity06.GibibitsPerSecond, GibibitsPerSecondTolerance); + Assert.Equal(1, quantity06.GibibitsPerSecond); Assert.Equal(BitRateUnit.GibibitPerSecond, quantity06.Unit); var quantity07 = BitRate.From(1, BitRateUnit.GibibytePerSecond); - AssertEx.EqualTolerance(1, quantity07.GibibytesPerSecond, GibibytesPerSecondTolerance); + Assert.Equal(1, quantity07.GibibytesPerSecond); Assert.Equal(BitRateUnit.GibibytePerSecond, quantity07.Unit); var quantity08 = BitRate.From(1, BitRateUnit.GigabitPerSecond); - AssertEx.EqualTolerance(1, quantity08.GigabitsPerSecond, GigabitsPerSecondTolerance); + Assert.Equal(1, quantity08.GigabitsPerSecond); Assert.Equal(BitRateUnit.GigabitPerSecond, quantity08.Unit); var quantity09 = BitRate.From(1, BitRateUnit.GigabytePerSecond); - AssertEx.EqualTolerance(1, quantity09.GigabytesPerSecond, GigabytesPerSecondTolerance); + Assert.Equal(1, quantity09.GigabytesPerSecond); Assert.Equal(BitRateUnit.GigabytePerSecond, quantity09.Unit); var quantity10 = BitRate.From(1, BitRateUnit.KibibitPerSecond); - AssertEx.EqualTolerance(1, quantity10.KibibitsPerSecond, KibibitsPerSecondTolerance); + Assert.Equal(1, quantity10.KibibitsPerSecond); Assert.Equal(BitRateUnit.KibibitPerSecond, quantity10.Unit); var quantity11 = BitRate.From(1, BitRateUnit.KibibytePerSecond); - AssertEx.EqualTolerance(1, quantity11.KibibytesPerSecond, KibibytesPerSecondTolerance); + Assert.Equal(1, quantity11.KibibytesPerSecond); Assert.Equal(BitRateUnit.KibibytePerSecond, quantity11.Unit); var quantity12 = BitRate.From(1, BitRateUnit.KilobitPerSecond); - AssertEx.EqualTolerance(1, quantity12.KilobitsPerSecond, KilobitsPerSecondTolerance); + Assert.Equal(1, quantity12.KilobitsPerSecond); Assert.Equal(BitRateUnit.KilobitPerSecond, quantity12.Unit); var quantity13 = BitRate.From(1, BitRateUnit.KilobytePerSecond); - AssertEx.EqualTolerance(1, quantity13.KilobytesPerSecond, KilobytesPerSecondTolerance); + Assert.Equal(1, quantity13.KilobytesPerSecond); Assert.Equal(BitRateUnit.KilobytePerSecond, quantity13.Unit); var quantity14 = BitRate.From(1, BitRateUnit.MebibitPerSecond); - AssertEx.EqualTolerance(1, quantity14.MebibitsPerSecond, MebibitsPerSecondTolerance); + Assert.Equal(1, quantity14.MebibitsPerSecond); Assert.Equal(BitRateUnit.MebibitPerSecond, quantity14.Unit); var quantity15 = BitRate.From(1, BitRateUnit.MebibytePerSecond); - AssertEx.EqualTolerance(1, quantity15.MebibytesPerSecond, MebibytesPerSecondTolerance); + Assert.Equal(1, quantity15.MebibytesPerSecond); Assert.Equal(BitRateUnit.MebibytePerSecond, quantity15.Unit); var quantity16 = BitRate.From(1, BitRateUnit.MegabitPerSecond); - AssertEx.EqualTolerance(1, quantity16.MegabitsPerSecond, MegabitsPerSecondTolerance); + Assert.Equal(1, quantity16.MegabitsPerSecond); Assert.Equal(BitRateUnit.MegabitPerSecond, quantity16.Unit); var quantity17 = BitRate.From(1, BitRateUnit.MegabytePerSecond); - AssertEx.EqualTolerance(1, quantity17.MegabytesPerSecond, MegabytesPerSecondTolerance); + Assert.Equal(1, quantity17.MegabytesPerSecond); Assert.Equal(BitRateUnit.MegabytePerSecond, quantity17.Unit); var quantity18 = BitRate.From(1, BitRateUnit.PebibitPerSecond); - AssertEx.EqualTolerance(1, quantity18.PebibitsPerSecond, PebibitsPerSecondTolerance); + Assert.Equal(1, quantity18.PebibitsPerSecond); Assert.Equal(BitRateUnit.PebibitPerSecond, quantity18.Unit); var quantity19 = BitRate.From(1, BitRateUnit.PebibytePerSecond); - AssertEx.EqualTolerance(1, quantity19.PebibytesPerSecond, PebibytesPerSecondTolerance); + Assert.Equal(1, quantity19.PebibytesPerSecond); Assert.Equal(BitRateUnit.PebibytePerSecond, quantity19.Unit); var quantity20 = BitRate.From(1, BitRateUnit.PetabitPerSecond); - AssertEx.EqualTolerance(1, quantity20.PetabitsPerSecond, PetabitsPerSecondTolerance); + Assert.Equal(1, quantity20.PetabitsPerSecond); Assert.Equal(BitRateUnit.PetabitPerSecond, quantity20.Unit); var quantity21 = BitRate.From(1, BitRateUnit.PetabytePerSecond); - AssertEx.EqualTolerance(1, quantity21.PetabytesPerSecond, PetabytesPerSecondTolerance); + Assert.Equal(1, quantity21.PetabytesPerSecond); Assert.Equal(BitRateUnit.PetabytePerSecond, quantity21.Unit); var quantity22 = BitRate.From(1, BitRateUnit.TebibitPerSecond); - AssertEx.EqualTolerance(1, quantity22.TebibitsPerSecond, TebibitsPerSecondTolerance); + Assert.Equal(1, quantity22.TebibitsPerSecond); Assert.Equal(BitRateUnit.TebibitPerSecond, quantity22.Unit); var quantity23 = BitRate.From(1, BitRateUnit.TebibytePerSecond); - AssertEx.EqualTolerance(1, quantity23.TebibytesPerSecond, TebibytesPerSecondTolerance); + Assert.Equal(1, quantity23.TebibytesPerSecond); Assert.Equal(BitRateUnit.TebibytePerSecond, quantity23.Unit); var quantity24 = BitRate.From(1, BitRateUnit.TerabitPerSecond); - AssertEx.EqualTolerance(1, quantity24.TerabitsPerSecond, TerabitsPerSecondTolerance); + Assert.Equal(1, quantity24.TerabitsPerSecond); Assert.Equal(BitRateUnit.TerabitPerSecond, quantity24.Unit); var quantity25 = BitRate.From(1, BitRateUnit.TerabytePerSecond); - AssertEx.EqualTolerance(1, quantity25.TerabytesPerSecond, TerabytesPerSecondTolerance); + Assert.Equal(1, quantity25.TerabytesPerSecond); Assert.Equal(BitRateUnit.TerabytePerSecond, quantity25.Unit); } @@ -517,521 +535,100 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 bit/s", BitRateUnit.BitPerSecond, 4.2)] + [InlineData("en-US", "4.2 bps", BitRateUnit.BitPerSecond, 4.2)] + [InlineData("en-US", "4.2 B/s", BitRateUnit.BytePerSecond, 4.2)] + [InlineData("en-US", "4.2 Ebit/s", BitRateUnit.ExabitPerSecond, 4.2)] + [InlineData("en-US", "4.2 Ebps", BitRateUnit.ExabitPerSecond, 4.2)] + [InlineData("en-US", "4.2 EB/s", BitRateUnit.ExabytePerSecond, 4.2)] + [InlineData("en-US", "4.2 Eibit/s", BitRateUnit.ExbibitPerSecond, 4.2)] + [InlineData("en-US", "4.2 Eibps", BitRateUnit.ExbibitPerSecond, 4.2)] + [InlineData("en-US", "4.2 EiB/s", BitRateUnit.ExbibytePerSecond, 4.2)] + [InlineData("en-US", "4.2 Gibit/s", BitRateUnit.GibibitPerSecond, 4.2)] + [InlineData("en-US", "4.2 Gibps", BitRateUnit.GibibitPerSecond, 4.2)] + [InlineData("en-US", "4.2 GiB/s", BitRateUnit.GibibytePerSecond, 4.2)] + [InlineData("en-US", "4.2 Gbit/s", BitRateUnit.GigabitPerSecond, 4.2)] + [InlineData("en-US", "4.2 Gbps", BitRateUnit.GigabitPerSecond, 4.2)] + [InlineData("en-US", "4.2 GB/s", BitRateUnit.GigabytePerSecond, 4.2)] + [InlineData("en-US", "4.2 Kibit/s", BitRateUnit.KibibitPerSecond, 4.2)] + [InlineData("en-US", "4.2 Kibps", BitRateUnit.KibibitPerSecond, 4.2)] + [InlineData("en-US", "4.2 KiB/s", BitRateUnit.KibibytePerSecond, 4.2)] + [InlineData("en-US", "4.2 kbit/s", BitRateUnit.KilobitPerSecond, 4.2)] + [InlineData("en-US", "4.2 kbps", BitRateUnit.KilobitPerSecond, 4.2)] + [InlineData("en-US", "4.2 kB/s", BitRateUnit.KilobytePerSecond, 4.2)] + [InlineData("en-US", "4.2 Mibit/s", BitRateUnit.MebibitPerSecond, 4.2)] + [InlineData("en-US", "4.2 Mibps", BitRateUnit.MebibitPerSecond, 4.2)] + [InlineData("en-US", "4.2 MiB/s", BitRateUnit.MebibytePerSecond, 4.2)] + [InlineData("en-US", "4.2 Mbit/s", BitRateUnit.MegabitPerSecond, 4.2)] + [InlineData("en-US", "4.2 Mbps", BitRateUnit.MegabitPerSecond, 4.2)] + [InlineData("en-US", "4.2 MB/s", BitRateUnit.MegabytePerSecond, 4.2)] + [InlineData("en-US", "4.2 Pibit/s", BitRateUnit.PebibitPerSecond, 4.2)] + [InlineData("en-US", "4.2 Pibps", BitRateUnit.PebibitPerSecond, 4.2)] + [InlineData("en-US", "4.2 PiB/s", BitRateUnit.PebibytePerSecond, 4.2)] + [InlineData("en-US", "4.2 Pbit/s", BitRateUnit.PetabitPerSecond, 4.2)] + [InlineData("en-US", "4.2 Pbps", BitRateUnit.PetabitPerSecond, 4.2)] + [InlineData("en-US", "4.2 PB/s", BitRateUnit.PetabytePerSecond, 4.2)] + [InlineData("en-US", "4.2 Tibit/s", BitRateUnit.TebibitPerSecond, 4.2)] + [InlineData("en-US", "4.2 Tibps", BitRateUnit.TebibitPerSecond, 4.2)] + [InlineData("en-US", "4.2 TiB/s", BitRateUnit.TebibytePerSecond, 4.2)] + [InlineData("en-US", "4.2 Tbit/s", BitRateUnit.TerabitPerSecond, 4.2)] + [InlineData("en-US", "4.2 Tbps", BitRateUnit.TerabitPerSecond, 4.2)] + [InlineData("en-US", "4.2 TB/s", BitRateUnit.TerabytePerSecond, 4.2)] + public void Parse(string culture, string quantityString, BitRateUnit expectedUnit, decimal expectedValue) { - try - { - var parsed = BitRate.Parse("1 bit/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.BitsPerSecond, BitsPerSecondTolerance); - Assert.Equal(BitRateUnit.BitPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 bps", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.BitsPerSecond, BitsPerSecondTolerance); - Assert.Equal(BitRateUnit.BitPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 B/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.BytesPerSecond, BytesPerSecondTolerance); - Assert.Equal(BitRateUnit.BytePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 Ebit/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ExabitsPerSecond, ExabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.ExabitPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 Ebps", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ExabitsPerSecond, ExabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.ExabitPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 EB/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ExabytesPerSecond, ExabytesPerSecondTolerance); - Assert.Equal(BitRateUnit.ExabytePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 Eibit/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ExbibitsPerSecond, ExbibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.ExbibitPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 Eibps", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ExbibitsPerSecond, ExbibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.ExbibitPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 EiB/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ExbibytesPerSecond, ExbibytesPerSecondTolerance); - Assert.Equal(BitRateUnit.ExbibytePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 Gibit/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GibibitsPerSecond, GibibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.GibibitPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 Gibps", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GibibitsPerSecond, GibibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.GibibitPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 GiB/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GibibytesPerSecond, GibibytesPerSecondTolerance); - Assert.Equal(BitRateUnit.GibibytePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 Gbit/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GigabitsPerSecond, GigabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.GigabitPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 Gbps", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GigabitsPerSecond, GigabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.GigabitPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 GB/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GigabytesPerSecond, GigabytesPerSecondTolerance); - Assert.Equal(BitRateUnit.GigabytePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 Kibit/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KibibitsPerSecond, KibibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.KibibitPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 Kibps", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KibibitsPerSecond, KibibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.KibibitPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 KiB/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KibibytesPerSecond, KibibytesPerSecondTolerance); - Assert.Equal(BitRateUnit.KibibytePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 kbit/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilobitsPerSecond, KilobitsPerSecondTolerance); - Assert.Equal(BitRateUnit.KilobitPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 kbps", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilobitsPerSecond, KilobitsPerSecondTolerance); - Assert.Equal(BitRateUnit.KilobitPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 kB/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilobytesPerSecond, KilobytesPerSecondTolerance); - Assert.Equal(BitRateUnit.KilobytePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 Mibit/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MebibitsPerSecond, MebibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.MebibitPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 Mibps", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MebibitsPerSecond, MebibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.MebibitPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 MiB/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MebibytesPerSecond, MebibytesPerSecondTolerance); - Assert.Equal(BitRateUnit.MebibytePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 Mbit/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegabitsPerSecond, MegabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.MegabitPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 Mbps", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegabitsPerSecond, MegabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.MegabitPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 MB/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegabytesPerSecond, MegabytesPerSecondTolerance); - Assert.Equal(BitRateUnit.MegabytePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 Pibit/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PebibitsPerSecond, PebibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.PebibitPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 Pibps", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PebibitsPerSecond, PebibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.PebibitPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 PiB/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PebibytesPerSecond, PebibytesPerSecondTolerance); - Assert.Equal(BitRateUnit.PebibytePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 Pbit/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PetabitsPerSecond, PetabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.PetabitPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 Pbps", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PetabitsPerSecond, PetabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.PetabitPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 PB/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PetabytesPerSecond, PetabytesPerSecondTolerance); - Assert.Equal(BitRateUnit.PetabytePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 Tibit/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TebibitsPerSecond, TebibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.TebibitPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 Tibps", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TebibitsPerSecond, TebibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.TebibitPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 TiB/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TebibytesPerSecond, TebibytesPerSecondTolerance); - Assert.Equal(BitRateUnit.TebibytePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 Tbit/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TerabitsPerSecond, TerabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.TerabitPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 Tbps", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TerabitsPerSecond, TerabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.TerabitPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BitRate.Parse("1 TB/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TerabytesPerSecond, TerabytesPerSecondTolerance); - Assert.Equal(BitRateUnit.TerabytePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = BitRate.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 bit/s", BitRateUnit.BitPerSecond, 4.2)] + [InlineData("en-US", "4.2 bps", BitRateUnit.BitPerSecond, 4.2)] + [InlineData("en-US", "4.2 B/s", BitRateUnit.BytePerSecond, 4.2)] + [InlineData("en-US", "4.2 Ebit/s", BitRateUnit.ExabitPerSecond, 4.2)] + [InlineData("en-US", "4.2 Ebps", BitRateUnit.ExabitPerSecond, 4.2)] + [InlineData("en-US", "4.2 EB/s", BitRateUnit.ExabytePerSecond, 4.2)] + [InlineData("en-US", "4.2 Eibit/s", BitRateUnit.ExbibitPerSecond, 4.2)] + [InlineData("en-US", "4.2 Eibps", BitRateUnit.ExbibitPerSecond, 4.2)] + [InlineData("en-US", "4.2 EiB/s", BitRateUnit.ExbibytePerSecond, 4.2)] + [InlineData("en-US", "4.2 Gibit/s", BitRateUnit.GibibitPerSecond, 4.2)] + [InlineData("en-US", "4.2 Gibps", BitRateUnit.GibibitPerSecond, 4.2)] + [InlineData("en-US", "4.2 GiB/s", BitRateUnit.GibibytePerSecond, 4.2)] + [InlineData("en-US", "4.2 Gbit/s", BitRateUnit.GigabitPerSecond, 4.2)] + [InlineData("en-US", "4.2 Gbps", BitRateUnit.GigabitPerSecond, 4.2)] + [InlineData("en-US", "4.2 GB/s", BitRateUnit.GigabytePerSecond, 4.2)] + [InlineData("en-US", "4.2 Kibit/s", BitRateUnit.KibibitPerSecond, 4.2)] + [InlineData("en-US", "4.2 Kibps", BitRateUnit.KibibitPerSecond, 4.2)] + [InlineData("en-US", "4.2 KiB/s", BitRateUnit.KibibytePerSecond, 4.2)] + [InlineData("en-US", "4.2 kbit/s", BitRateUnit.KilobitPerSecond, 4.2)] + [InlineData("en-US", "4.2 kbps", BitRateUnit.KilobitPerSecond, 4.2)] + [InlineData("en-US", "4.2 kB/s", BitRateUnit.KilobytePerSecond, 4.2)] + [InlineData("en-US", "4.2 Mibit/s", BitRateUnit.MebibitPerSecond, 4.2)] + [InlineData("en-US", "4.2 Mibps", BitRateUnit.MebibitPerSecond, 4.2)] + [InlineData("en-US", "4.2 MiB/s", BitRateUnit.MebibytePerSecond, 4.2)] + [InlineData("en-US", "4.2 Mbit/s", BitRateUnit.MegabitPerSecond, 4.2)] + [InlineData("en-US", "4.2 Mbps", BitRateUnit.MegabitPerSecond, 4.2)] + [InlineData("en-US", "4.2 MB/s", BitRateUnit.MegabytePerSecond, 4.2)] + [InlineData("en-US", "4.2 Pibit/s", BitRateUnit.PebibitPerSecond, 4.2)] + [InlineData("en-US", "4.2 Pibps", BitRateUnit.PebibitPerSecond, 4.2)] + [InlineData("en-US", "4.2 PiB/s", BitRateUnit.PebibytePerSecond, 4.2)] + [InlineData("en-US", "4.2 Pbit/s", BitRateUnit.PetabitPerSecond, 4.2)] + [InlineData("en-US", "4.2 Pbps", BitRateUnit.PetabitPerSecond, 4.2)] + [InlineData("en-US", "4.2 PB/s", BitRateUnit.PetabytePerSecond, 4.2)] + [InlineData("en-US", "4.2 Tibit/s", BitRateUnit.TebibitPerSecond, 4.2)] + [InlineData("en-US", "4.2 Tibps", BitRateUnit.TebibitPerSecond, 4.2)] + [InlineData("en-US", "4.2 TiB/s", BitRateUnit.TebibytePerSecond, 4.2)] + [InlineData("en-US", "4.2 Tbit/s", BitRateUnit.TerabitPerSecond, 4.2)] + [InlineData("en-US", "4.2 Tbps", BitRateUnit.TerabitPerSecond, 4.2)] + [InlineData("en-US", "4.2 TB/s", BitRateUnit.TerabytePerSecond, 4.2)] + public void TryParse(string culture, string quantityString, BitRateUnit expectedUnit, decimal expectedValue) { - { - Assert.True(BitRate.TryParse("1 bit/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BitsPerSecond, BitsPerSecondTolerance); - Assert.Equal(BitRateUnit.BitPerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 bps", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BitsPerSecond, BitsPerSecondTolerance); - Assert.Equal(BitRateUnit.BitPerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 B/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BytesPerSecond, BytesPerSecondTolerance); - Assert.Equal(BitRateUnit.BytePerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 Ebit/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ExabitsPerSecond, ExabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.ExabitPerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 Ebps", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ExabitsPerSecond, ExabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.ExabitPerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 EB/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ExabytesPerSecond, ExabytesPerSecondTolerance); - Assert.Equal(BitRateUnit.ExabytePerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 Eibit/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ExbibitsPerSecond, ExbibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.ExbibitPerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 Eibps", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ExbibitsPerSecond, ExbibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.ExbibitPerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 EiB/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ExbibytesPerSecond, ExbibytesPerSecondTolerance); - Assert.Equal(BitRateUnit.ExbibytePerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 Gibit/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GibibitsPerSecond, GibibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.GibibitPerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 Gibps", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GibibitsPerSecond, GibibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.GibibitPerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 GiB/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GibibytesPerSecond, GibibytesPerSecondTolerance); - Assert.Equal(BitRateUnit.GibibytePerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 Gbit/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigabitsPerSecond, GigabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.GigabitPerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 Gbps", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigabitsPerSecond, GigabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.GigabitPerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 GB/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigabytesPerSecond, GigabytesPerSecondTolerance); - Assert.Equal(BitRateUnit.GigabytePerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 Kibit/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KibibitsPerSecond, KibibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.KibibitPerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 Kibps", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KibibitsPerSecond, KibibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.KibibitPerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 KiB/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KibibytesPerSecond, KibibytesPerSecondTolerance); - Assert.Equal(BitRateUnit.KibibytePerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 kbit/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilobitsPerSecond, KilobitsPerSecondTolerance); - Assert.Equal(BitRateUnit.KilobitPerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 kbps", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilobitsPerSecond, KilobitsPerSecondTolerance); - Assert.Equal(BitRateUnit.KilobitPerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 kB/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilobytesPerSecond, KilobytesPerSecondTolerance); - Assert.Equal(BitRateUnit.KilobytePerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 Mibit/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MebibitsPerSecond, MebibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.MebibitPerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 Mibps", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MebibitsPerSecond, MebibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.MebibitPerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 MiB/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MebibytesPerSecond, MebibytesPerSecondTolerance); - Assert.Equal(BitRateUnit.MebibytePerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 Mbit/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegabitsPerSecond, MegabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.MegabitPerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 Mbps", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegabitsPerSecond, MegabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.MegabitPerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 MB/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegabytesPerSecond, MegabytesPerSecondTolerance); - Assert.Equal(BitRateUnit.MegabytePerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 Pibit/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PebibitsPerSecond, PebibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.PebibitPerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 Pibps", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PebibitsPerSecond, PebibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.PebibitPerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 PiB/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PebibytesPerSecond, PebibytesPerSecondTolerance); - Assert.Equal(BitRateUnit.PebibytePerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 Pbit/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PetabitsPerSecond, PetabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.PetabitPerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 Pbps", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PetabitsPerSecond, PetabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.PetabitPerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 PB/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PetabytesPerSecond, PetabytesPerSecondTolerance); - Assert.Equal(BitRateUnit.PetabytePerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 Tibit/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TebibitsPerSecond, TebibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.TebibitPerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 Tibps", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TebibitsPerSecond, TebibitsPerSecondTolerance); - Assert.Equal(BitRateUnit.TebibitPerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 TiB/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TebibytesPerSecond, TebibytesPerSecondTolerance); - Assert.Equal(BitRateUnit.TebibytePerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 Tbit/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TerabitsPerSecond, TerabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.TerabitPerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 Tbps", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TerabitsPerSecond, TerabitsPerSecondTolerance); - Assert.Equal(BitRateUnit.TerabitPerSecond, parsed.Unit); - } - - { - Assert.True(BitRate.TryParse("1 TB/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TerabytesPerSecond, TerabytesPerSecondTolerance); - Assert.Equal(BitRateUnit.TerabytePerSecond, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(BitRate.TryParse(quantityString, out BitRate parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -1412,6 +1009,52 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, BitRat Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", BitRateUnit.BitPerSecond, "bit/s")] + [InlineData("en-US", BitRateUnit.BytePerSecond, "B/s")] + [InlineData("en-US", BitRateUnit.ExabitPerSecond, "Ebit/s")] + [InlineData("en-US", BitRateUnit.ExabytePerSecond, "EB/s")] + [InlineData("en-US", BitRateUnit.ExbibitPerSecond, "Eibit/s")] + [InlineData("en-US", BitRateUnit.ExbibytePerSecond, "EiB/s")] + [InlineData("en-US", BitRateUnit.GibibitPerSecond, "Gibit/s")] + [InlineData("en-US", BitRateUnit.GibibytePerSecond, "GiB/s")] + [InlineData("en-US", BitRateUnit.GigabitPerSecond, "Gbit/s")] + [InlineData("en-US", BitRateUnit.GigabytePerSecond, "GB/s")] + [InlineData("en-US", BitRateUnit.KibibitPerSecond, "Kibit/s")] + [InlineData("en-US", BitRateUnit.KibibytePerSecond, "KiB/s")] + [InlineData("en-US", BitRateUnit.KilobitPerSecond, "kbit/s")] + [InlineData("en-US", BitRateUnit.KilobytePerSecond, "kB/s")] + [InlineData("en-US", BitRateUnit.MebibitPerSecond, "Mibit/s")] + [InlineData("en-US", BitRateUnit.MebibytePerSecond, "MiB/s")] + [InlineData("en-US", BitRateUnit.MegabitPerSecond, "Mbit/s")] + [InlineData("en-US", BitRateUnit.MegabytePerSecond, "MB/s")] + [InlineData("en-US", BitRateUnit.PebibitPerSecond, "Pibit/s")] + [InlineData("en-US", BitRateUnit.PebibytePerSecond, "PiB/s")] + [InlineData("en-US", BitRateUnit.PetabitPerSecond, "Pbit/s")] + [InlineData("en-US", BitRateUnit.PetabytePerSecond, "PB/s")] + [InlineData("en-US", BitRateUnit.TebibitPerSecond, "Tibit/s")] + [InlineData("en-US", BitRateUnit.TebibytePerSecond, "TiB/s")] + [InlineData("en-US", BitRateUnit.TerabitPerSecond, "Tbit/s")] + [InlineData("en-US", BitRateUnit.TerabytePerSecond, "TB/s")] + public void GetAbbreviationForCulture(string culture, BitRateUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = BitRate.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(BitRate.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = BitRate.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(BitRateUnit unit) @@ -1442,6 +1085,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); }); } @@ -1465,57 +1109,59 @@ 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.FromExbibitsPerSecond(bitpersecond.ExbibitsPerSecond).BitsPerSecond, ExbibitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromExbibytesPerSecond(bitpersecond.ExbibytesPerSecond).BitsPerSecond, ExbibytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromGibibitsPerSecond(bitpersecond.GibibitsPerSecond).BitsPerSecond, GibibitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromGibibytesPerSecond(bitpersecond.GibibytesPerSecond).BitsPerSecond, GibibytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromGigabitsPerSecond(bitpersecond.GigabitsPerSecond).BitsPerSecond, GigabitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromGigabytesPerSecond(bitpersecond.GigabytesPerSecond).BitsPerSecond, GigabytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromKibibitsPerSecond(bitpersecond.KibibitsPerSecond).BitsPerSecond, KibibitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromKibibytesPerSecond(bitpersecond.KibibytesPerSecond).BitsPerSecond, KibibytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromKilobitsPerSecond(bitpersecond.KilobitsPerSecond).BitsPerSecond, KilobitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromKilobytesPerSecond(bitpersecond.KilobytesPerSecond).BitsPerSecond, KilobytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromMebibitsPerSecond(bitpersecond.MebibitsPerSecond).BitsPerSecond, MebibitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromMebibytesPerSecond(bitpersecond.MebibytesPerSecond).BitsPerSecond, MebibytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromMegabitsPerSecond(bitpersecond.MegabitsPerSecond).BitsPerSecond, MegabitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromMegabytesPerSecond(bitpersecond.MegabytesPerSecond).BitsPerSecond, MegabytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromPebibitsPerSecond(bitpersecond.PebibitsPerSecond).BitsPerSecond, PebibitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromPebibytesPerSecond(bitpersecond.PebibytesPerSecond).BitsPerSecond, PebibytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromPetabitsPerSecond(bitpersecond.PetabitsPerSecond).BitsPerSecond, PetabitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromPetabytesPerSecond(bitpersecond.PetabytesPerSecond).BitsPerSecond, PetabytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromTebibitsPerSecond(bitpersecond.TebibitsPerSecond).BitsPerSecond, TebibitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromTebibytesPerSecond(bitpersecond.TebibytesPerSecond).BitsPerSecond, TebibytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromTerabitsPerSecond(bitpersecond.TerabitsPerSecond).BitsPerSecond, TerabitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromTerabytesPerSecond(bitpersecond.TerabytesPerSecond).BitsPerSecond, TerabytesPerSecondTolerance); + 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.FromExbibitsPerSecond(bitpersecond.ExbibitsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromExbibytesPerSecond(bitpersecond.ExbibytesPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromGibibitsPerSecond(bitpersecond.GibibitsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromGibibytesPerSecond(bitpersecond.GibibytesPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromGigabitsPerSecond(bitpersecond.GigabitsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromGigabytesPerSecond(bitpersecond.GigabytesPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromKibibitsPerSecond(bitpersecond.KibibitsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromKibibytesPerSecond(bitpersecond.KibibytesPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromKilobitsPerSecond(bitpersecond.KilobitsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromKilobytesPerSecond(bitpersecond.KilobytesPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromMebibitsPerSecond(bitpersecond.MebibitsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromMebibytesPerSecond(bitpersecond.MebibytesPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromMegabitsPerSecond(bitpersecond.MegabitsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromMegabytesPerSecond(bitpersecond.MegabytesPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromPebibitsPerSecond(bitpersecond.PebibitsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromPebibytesPerSecond(bitpersecond.PebibytesPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromPetabitsPerSecond(bitpersecond.PetabitsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromPetabytesPerSecond(bitpersecond.PetabytesPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromTebibitsPerSecond(bitpersecond.TebibitsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromTebibytesPerSecond(bitpersecond.TebibytesPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromTerabitsPerSecond(bitpersecond.TerabitsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromTerabytesPerSecond(bitpersecond.TerabytesPerSecond).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] @@ -1561,8 +1207,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); @@ -1599,23 +1243,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = BitRate.FromBitsPerSecond(1); - Assert.True(v.Equals(BitRate.FromBitsPerSecond(1), BitsPerSecondTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(BitRate.Zero, BitsPerSecondTolerance, ComparisonType.Relative)); - Assert.True(BitRate.FromBitsPerSecond(100).Equals(BitRate.FromBitsPerSecond(120), 0.3, ComparisonType.Relative)); - Assert.False(BitRate.FromBitsPerSecond(100).Equals(BitRate.FromBitsPerSecond(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = BitRate.FromBitsPerSecond(1); - Assert.Throws(() => v.Equals(BitRate.FromBitsPerSecond(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1630,6 +1257,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(bitpersecond.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = BitRate.FromBitsPerSecond(1); + var negativeTolerance = BitRate.FromBitsPerSecond(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1646,6 +1299,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() { @@ -1754,158 +1419,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(BitRate))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(BitRateUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal(BitRate.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal(BitRate.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal(new {BitRate.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 4fa88eab3d..91ed8304be 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/BrakeSpecificFuelConsumptionTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/BrakeSpecificFuelConsumptionTestsBase.g.cs @@ -104,7 +104,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new BrakeSpecificFuelConsumption(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -117,15 +117,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void BrakeSpecificFuelConsumption_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + BrakeSpecificFuelConsumptionUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new BrakeSpecificFuelConsumption(1, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(BrakeSpecificFuelConsumption.Zero, quantityInfo.Zero); Assert.Equal("BrakeSpecificFuelConsumption", quantityInfo.Name); + Assert.Equal(BrakeSpecificFuelConsumption.Zero, quantityInfo.Zero); + Assert.Equal(BrakeSpecificFuelConsumption.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(BrakeSpecificFuelConsumption.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void BrakeSpecificFuelConsumptionInfo_CreateWithCustomUnitInfos() + { + BrakeSpecificFuelConsumptionUnit[] expectedUnits = [BrakeSpecificFuelConsumptionUnit.KilogramPerJoule]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -141,15 +159,15 @@ public void KilogramPerJouleToBrakeSpecificFuelConsumptionUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = BrakeSpecificFuelConsumption.From(1, BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour); - AssertEx.EqualTolerance(1, quantity00.GramsPerKiloWattHour, GramsPerKiloWattHourTolerance); + Assert.Equal(1, quantity00.GramsPerKiloWattHour); Assert.Equal(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour, quantity00.Unit); var quantity01 = BrakeSpecificFuelConsumption.From(1, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule); - AssertEx.EqualTolerance(1, quantity01.KilogramsPerJoule, KilogramsPerJouleTolerance); + Assert.Equal(1, quantity01.KilogramsPerJoule); Assert.Equal(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, quantity01.Unit); var quantity02 = BrakeSpecificFuelConsumption.From(1, BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour); - AssertEx.EqualTolerance(1, quantity02.PoundsPerMechanicalHorsepowerHour, PoundsPerMechanicalHorsepowerHourTolerance); + Assert.Equal(1, quantity02.PoundsPerMechanicalHorsepowerHour); Assert.Equal(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, quantity02.Unit); } @@ -287,53 +305,28 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [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, decimal expectedValue) { - try - { - var parsed = BrakeSpecificFuelConsumption.Parse("1 g/kWh", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerKiloWattHour, GramsPerKiloWattHourTolerance); - Assert.Equal(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BrakeSpecificFuelConsumption.Parse("1 kg/J", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerJoule, KilogramsPerJouleTolerance); - Assert.Equal(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = BrakeSpecificFuelConsumption.Parse("1 lb/hph", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerMechanicalHorsepowerHour, PoundsPerMechanicalHorsepowerHourTolerance); - Assert.Equal(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = BrakeSpecificFuelConsumption.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [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, decimal expectedValue) { - { - Assert.True(BrakeSpecificFuelConsumption.TryParse("1 g/kWh", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerKiloWattHour, GramsPerKiloWattHourTolerance); - Assert.Equal(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour, parsed.Unit); - } - - { - Assert.True(BrakeSpecificFuelConsumption.TryParse("1 kg/J", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerJoule, KilogramsPerJouleTolerance); - Assert.Equal(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, parsed.Unit); - } - - { - Assert.True(BrakeSpecificFuelConsumption.TryParse("1 lb/hph", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerMechanicalHorsepowerHour, PoundsPerMechanicalHorsepowerHourTolerance); - Assert.Equal(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(BrakeSpecificFuelConsumption.TryParse(quantityString, out BrakeSpecificFuelConsumption parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -426,6 +419,29 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, BrakeS Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour, "g/kWh")] + [InlineData("en-US", BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, "kg/J")] + [InlineData("en-US", BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, "lb/hph")] + public void GetAbbreviationForCulture(string culture, BrakeSpecificFuelConsumptionUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = BrakeSpecificFuelConsumption.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(BrakeSpecificFuelConsumption.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = BrakeSpecificFuelConsumption.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(BrakeSpecificFuelConsumptionUnit unit) @@ -456,6 +472,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); }); } @@ -479,34 +496,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] @@ -552,8 +571,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); @@ -591,34 +608,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1); - Assert.True(v.Equals(BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1), KilogramsPerJouleTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(BrakeSpecificFuelConsumption.Zero, KilogramsPerJouleTolerance, ComparisonType.Relative)); - Assert.True(BrakeSpecificFuelConsumption.FromKilogramsPerJoule(100).Equals(BrakeSpecificFuelConsumption.FromKilogramsPerJoule(120), 0.3, ComparisonType.Relative)); - Assert.False(BrakeSpecificFuelConsumption.FromKilogramsPerJoule(100).Equals(BrakeSpecificFuelConsumption.FromKilogramsPerJoule(120), 0.1, ComparisonType.Relative)); + BrakeSpecificFuelConsumption kilogramperjoule = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1); + Assert.False(kilogramperjoule.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1); - Assert.Throws(() => v.Equals(BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1), -1, ComparisonType.Relative)); + BrakeSpecificFuelConsumption kilogramperjoule = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1); + Assert.False(kilogramperjoule.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - BrakeSpecificFuelConsumption kilogramperjoule = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1); - Assert.False(kilogramperjoule.Equals(new object())); + var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(firstValue); + var otherQuantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(secondValue); + BrakeSpecificFuelConsumption maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - BrakeSpecificFuelConsumption kilogramperjoule = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1); - Assert.False(kilogramperjoule.Equals(null)); + var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1); + var negativeTolerance = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -637,6 +663,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() { @@ -699,158 +737,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(BrakeSpecificFuelConsumption))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(BrakeSpecificFuelConsumptionUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal(BrakeSpecificFuelConsumption.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal(BrakeSpecificFuelConsumption.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal(new {BrakeSpecificFuelConsumption.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 920d7f55a1..350375ba0b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/CoefficientOfThermalExpansionTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/CoefficientOfThermalExpansionTestsBase.g.cs @@ -116,7 +116,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new CoefficientOfThermalExpansion(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -129,15 +129,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void CoefficientOfThermalExpansion_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + CoefficientOfThermalExpansionUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new CoefficientOfThermalExpansion(1, CoefficientOfThermalExpansionUnit.PerKelvin); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(CoefficientOfThermalExpansion.Zero, quantityInfo.Zero); Assert.Equal("CoefficientOfThermalExpansion", quantityInfo.Name); + Assert.Equal(CoefficientOfThermalExpansion.Zero, quantityInfo.Zero); + Assert.Equal(CoefficientOfThermalExpansion.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(CoefficientOfThermalExpansion.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void CoefficientOfThermalExpansionInfo_CreateWithCustomUnitInfos() + { + CoefficientOfThermalExpansionUnit[] expectedUnits = [CoefficientOfThermalExpansionUnit.PerKelvin]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -156,27 +174,27 @@ public void PerKelvinToCoefficientOfThermalExpansionUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = CoefficientOfThermalExpansion.From(1, CoefficientOfThermalExpansionUnit.PerDegreeCelsius); - AssertEx.EqualTolerance(1, quantity00.PerDegreeCelsius, PerDegreeCelsiusTolerance); + Assert.Equal(1, quantity00.PerDegreeCelsius); Assert.Equal(CoefficientOfThermalExpansionUnit.PerDegreeCelsius, quantity00.Unit); var quantity01 = CoefficientOfThermalExpansion.From(1, CoefficientOfThermalExpansionUnit.PerDegreeFahrenheit); - AssertEx.EqualTolerance(1, quantity01.PerDegreeFahrenheit, PerDegreeFahrenheitTolerance); + Assert.Equal(1, quantity01.PerDegreeFahrenheit); Assert.Equal(CoefficientOfThermalExpansionUnit.PerDegreeFahrenheit, quantity01.Unit); var quantity02 = CoefficientOfThermalExpansion.From(1, CoefficientOfThermalExpansionUnit.PerKelvin); - AssertEx.EqualTolerance(1, quantity02.PerKelvin, PerKelvinTolerance); + Assert.Equal(1, quantity02.PerKelvin); Assert.Equal(CoefficientOfThermalExpansionUnit.PerKelvin, quantity02.Unit); var quantity03 = CoefficientOfThermalExpansion.From(1, CoefficientOfThermalExpansionUnit.PpmPerDegreeCelsius); - AssertEx.EqualTolerance(1, quantity03.PpmPerDegreeCelsius, PpmPerDegreeCelsiusTolerance); + Assert.Equal(1, quantity03.PpmPerDegreeCelsius); Assert.Equal(CoefficientOfThermalExpansionUnit.PpmPerDegreeCelsius, quantity03.Unit); var quantity04 = CoefficientOfThermalExpansion.From(1, CoefficientOfThermalExpansionUnit.PpmPerDegreeFahrenheit); - AssertEx.EqualTolerance(1, quantity04.PpmPerDegreeFahrenheit, PpmPerDegreeFahrenheitTolerance); + Assert.Equal(1, quantity04.PpmPerDegreeFahrenheit); Assert.Equal(CoefficientOfThermalExpansionUnit.PpmPerDegreeFahrenheit, quantity04.Unit); var quantity05 = CoefficientOfThermalExpansion.From(1, CoefficientOfThermalExpansionUnit.PpmPerKelvin); - AssertEx.EqualTolerance(1, quantity05.PpmPerKelvin, PpmPerKelvinTolerance); + Assert.Equal(1, quantity05.PpmPerKelvin); Assert.Equal(CoefficientOfThermalExpansionUnit.PpmPerKelvin, quantity05.Unit); } @@ -317,92 +335,34 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 °C⁻¹", CoefficientOfThermalExpansionUnit.PerDegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 °F⁻¹", CoefficientOfThermalExpansionUnit.PerDegreeFahrenheit, 4.2)] + [InlineData("en-US", "4.2 K⁻¹", CoefficientOfThermalExpansionUnit.PerKelvin, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = CoefficientOfThermalExpansion.Parse("1 °C⁻¹", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PerDegreeCelsius, PerDegreeCelsiusTolerance); - Assert.Equal(CoefficientOfThermalExpansionUnit.PerDegreeCelsius, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = CoefficientOfThermalExpansion.Parse("1 °F⁻¹", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PerDegreeFahrenheit, PerDegreeFahrenheitTolerance); - Assert.Equal(CoefficientOfThermalExpansionUnit.PerDegreeFahrenheit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = CoefficientOfThermalExpansion.Parse("1 K⁻¹", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PerKelvin, PerKelvinTolerance); - Assert.Equal(CoefficientOfThermalExpansionUnit.PerKelvin, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = CoefficientOfThermalExpansion.Parse("1 ppm/°C", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PpmPerDegreeCelsius, PpmPerDegreeCelsiusTolerance); - Assert.Equal(CoefficientOfThermalExpansionUnit.PpmPerDegreeCelsius, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = CoefficientOfThermalExpansion.Parse("1 ppm/°F", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PpmPerDegreeFahrenheit, PpmPerDegreeFahrenheitTolerance); - Assert.Equal(CoefficientOfThermalExpansionUnit.PpmPerDegreeFahrenheit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = CoefficientOfThermalExpansion.Parse("1 ppm/K", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PpmPerKelvin, PpmPerKelvinTolerance); - Assert.Equal(CoefficientOfThermalExpansionUnit.PpmPerKelvin, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = CoefficientOfThermalExpansion.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 °C⁻¹", CoefficientOfThermalExpansionUnit.PerDegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 °F⁻¹", CoefficientOfThermalExpansionUnit.PerDegreeFahrenheit, 4.2)] + [InlineData("en-US", "4.2 K⁻¹", CoefficientOfThermalExpansionUnit.PerKelvin, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(CoefficientOfThermalExpansion.TryParse("1 °C⁻¹", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PerDegreeCelsius, PerDegreeCelsiusTolerance); - Assert.Equal(CoefficientOfThermalExpansionUnit.PerDegreeCelsius, parsed.Unit); - } - - { - Assert.True(CoefficientOfThermalExpansion.TryParse("1 °F⁻¹", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PerDegreeFahrenheit, PerDegreeFahrenheitTolerance); - Assert.Equal(CoefficientOfThermalExpansionUnit.PerDegreeFahrenheit, parsed.Unit); - } - - { - Assert.True(CoefficientOfThermalExpansion.TryParse("1 K⁻¹", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PerKelvin, PerKelvinTolerance); - Assert.Equal(CoefficientOfThermalExpansionUnit.PerKelvin, parsed.Unit); - } - - { - Assert.True(CoefficientOfThermalExpansion.TryParse("1 ppm/°C", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PpmPerDegreeCelsius, PpmPerDegreeCelsiusTolerance); - Assert.Equal(CoefficientOfThermalExpansionUnit.PpmPerDegreeCelsius, parsed.Unit); - } - - { - Assert.True(CoefficientOfThermalExpansion.TryParse("1 ppm/°F", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PpmPerDegreeFahrenheit, PpmPerDegreeFahrenheitTolerance); - Assert.Equal(CoefficientOfThermalExpansionUnit.PpmPerDegreeFahrenheit, parsed.Unit); - } - - { - Assert.True(CoefficientOfThermalExpansion.TryParse("1 ppm/K", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PpmPerKelvin, PpmPerKelvinTolerance); - Assert.Equal(CoefficientOfThermalExpansionUnit.PpmPerKelvin, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(CoefficientOfThermalExpansion.TryParse(quantityString, out CoefficientOfThermalExpansion parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -519,6 +479,32 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Coeffi Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", CoefficientOfThermalExpansionUnit.PerDegreeCelsius, "°C⁻¹")] + [InlineData("en-US", CoefficientOfThermalExpansionUnit.PerDegreeFahrenheit, "°F⁻¹")] + [InlineData("en-US", CoefficientOfThermalExpansionUnit.PerKelvin, "K⁻¹")] + [InlineData("en-US", CoefficientOfThermalExpansionUnit.PpmPerDegreeCelsius, "ppm/°C")] + [InlineData("en-US", CoefficientOfThermalExpansionUnit.PpmPerDegreeFahrenheit, "ppm/°F")] + [InlineData("en-US", CoefficientOfThermalExpansionUnit.PpmPerKelvin, "ppm/K")] + public void GetAbbreviationForCulture(string culture, CoefficientOfThermalExpansionUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = CoefficientOfThermalExpansion.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(CoefficientOfThermalExpansion.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = CoefficientOfThermalExpansion.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(CoefficientOfThermalExpansionUnit unit) @@ -549,6 +535,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); }); } @@ -572,37 +559,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] @@ -648,8 +637,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); @@ -687,34 +674,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = CoefficientOfThermalExpansion.FromPerKelvin(1); - Assert.True(v.Equals(CoefficientOfThermalExpansion.FromPerKelvin(1), PerKelvinTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(CoefficientOfThermalExpansion.Zero, PerKelvinTolerance, ComparisonType.Relative)); - Assert.True(CoefficientOfThermalExpansion.FromPerKelvin(100).Equals(CoefficientOfThermalExpansion.FromPerKelvin(120), 0.3, ComparisonType.Relative)); - Assert.False(CoefficientOfThermalExpansion.FromPerKelvin(100).Equals(CoefficientOfThermalExpansion.FromPerKelvin(120), 0.1, ComparisonType.Relative)); + CoefficientOfThermalExpansion perkelvin = CoefficientOfThermalExpansion.FromPerKelvin(1); + Assert.False(perkelvin.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = CoefficientOfThermalExpansion.FromPerKelvin(1); - Assert.Throws(() => v.Equals(CoefficientOfThermalExpansion.FromPerKelvin(1), -1, ComparisonType.Relative)); + CoefficientOfThermalExpansion perkelvin = CoefficientOfThermalExpansion.FromPerKelvin(1); + Assert.False(perkelvin.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - CoefficientOfThermalExpansion perkelvin = CoefficientOfThermalExpansion.FromPerKelvin(1); - Assert.False(perkelvin.Equals(new object())); + var quantity = CoefficientOfThermalExpansion.FromPerKelvin(firstValue); + var otherQuantity = CoefficientOfThermalExpansion.FromPerKelvin(secondValue); + CoefficientOfThermalExpansion maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - CoefficientOfThermalExpansion perkelvin = CoefficientOfThermalExpansion.FromPerKelvin(1); - Assert.False(perkelvin.Equals(null)); + var quantity = CoefficientOfThermalExpansion.FromPerKelvin(1); + var negativeTolerance = CoefficientOfThermalExpansion.FromPerKelvin(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -733,6 +729,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() { @@ -801,158 +809,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = CoefficientOfThermalExpansion.FromPerKelvin(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = CoefficientOfThermalExpansion.FromPerKelvin(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = CoefficientOfThermalExpansion.FromPerKelvin(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = CoefficientOfThermalExpansion.FromPerKelvin(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = CoefficientOfThermalExpansion.FromPerKelvin(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = CoefficientOfThermalExpansion.FromPerKelvin(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = CoefficientOfThermalExpansion.FromPerKelvin(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = CoefficientOfThermalExpansion.FromPerKelvin(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = CoefficientOfThermalExpansion.FromPerKelvin(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = CoefficientOfThermalExpansion.FromPerKelvin(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = CoefficientOfThermalExpansion.FromPerKelvin(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = CoefficientOfThermalExpansion.FromPerKelvin(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = CoefficientOfThermalExpansion.FromPerKelvin(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = CoefficientOfThermalExpansion.FromPerKelvin(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = CoefficientOfThermalExpansion.FromPerKelvin(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = CoefficientOfThermalExpansion.FromPerKelvin(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(CoefficientOfThermalExpansion))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = CoefficientOfThermalExpansion.FromPerKelvin(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(CoefficientOfThermalExpansionUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = CoefficientOfThermalExpansion.FromPerKelvin(1.0); - Assert.Equal(CoefficientOfThermalExpansion.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = CoefficientOfThermalExpansion.FromPerKelvin(1.0); - Assert.Equal(CoefficientOfThermalExpansion.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = CoefficientOfThermalExpansion.FromPerKelvin(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = CoefficientOfThermalExpansion.FromPerKelvin(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = CoefficientOfThermalExpansion.FromPerKelvin(1.0); - Assert.Equal(new {CoefficientOfThermalExpansion.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 8c25391d12..a90c7bc1bf 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/CompressibilityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/CompressibilityTestsBase.g.cs @@ -120,7 +120,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Compressibility(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -133,15 +133,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Compressibility_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + CompressibilityUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Compressibility(1, CompressibilityUnit.InversePascal); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Compressibility.Zero, quantityInfo.Zero); Assert.Equal("Compressibility", quantityInfo.Name); + Assert.Equal(Compressibility.Zero, quantityInfo.Zero); + Assert.Equal(Compressibility.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Compressibility.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void CompressibilityInfo_CreateWithCustomUnitInfos() + { + CompressibilityUnit[] expectedUnits = [CompressibilityUnit.InversePascal]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -161,31 +179,31 @@ public void InversePascalToCompressibilityUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Compressibility.From(1, CompressibilityUnit.InverseAtmosphere); - AssertEx.EqualTolerance(1, quantity00.InverseAtmospheres, InverseAtmospheresTolerance); + Assert.Equal(1, quantity00.InverseAtmospheres); Assert.Equal(CompressibilityUnit.InverseAtmosphere, quantity00.Unit); var quantity01 = Compressibility.From(1, CompressibilityUnit.InverseBar); - AssertEx.EqualTolerance(1, quantity01.InverseBars, InverseBarsTolerance); + Assert.Equal(1, quantity01.InverseBars); Assert.Equal(CompressibilityUnit.InverseBar, quantity01.Unit); var quantity02 = Compressibility.From(1, CompressibilityUnit.InverseKilopascal); - AssertEx.EqualTolerance(1, quantity02.InverseKilopascals, InverseKilopascalsTolerance); + Assert.Equal(1, quantity02.InverseKilopascals); Assert.Equal(CompressibilityUnit.InverseKilopascal, quantity02.Unit); var quantity03 = Compressibility.From(1, CompressibilityUnit.InverseMegapascal); - AssertEx.EqualTolerance(1, quantity03.InverseMegapascals, InverseMegapascalsTolerance); + Assert.Equal(1, quantity03.InverseMegapascals); Assert.Equal(CompressibilityUnit.InverseMegapascal, quantity03.Unit); var quantity04 = Compressibility.From(1, CompressibilityUnit.InverseMillibar); - AssertEx.EqualTolerance(1, quantity04.InverseMillibars, InverseMillibarsTolerance); + Assert.Equal(1, quantity04.InverseMillibars); Assert.Equal(CompressibilityUnit.InverseMillibar, quantity04.Unit); var quantity05 = Compressibility.From(1, CompressibilityUnit.InversePascal); - AssertEx.EqualTolerance(1, quantity05.InversePascals, InversePascalsTolerance); + Assert.Equal(1, quantity05.InversePascals); Assert.Equal(CompressibilityUnit.InversePascal, quantity05.Unit); var quantity06 = Compressibility.From(1, CompressibilityUnit.InversePoundForcePerSquareInch); - AssertEx.EqualTolerance(1, quantity06.InversePoundsForcePerSquareInch, InversePoundsForcePerSquareInchTolerance); + Assert.Equal(1, quantity06.InversePoundsForcePerSquareInch); Assert.Equal(CompressibilityUnit.InversePoundForcePerSquareInch, quantity06.Unit); } @@ -327,196 +345,50 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 atm⁻¹", CompressibilityUnit.InverseAtmosphere, 4.2)] + [InlineData("en-US", "4.2 1/atm", CompressibilityUnit.InverseAtmosphere, 4.2)] + [InlineData("en-US", "4.2 bar⁻¹", CompressibilityUnit.InverseBar, 4.2)] + [InlineData("en-US", "4.2 1/bar", CompressibilityUnit.InverseBar, 4.2)] + [InlineData("en-US", "4.2 kPa⁻¹", CompressibilityUnit.InverseKilopascal, 4.2)] + [InlineData("en-US", "4.2 1/kPa", CompressibilityUnit.InverseKilopascal, 4.2)] + [InlineData("en-US", "4.2 MPa⁻¹", CompressibilityUnit.InverseMegapascal, 4.2)] + [InlineData("en-US", "4.2 1/MPa", CompressibilityUnit.InverseMegapascal, 4.2)] + [InlineData("en-US", "4.2 mbar⁻¹", CompressibilityUnit.InverseMillibar, 4.2)] + [InlineData("en-US", "4.2 1/mbar", CompressibilityUnit.InverseMillibar, 4.2)] + [InlineData("en-US", "4.2 Pa⁻¹", CompressibilityUnit.InversePascal, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = Compressibility.Parse("1 atm⁻¹", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseAtmospheres, InverseAtmospheresTolerance); - Assert.Equal(CompressibilityUnit.InverseAtmosphere, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Compressibility.Parse("1 1/atm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseAtmospheres, InverseAtmospheresTolerance); - Assert.Equal(CompressibilityUnit.InverseAtmosphere, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Compressibility.Parse("1 bar⁻¹", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseBars, InverseBarsTolerance); - Assert.Equal(CompressibilityUnit.InverseBar, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Compressibility.Parse("1 1/bar", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseBars, InverseBarsTolerance); - Assert.Equal(CompressibilityUnit.InverseBar, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Compressibility.Parse("1 kPa⁻¹", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseKilopascals, InverseKilopascalsTolerance); - Assert.Equal(CompressibilityUnit.InverseKilopascal, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Compressibility.Parse("1 1/kPa", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseKilopascals, InverseKilopascalsTolerance); - Assert.Equal(CompressibilityUnit.InverseKilopascal, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Compressibility.Parse("1 MPa⁻¹", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseMegapascals, InverseMegapascalsTolerance); - Assert.Equal(CompressibilityUnit.InverseMegapascal, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Compressibility.Parse("1 1/MPa", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseMegapascals, InverseMegapascalsTolerance); - Assert.Equal(CompressibilityUnit.InverseMegapascal, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Compressibility.Parse("1 mbar⁻¹", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseMillibars, InverseMillibarsTolerance); - Assert.Equal(CompressibilityUnit.InverseMillibar, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Compressibility.Parse("1 1/mbar", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseMillibars, InverseMillibarsTolerance); - Assert.Equal(CompressibilityUnit.InverseMillibar, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Compressibility.Parse("1 Pa⁻¹", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InversePascals, InversePascalsTolerance); - Assert.Equal(CompressibilityUnit.InversePascal, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Compressibility.Parse("1 1/Pa", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InversePascals, InversePascalsTolerance); - Assert.Equal(CompressibilityUnit.InversePascal, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Compressibility.Parse("1 psi⁻¹", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InversePoundsForcePerSquareInch, InversePoundsForcePerSquareInchTolerance); - Assert.Equal(CompressibilityUnit.InversePoundForcePerSquareInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Compressibility.Parse("1 1/psi", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InversePoundsForcePerSquareInch, InversePoundsForcePerSquareInchTolerance); - Assert.Equal(CompressibilityUnit.InversePoundForcePerSquareInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Compressibility.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 atm⁻¹", CompressibilityUnit.InverseAtmosphere, 4.2)] + [InlineData("en-US", "4.2 1/atm", CompressibilityUnit.InverseAtmosphere, 4.2)] + [InlineData("en-US", "4.2 bar⁻¹", CompressibilityUnit.InverseBar, 4.2)] + [InlineData("en-US", "4.2 1/bar", CompressibilityUnit.InverseBar, 4.2)] + [InlineData("en-US", "4.2 kPa⁻¹", CompressibilityUnit.InverseKilopascal, 4.2)] + [InlineData("en-US", "4.2 1/kPa", CompressibilityUnit.InverseKilopascal, 4.2)] + [InlineData("en-US", "4.2 MPa⁻¹", CompressibilityUnit.InverseMegapascal, 4.2)] + [InlineData("en-US", "4.2 1/MPa", CompressibilityUnit.InverseMegapascal, 4.2)] + [InlineData("en-US", "4.2 mbar⁻¹", CompressibilityUnit.InverseMillibar, 4.2)] + [InlineData("en-US", "4.2 1/mbar", CompressibilityUnit.InverseMillibar, 4.2)] + [InlineData("en-US", "4.2 Pa⁻¹", CompressibilityUnit.InversePascal, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(Compressibility.TryParse("1 atm⁻¹", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseAtmospheres, InverseAtmospheresTolerance); - Assert.Equal(CompressibilityUnit.InverseAtmosphere, parsed.Unit); - } - - { - Assert.True(Compressibility.TryParse("1 1/atm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseAtmospheres, InverseAtmospheresTolerance); - Assert.Equal(CompressibilityUnit.InverseAtmosphere, parsed.Unit); - } - - { - Assert.True(Compressibility.TryParse("1 bar⁻¹", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseBars, InverseBarsTolerance); - Assert.Equal(CompressibilityUnit.InverseBar, parsed.Unit); - } - - { - Assert.True(Compressibility.TryParse("1 1/bar", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseBars, InverseBarsTolerance); - Assert.Equal(CompressibilityUnit.InverseBar, parsed.Unit); - } - - { - Assert.True(Compressibility.TryParse("1 kPa⁻¹", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseKilopascals, InverseKilopascalsTolerance); - Assert.Equal(CompressibilityUnit.InverseKilopascal, parsed.Unit); - } - - { - Assert.True(Compressibility.TryParse("1 1/kPa", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseKilopascals, InverseKilopascalsTolerance); - Assert.Equal(CompressibilityUnit.InverseKilopascal, parsed.Unit); - } - - { - Assert.True(Compressibility.TryParse("1 MPa⁻¹", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseMegapascals, InverseMegapascalsTolerance); - Assert.Equal(CompressibilityUnit.InverseMegapascal, parsed.Unit); - } - - { - Assert.True(Compressibility.TryParse("1 1/MPa", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseMegapascals, InverseMegapascalsTolerance); - Assert.Equal(CompressibilityUnit.InverseMegapascal, parsed.Unit); - } - - { - Assert.True(Compressibility.TryParse("1 mbar⁻¹", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseMillibars, InverseMillibarsTolerance); - Assert.Equal(CompressibilityUnit.InverseMillibar, parsed.Unit); - } - - { - Assert.True(Compressibility.TryParse("1 1/mbar", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseMillibars, InverseMillibarsTolerance); - Assert.Equal(CompressibilityUnit.InverseMillibar, parsed.Unit); - } - - { - Assert.True(Compressibility.TryParse("1 Pa⁻¹", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InversePascals, InversePascalsTolerance); - Assert.Equal(CompressibilityUnit.InversePascal, parsed.Unit); - } - - { - Assert.True(Compressibility.TryParse("1 1/Pa", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InversePascals, InversePascalsTolerance); - Assert.Equal(CompressibilityUnit.InversePascal, parsed.Unit); - } - - { - Assert.True(Compressibility.TryParse("1 psi⁻¹", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InversePoundsForcePerSquareInch, InversePoundsForcePerSquareInchTolerance); - Assert.Equal(CompressibilityUnit.InversePoundForcePerSquareInch, parsed.Unit); - } - - { - Assert.True(Compressibility.TryParse("1 1/psi", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InversePoundsForcePerSquareInch, InversePoundsForcePerSquareInchTolerance); - Assert.Equal(CompressibilityUnit.InversePoundForcePerSquareInch, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Compressibility.TryParse(quantityString, out Compressibility parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -697,6 +569,33 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Compre Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", CompressibilityUnit.InverseAtmosphere, "atm⁻¹")] + [InlineData("en-US", CompressibilityUnit.InverseBar, "bar⁻¹")] + [InlineData("en-US", CompressibilityUnit.InverseKilopascal, "kPa⁻¹")] + [InlineData("en-US", CompressibilityUnit.InverseMegapascal, "MPa⁻¹")] + [InlineData("en-US", CompressibilityUnit.InverseMillibar, "mbar⁻¹")] + [InlineData("en-US", CompressibilityUnit.InversePascal, "Pa⁻¹")] + [InlineData("en-US", CompressibilityUnit.InversePoundForcePerSquareInch, "psi⁻¹")] + public void GetAbbreviationForCulture(string culture, CompressibilityUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Compressibility.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Compressibility.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Compressibility.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(CompressibilityUnit unit) @@ -727,6 +626,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); }); } @@ -750,38 +650,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] @@ -827,8 +729,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); @@ -866,34 +766,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = Compressibility.FromInversePascals(1); - Assert.True(v.Equals(Compressibility.FromInversePascals(1), InversePascalsTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Compressibility.Zero, InversePascalsTolerance, ComparisonType.Relative)); - Assert.True(Compressibility.FromInversePascals(100).Equals(Compressibility.FromInversePascals(120), 0.3, ComparisonType.Relative)); - Assert.False(Compressibility.FromInversePascals(100).Equals(Compressibility.FromInversePascals(120), 0.1, ComparisonType.Relative)); + Compressibility inversepascal = Compressibility.FromInversePascals(1); + Assert.False(inversepascal.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = Compressibility.FromInversePascals(1); - Assert.Throws(() => v.Equals(Compressibility.FromInversePascals(1), -1, ComparisonType.Relative)); + Compressibility inversepascal = Compressibility.FromInversePascals(1); + Assert.False(inversepascal.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - Compressibility inversepascal = Compressibility.FromInversePascals(1); - Assert.False(inversepascal.Equals(new object())); + var quantity = Compressibility.FromInversePascals(firstValue); + var otherQuantity = Compressibility.FromInversePascals(secondValue); + Compressibility maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - Compressibility inversepascal = Compressibility.FromInversePascals(1); - Assert.False(inversepascal.Equals(null)); + var quantity = Compressibility.FromInversePascals(1); + var negativeTolerance = Compressibility.FromInversePascals(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -912,6 +821,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() { @@ -982,158 +903,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Compressibility))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(CompressibilityUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal(Compressibility.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal(Compressibility.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal(new {Compressibility.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 67fb24653f..919233955a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/DensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/DensityTestsBase.g.cs @@ -316,7 +316,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Density(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -329,15 +329,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Density_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + DensityUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Density(1, DensityUnit.KilogramPerCubicMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Density.Zero, quantityInfo.Zero); Assert.Equal("Density", quantityInfo.Name); + Assert.Equal(Density.Zero, quantityInfo.Zero); + Assert.Equal(Density.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Density.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void DensityInfo_CreateWithCustomUnitInfos() + { + DensityUnit[] expectedUnits = [DensityUnit.KilogramPerCubicMeter]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -406,227 +424,227 @@ public void KilogramPerCubicMeterToDensityUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Density.From(1, DensityUnit.CentigramPerDeciliter); - AssertEx.EqualTolerance(1, quantity00.CentigramsPerDeciliter, CentigramsPerDeciliterTolerance); + Assert.Equal(1, quantity00.CentigramsPerDeciliter); Assert.Equal(DensityUnit.CentigramPerDeciliter, quantity00.Unit); var quantity01 = Density.From(1, DensityUnit.CentigramPerLiter); - AssertEx.EqualTolerance(1, quantity01.CentigramsPerLiter, CentigramsPerLiterTolerance); + Assert.Equal(1, quantity01.CentigramsPerLiter); Assert.Equal(DensityUnit.CentigramPerLiter, quantity01.Unit); var quantity02 = Density.From(1, DensityUnit.CentigramPerMilliliter); - AssertEx.EqualTolerance(1, quantity02.CentigramsPerMilliliter, CentigramsPerMilliliterTolerance); + Assert.Equal(1, quantity02.CentigramsPerMilliliter); Assert.Equal(DensityUnit.CentigramPerMilliliter, quantity02.Unit); var quantity03 = Density.From(1, DensityUnit.DecigramPerDeciliter); - AssertEx.EqualTolerance(1, quantity03.DecigramsPerDeciliter, DecigramsPerDeciliterTolerance); + Assert.Equal(1, quantity03.DecigramsPerDeciliter); Assert.Equal(DensityUnit.DecigramPerDeciliter, quantity03.Unit); var quantity04 = Density.From(1, DensityUnit.DecigramPerLiter); - AssertEx.EqualTolerance(1, quantity04.DecigramsPerLiter, DecigramsPerLiterTolerance); + Assert.Equal(1, quantity04.DecigramsPerLiter); Assert.Equal(DensityUnit.DecigramPerLiter, quantity04.Unit); var quantity05 = Density.From(1, DensityUnit.DecigramPerMilliliter); - AssertEx.EqualTolerance(1, quantity05.DecigramsPerMilliliter, DecigramsPerMilliliterTolerance); + Assert.Equal(1, quantity05.DecigramsPerMilliliter); Assert.Equal(DensityUnit.DecigramPerMilliliter, quantity05.Unit); var quantity06 = Density.From(1, DensityUnit.FemtogramPerDeciliter); - AssertEx.EqualTolerance(1, quantity06.FemtogramsPerDeciliter, FemtogramsPerDeciliterTolerance); + Assert.Equal(1, quantity06.FemtogramsPerDeciliter); Assert.Equal(DensityUnit.FemtogramPerDeciliter, quantity06.Unit); var quantity07 = Density.From(1, DensityUnit.FemtogramPerLiter); - AssertEx.EqualTolerance(1, quantity07.FemtogramsPerLiter, FemtogramsPerLiterTolerance); + Assert.Equal(1, quantity07.FemtogramsPerLiter); Assert.Equal(DensityUnit.FemtogramPerLiter, quantity07.Unit); var quantity08 = Density.From(1, DensityUnit.FemtogramPerMilliliter); - AssertEx.EqualTolerance(1, quantity08.FemtogramsPerMilliliter, FemtogramsPerMilliliterTolerance); + Assert.Equal(1, quantity08.FemtogramsPerMilliliter); Assert.Equal(DensityUnit.FemtogramPerMilliliter, quantity08.Unit); var quantity09 = Density.From(1, DensityUnit.GramPerCubicCentimeter); - AssertEx.EqualTolerance(1, quantity09.GramsPerCubicCentimeter, GramsPerCubicCentimeterTolerance); + Assert.Equal(1, quantity09.GramsPerCubicCentimeter); Assert.Equal(DensityUnit.GramPerCubicCentimeter, quantity09.Unit); var quantity10 = Density.From(1, DensityUnit.GramPerCubicFoot); - AssertEx.EqualTolerance(1, quantity10.GramsPerCubicFoot, GramsPerCubicFootTolerance); + Assert.Equal(1, quantity10.GramsPerCubicFoot); Assert.Equal(DensityUnit.GramPerCubicFoot, quantity10.Unit); var quantity11 = Density.From(1, DensityUnit.GramPerCubicInch); - AssertEx.EqualTolerance(1, quantity11.GramsPerCubicInch, GramsPerCubicInchTolerance); + Assert.Equal(1, quantity11.GramsPerCubicInch); Assert.Equal(DensityUnit.GramPerCubicInch, quantity11.Unit); var quantity12 = Density.From(1, DensityUnit.GramPerCubicMeter); - AssertEx.EqualTolerance(1, quantity12.GramsPerCubicMeter, GramsPerCubicMeterTolerance); + Assert.Equal(1, quantity12.GramsPerCubicMeter); Assert.Equal(DensityUnit.GramPerCubicMeter, quantity12.Unit); var quantity13 = Density.From(1, DensityUnit.GramPerCubicMillimeter); - AssertEx.EqualTolerance(1, quantity13.GramsPerCubicMillimeter, GramsPerCubicMillimeterTolerance); + Assert.Equal(1, quantity13.GramsPerCubicMillimeter); Assert.Equal(DensityUnit.GramPerCubicMillimeter, quantity13.Unit); var quantity14 = Density.From(1, DensityUnit.GramPerDeciliter); - AssertEx.EqualTolerance(1, quantity14.GramsPerDeciliter, GramsPerDeciliterTolerance); + Assert.Equal(1, quantity14.GramsPerDeciliter); Assert.Equal(DensityUnit.GramPerDeciliter, quantity14.Unit); var quantity15 = Density.From(1, DensityUnit.GramPerLiter); - AssertEx.EqualTolerance(1, quantity15.GramsPerLiter, GramsPerLiterTolerance); + Assert.Equal(1, quantity15.GramsPerLiter); Assert.Equal(DensityUnit.GramPerLiter, quantity15.Unit); var quantity16 = Density.From(1, DensityUnit.GramPerMilliliter); - AssertEx.EqualTolerance(1, quantity16.GramsPerMilliliter, GramsPerMilliliterTolerance); + Assert.Equal(1, quantity16.GramsPerMilliliter); Assert.Equal(DensityUnit.GramPerMilliliter, quantity16.Unit); var quantity17 = Density.From(1, DensityUnit.KilogramPerCubicCentimeter); - AssertEx.EqualTolerance(1, quantity17.KilogramsPerCubicCentimeter, KilogramsPerCubicCentimeterTolerance); + Assert.Equal(1, quantity17.KilogramsPerCubicCentimeter); Assert.Equal(DensityUnit.KilogramPerCubicCentimeter, quantity17.Unit); var quantity18 = Density.From(1, DensityUnit.KilogramPerCubicMeter); - AssertEx.EqualTolerance(1, quantity18.KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); + Assert.Equal(1, quantity18.KilogramsPerCubicMeter); Assert.Equal(DensityUnit.KilogramPerCubicMeter, quantity18.Unit); var quantity19 = Density.From(1, DensityUnit.KilogramPerCubicMillimeter); - AssertEx.EqualTolerance(1, quantity19.KilogramsPerCubicMillimeter, KilogramsPerCubicMillimeterTolerance); + Assert.Equal(1, quantity19.KilogramsPerCubicMillimeter); Assert.Equal(DensityUnit.KilogramPerCubicMillimeter, quantity19.Unit); var quantity20 = Density.From(1, DensityUnit.KilogramPerLiter); - AssertEx.EqualTolerance(1, quantity20.KilogramsPerLiter, KilogramsPerLiterTolerance); + Assert.Equal(1, quantity20.KilogramsPerLiter); Assert.Equal(DensityUnit.KilogramPerLiter, quantity20.Unit); var quantity21 = Density.From(1, DensityUnit.KilopoundPerCubicFoot); - AssertEx.EqualTolerance(1, quantity21.KilopoundsPerCubicFoot, KilopoundsPerCubicFootTolerance); + Assert.Equal(1, quantity21.KilopoundsPerCubicFoot); Assert.Equal(DensityUnit.KilopoundPerCubicFoot, quantity21.Unit); var quantity22 = Density.From(1, DensityUnit.KilopoundPerCubicInch); - AssertEx.EqualTolerance(1, quantity22.KilopoundsPerCubicInch, KilopoundsPerCubicInchTolerance); + Assert.Equal(1, quantity22.KilopoundsPerCubicInch); Assert.Equal(DensityUnit.KilopoundPerCubicInch, quantity22.Unit); var quantity23 = Density.From(1, DensityUnit.KilopoundPerCubicYard); - AssertEx.EqualTolerance(1, quantity23.KilopoundsPerCubicYard, KilopoundsPerCubicYardTolerance); + Assert.Equal(1, quantity23.KilopoundsPerCubicYard); Assert.Equal(DensityUnit.KilopoundPerCubicYard, quantity23.Unit); var quantity24 = Density.From(1, DensityUnit.MicrogramPerCubicMeter); - AssertEx.EqualTolerance(1, quantity24.MicrogramsPerCubicMeter, MicrogramsPerCubicMeterTolerance); + Assert.Equal(1, quantity24.MicrogramsPerCubicMeter); Assert.Equal(DensityUnit.MicrogramPerCubicMeter, quantity24.Unit); var quantity25 = Density.From(1, DensityUnit.MicrogramPerDeciliter); - AssertEx.EqualTolerance(1, quantity25.MicrogramsPerDeciliter, MicrogramsPerDeciliterTolerance); + Assert.Equal(1, quantity25.MicrogramsPerDeciliter); Assert.Equal(DensityUnit.MicrogramPerDeciliter, quantity25.Unit); var quantity26 = Density.From(1, DensityUnit.MicrogramPerLiter); - AssertEx.EqualTolerance(1, quantity26.MicrogramsPerLiter, MicrogramsPerLiterTolerance); + Assert.Equal(1, quantity26.MicrogramsPerLiter); Assert.Equal(DensityUnit.MicrogramPerLiter, quantity26.Unit); var quantity27 = Density.From(1, DensityUnit.MicrogramPerMilliliter); - AssertEx.EqualTolerance(1, quantity27.MicrogramsPerMilliliter, MicrogramsPerMilliliterTolerance); + Assert.Equal(1, quantity27.MicrogramsPerMilliliter); Assert.Equal(DensityUnit.MicrogramPerMilliliter, quantity27.Unit); var quantity28 = Density.From(1, DensityUnit.MilligramPerCubicMeter); - AssertEx.EqualTolerance(1, quantity28.MilligramsPerCubicMeter, MilligramsPerCubicMeterTolerance); + Assert.Equal(1, quantity28.MilligramsPerCubicMeter); Assert.Equal(DensityUnit.MilligramPerCubicMeter, quantity28.Unit); var quantity29 = Density.From(1, DensityUnit.MilligramPerDeciliter); - AssertEx.EqualTolerance(1, quantity29.MilligramsPerDeciliter, MilligramsPerDeciliterTolerance); + Assert.Equal(1, quantity29.MilligramsPerDeciliter); Assert.Equal(DensityUnit.MilligramPerDeciliter, quantity29.Unit); var quantity30 = Density.From(1, DensityUnit.MilligramPerLiter); - AssertEx.EqualTolerance(1, quantity30.MilligramsPerLiter, MilligramsPerLiterTolerance); + Assert.Equal(1, quantity30.MilligramsPerLiter); Assert.Equal(DensityUnit.MilligramPerLiter, quantity30.Unit); var quantity31 = Density.From(1, DensityUnit.MilligramPerMilliliter); - AssertEx.EqualTolerance(1, quantity31.MilligramsPerMilliliter, MilligramsPerMilliliterTolerance); + Assert.Equal(1, quantity31.MilligramsPerMilliliter); Assert.Equal(DensityUnit.MilligramPerMilliliter, quantity31.Unit); var quantity32 = Density.From(1, DensityUnit.NanogramPerDeciliter); - AssertEx.EqualTolerance(1, quantity32.NanogramsPerDeciliter, NanogramsPerDeciliterTolerance); + Assert.Equal(1, quantity32.NanogramsPerDeciliter); Assert.Equal(DensityUnit.NanogramPerDeciliter, quantity32.Unit); var quantity33 = Density.From(1, DensityUnit.NanogramPerLiter); - AssertEx.EqualTolerance(1, quantity33.NanogramsPerLiter, NanogramsPerLiterTolerance); + Assert.Equal(1, quantity33.NanogramsPerLiter); Assert.Equal(DensityUnit.NanogramPerLiter, quantity33.Unit); var quantity34 = Density.From(1, DensityUnit.NanogramPerMilliliter); - AssertEx.EqualTolerance(1, quantity34.NanogramsPerMilliliter, NanogramsPerMilliliterTolerance); + Assert.Equal(1, quantity34.NanogramsPerMilliliter); Assert.Equal(DensityUnit.NanogramPerMilliliter, quantity34.Unit); var quantity35 = Density.From(1, DensityUnit.PicogramPerDeciliter); - AssertEx.EqualTolerance(1, quantity35.PicogramsPerDeciliter, PicogramsPerDeciliterTolerance); + Assert.Equal(1, quantity35.PicogramsPerDeciliter); Assert.Equal(DensityUnit.PicogramPerDeciliter, quantity35.Unit); var quantity36 = Density.From(1, DensityUnit.PicogramPerLiter); - AssertEx.EqualTolerance(1, quantity36.PicogramsPerLiter, PicogramsPerLiterTolerance); + Assert.Equal(1, quantity36.PicogramsPerLiter); Assert.Equal(DensityUnit.PicogramPerLiter, quantity36.Unit); var quantity37 = Density.From(1, DensityUnit.PicogramPerMilliliter); - AssertEx.EqualTolerance(1, quantity37.PicogramsPerMilliliter, PicogramsPerMilliliterTolerance); + Assert.Equal(1, quantity37.PicogramsPerMilliliter); Assert.Equal(DensityUnit.PicogramPerMilliliter, quantity37.Unit); var quantity38 = Density.From(1, DensityUnit.PoundPerCubicCentimeter); - AssertEx.EqualTolerance(1, quantity38.PoundsPerCubicCentimeter, PoundsPerCubicCentimeterTolerance); + Assert.Equal(1, quantity38.PoundsPerCubicCentimeter); Assert.Equal(DensityUnit.PoundPerCubicCentimeter, quantity38.Unit); var quantity39 = Density.From(1, DensityUnit.PoundPerCubicFoot); - AssertEx.EqualTolerance(1, quantity39.PoundsPerCubicFoot, PoundsPerCubicFootTolerance); + Assert.Equal(1, quantity39.PoundsPerCubicFoot); Assert.Equal(DensityUnit.PoundPerCubicFoot, quantity39.Unit); var quantity40 = Density.From(1, DensityUnit.PoundPerCubicInch); - AssertEx.EqualTolerance(1, quantity40.PoundsPerCubicInch, PoundsPerCubicInchTolerance); + Assert.Equal(1, quantity40.PoundsPerCubicInch); Assert.Equal(DensityUnit.PoundPerCubicInch, quantity40.Unit); var quantity41 = Density.From(1, DensityUnit.PoundPerCubicMeter); - AssertEx.EqualTolerance(1, quantity41.PoundsPerCubicMeter, PoundsPerCubicMeterTolerance); + Assert.Equal(1, quantity41.PoundsPerCubicMeter); Assert.Equal(DensityUnit.PoundPerCubicMeter, quantity41.Unit); var quantity42 = Density.From(1, DensityUnit.PoundPerCubicMillimeter); - AssertEx.EqualTolerance(1, quantity42.PoundsPerCubicMillimeter, PoundsPerCubicMillimeterTolerance); + Assert.Equal(1, quantity42.PoundsPerCubicMillimeter); Assert.Equal(DensityUnit.PoundPerCubicMillimeter, quantity42.Unit); var quantity43 = Density.From(1, DensityUnit.PoundPerCubicYard); - AssertEx.EqualTolerance(1, quantity43.PoundsPerCubicYard, PoundsPerCubicYardTolerance); + Assert.Equal(1, quantity43.PoundsPerCubicYard); Assert.Equal(DensityUnit.PoundPerCubicYard, quantity43.Unit); var quantity44 = Density.From(1, DensityUnit.PoundPerImperialGallon); - AssertEx.EqualTolerance(1, quantity44.PoundsPerImperialGallon, PoundsPerImperialGallonTolerance); + Assert.Equal(1, quantity44.PoundsPerImperialGallon); Assert.Equal(DensityUnit.PoundPerImperialGallon, quantity44.Unit); var quantity45 = Density.From(1, DensityUnit.PoundPerUSGallon); - AssertEx.EqualTolerance(1, quantity45.PoundsPerUSGallon, PoundsPerUSGallonTolerance); + Assert.Equal(1, quantity45.PoundsPerUSGallon); Assert.Equal(DensityUnit.PoundPerUSGallon, quantity45.Unit); var quantity46 = Density.From(1, DensityUnit.SlugPerCubicCentimeter); - AssertEx.EqualTolerance(1, quantity46.SlugsPerCubicCentimeter, SlugsPerCubicCentimeterTolerance); + Assert.Equal(1, quantity46.SlugsPerCubicCentimeter); Assert.Equal(DensityUnit.SlugPerCubicCentimeter, quantity46.Unit); var quantity47 = Density.From(1, DensityUnit.SlugPerCubicFoot); - AssertEx.EqualTolerance(1, quantity47.SlugsPerCubicFoot, SlugsPerCubicFootTolerance); + Assert.Equal(1, quantity47.SlugsPerCubicFoot); Assert.Equal(DensityUnit.SlugPerCubicFoot, quantity47.Unit); var quantity48 = Density.From(1, DensityUnit.SlugPerCubicInch); - AssertEx.EqualTolerance(1, quantity48.SlugsPerCubicInch, SlugsPerCubicInchTolerance); + Assert.Equal(1, quantity48.SlugsPerCubicInch); Assert.Equal(DensityUnit.SlugPerCubicInch, quantity48.Unit); var quantity49 = Density.From(1, DensityUnit.SlugPerCubicMeter); - AssertEx.EqualTolerance(1, quantity49.SlugsPerCubicMeter, SlugsPerCubicMeterTolerance); + Assert.Equal(1, quantity49.SlugsPerCubicMeter); Assert.Equal(DensityUnit.SlugPerCubicMeter, quantity49.Unit); var quantity50 = Density.From(1, DensityUnit.SlugPerCubicMillimeter); - AssertEx.EqualTolerance(1, quantity50.SlugsPerCubicMillimeter, SlugsPerCubicMillimeterTolerance); + Assert.Equal(1, quantity50.SlugsPerCubicMillimeter); Assert.Equal(DensityUnit.SlugPerCubicMillimeter, quantity50.Unit); var quantity51 = Density.From(1, DensityUnit.TonnePerCubicCentimeter); - AssertEx.EqualTolerance(1, quantity51.TonnesPerCubicCentimeter, TonnesPerCubicCentimeterTolerance); + Assert.Equal(1, quantity51.TonnesPerCubicCentimeter); Assert.Equal(DensityUnit.TonnePerCubicCentimeter, quantity51.Unit); var quantity52 = Density.From(1, DensityUnit.TonnePerCubicFoot); - AssertEx.EqualTolerance(1, quantity52.TonnesPerCubicFoot, TonnesPerCubicFootTolerance); + Assert.Equal(1, quantity52.TonnesPerCubicFoot); Assert.Equal(DensityUnit.TonnePerCubicFoot, quantity52.Unit); var quantity53 = Density.From(1, DensityUnit.TonnePerCubicInch); - AssertEx.EqualTolerance(1, quantity53.TonnesPerCubicInch, TonnesPerCubicInchTolerance); + Assert.Equal(1, quantity53.TonnesPerCubicInch); Assert.Equal(DensityUnit.TonnePerCubicInch, quantity53.Unit); var quantity54 = Density.From(1, DensityUnit.TonnePerCubicMeter); - AssertEx.EqualTolerance(1, quantity54.TonnesPerCubicMeter, TonnesPerCubicMeterTolerance); + Assert.Equal(1, quantity54.TonnesPerCubicMeter); Assert.Equal(DensityUnit.TonnePerCubicMeter, quantity54.Unit); var quantity55 = Density.From(1, DensityUnit.TonnePerCubicMillimeter); - AssertEx.EqualTolerance(1, quantity55.TonnesPerCubicMillimeter, TonnesPerCubicMillimeterTolerance); + Assert.Equal(1, quantity55.TonnesPerCubicMillimeter); Assert.Equal(DensityUnit.TonnePerCubicMillimeter, quantity55.Unit); } @@ -817,872 +835,154 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 cg/dl", DensityUnit.CentigramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 cg/l", DensityUnit.CentigramPerLiter, 4.2)] + [InlineData("en-US", "4.2 cg/ml", DensityUnit.CentigramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 dg/dl", DensityUnit.DecigramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 dg/l", DensityUnit.DecigramPerLiter, 4.2)] + [InlineData("en-US", "4.2 dg/ml", DensityUnit.DecigramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 fg/dl", DensityUnit.FemtogramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 fg/l", DensityUnit.FemtogramPerLiter, 4.2)] + [InlineData("en-US", "4.2 fg/ml", DensityUnit.FemtogramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 g/cm³", DensityUnit.GramPerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 g/ft³", DensityUnit.GramPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 g/in³", DensityUnit.GramPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 g/m³", DensityUnit.GramPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 g/mm³", DensityUnit.GramPerCubicMillimeter, 4.2)] + [InlineData("en-US", "4.2 g/dl", DensityUnit.GramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 g/l", DensityUnit.GramPerLiter, 4.2)] + [InlineData("en-US", "4.2 g/ml", DensityUnit.GramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 kg/cm³", DensityUnit.KilogramPerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 kg/m³", DensityUnit.KilogramPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 kg/mm³", DensityUnit.KilogramPerCubicMillimeter, 4.2)] + [InlineData("en-US", "4.2 kg/l", DensityUnit.KilogramPerLiter, 4.2)] + [InlineData("en-US", "4.2 kip/ft³", DensityUnit.KilopoundPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 kip/in³", DensityUnit.KilopoundPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 kip/yd³", DensityUnit.KilopoundPerCubicYard, 4.2)] + [InlineData("en-US", "4.2 µg/m³", DensityUnit.MicrogramPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 µg/dl", DensityUnit.MicrogramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 µg/l", DensityUnit.MicrogramPerLiter, 4.2)] + [InlineData("en-US", "4.2 µg/ml", DensityUnit.MicrogramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 mg/m³", DensityUnit.MilligramPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 mg/dl", DensityUnit.MilligramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 mg/l", DensityUnit.MilligramPerLiter, 4.2)] + [InlineData("en-US", "4.2 mg/ml", DensityUnit.MilligramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 ng/dl", DensityUnit.NanogramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 ng/l", DensityUnit.NanogramPerLiter, 4.2)] + [InlineData("en-US", "4.2 ng/ml", DensityUnit.NanogramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 pg/dl", DensityUnit.PicogramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 pg/l", DensityUnit.PicogramPerLiter, 4.2)] + [InlineData("en-US", "4.2 pg/ml", DensityUnit.PicogramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 lb/cm³", DensityUnit.PoundPerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 lbm/cm³", DensityUnit.PoundPerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 lb/ft³", DensityUnit.PoundPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 lbm/ft³", DensityUnit.PoundPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 lb/in³", DensityUnit.PoundPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 lbm/in³", DensityUnit.PoundPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 lb/m³", DensityUnit.PoundPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 lbm/m³", DensityUnit.PoundPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 lb/mm³", DensityUnit.PoundPerCubicMillimeter, 4.2)] + [InlineData("en-US", "4.2 lbm/mm³", DensityUnit.PoundPerCubicMillimeter, 4.2)] + [InlineData("en-US", "4.2 lb/yd³", DensityUnit.PoundPerCubicYard, 4.2)] + [InlineData("en-US", "4.2 lbm/yd³", DensityUnit.PoundPerCubicYard, 4.2)] + [InlineData("en-US", "4.2 ppg (imp.)", DensityUnit.PoundPerImperialGallon, 4.2)] + [InlineData("en-US", "4.2 ppg (U.S.)", DensityUnit.PoundPerUSGallon, 4.2)] + [InlineData("en-US", "4.2 slug/cm³", DensityUnit.SlugPerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 slug/ft³", DensityUnit.SlugPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 slug/in³", DensityUnit.SlugPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 slug/m³", DensityUnit.SlugPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 slug/mm³", DensityUnit.SlugPerCubicMillimeter, 4.2)] + [InlineData("en-US", "4.2 t/cm³", DensityUnit.TonnePerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 t/ft³", DensityUnit.TonnePerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 t/in³", DensityUnit.TonnePerCubicInch, 4.2)] + [InlineData("en-US", "4.2 t/m³", DensityUnit.TonnePerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 t/mm³", DensityUnit.TonnePerCubicMillimeter, 4.2)] + [InlineData("ru-RU", "4,2 г/м³", DensityUnit.GramPerCubicMeter, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = Density.Parse("1 cg/dl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentigramsPerDeciliter, CentigramsPerDeciliterTolerance); - Assert.Equal(DensityUnit.CentigramPerDeciliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 cg/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentigramsPerLiter, CentigramsPerLiterTolerance); - Assert.Equal(DensityUnit.CentigramPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 cg/ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentigramsPerMilliliter, CentigramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.CentigramPerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 dg/dl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecigramsPerDeciliter, DecigramsPerDeciliterTolerance); - Assert.Equal(DensityUnit.DecigramPerDeciliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 dg/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecigramsPerLiter, DecigramsPerLiterTolerance); - Assert.Equal(DensityUnit.DecigramPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 dg/ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecigramsPerMilliliter, DecigramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.DecigramPerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 fg/dl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.FemtogramsPerDeciliter, FemtogramsPerDeciliterTolerance); - Assert.Equal(DensityUnit.FemtogramPerDeciliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 fg/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.FemtogramsPerLiter, FemtogramsPerLiterTolerance); - Assert.Equal(DensityUnit.FemtogramPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 fg/ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.FemtogramsPerMilliliter, FemtogramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.FemtogramPerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 g/cm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerCubicCentimeter, GramsPerCubicCentimeterTolerance); - Assert.Equal(DensityUnit.GramPerCubicCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 g/ft³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerCubicFoot, GramsPerCubicFootTolerance); - Assert.Equal(DensityUnit.GramPerCubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 g/in³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerCubicInch, GramsPerCubicInchTolerance); - Assert.Equal(DensityUnit.GramPerCubicInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 g/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerCubicMeter, GramsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.GramPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 г/м³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.GramsPerCubicMeter, GramsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.GramPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 g/mm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerCubicMillimeter, GramsPerCubicMillimeterTolerance); - Assert.Equal(DensityUnit.GramPerCubicMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 g/dl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerDeciliter, GramsPerDeciliterTolerance); - Assert.Equal(DensityUnit.GramPerDeciliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 g/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerLiter, GramsPerLiterTolerance); - Assert.Equal(DensityUnit.GramPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 g/ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerMilliliter, GramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.GramPerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 kg/cm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerCubicCentimeter, KilogramsPerCubicCentimeterTolerance); - Assert.Equal(DensityUnit.KilogramPerCubicCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 kg/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.KilogramPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 кг/м³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.KilogramPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 kg/mm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerCubicMillimeter, KilogramsPerCubicMillimeterTolerance); - Assert.Equal(DensityUnit.KilogramPerCubicMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 kg/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerLiter, KilogramsPerLiterTolerance); - Assert.Equal(DensityUnit.KilogramPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 kip/ft³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsPerCubicFoot, KilopoundsPerCubicFootTolerance); - Assert.Equal(DensityUnit.KilopoundPerCubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 kip/in³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsPerCubicInch, KilopoundsPerCubicInchTolerance); - Assert.Equal(DensityUnit.KilopoundPerCubicInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 kip/yd³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsPerCubicYard, KilopoundsPerCubicYardTolerance); - Assert.Equal(DensityUnit.KilopoundPerCubicYard, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 µg/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerCubicMeter, MicrogramsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.MicrogramPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 мкг/м³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerCubicMeter, MicrogramsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.MicrogramPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 µg/dl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerDeciliter, MicrogramsPerDeciliterTolerance); - Assert.Equal(DensityUnit.MicrogramPerDeciliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 µg/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerLiter, MicrogramsPerLiterTolerance); - Assert.Equal(DensityUnit.MicrogramPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 µg/ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerMilliliter, MicrogramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.MicrogramPerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 mg/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligramsPerCubicMeter, MilligramsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.MilligramPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 мг/м³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MilligramsPerCubicMeter, MilligramsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.MilligramPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 mg/dl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligramsPerDeciliter, MilligramsPerDeciliterTolerance); - Assert.Equal(DensityUnit.MilligramPerDeciliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 mg/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligramsPerLiter, MilligramsPerLiterTolerance); - Assert.Equal(DensityUnit.MilligramPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 mg/ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligramsPerMilliliter, MilligramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.MilligramPerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 ng/dl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanogramsPerDeciliter, NanogramsPerDeciliterTolerance); - Assert.Equal(DensityUnit.NanogramPerDeciliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 ng/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanogramsPerLiter, NanogramsPerLiterTolerance); - Assert.Equal(DensityUnit.NanogramPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 ng/ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanogramsPerMilliliter, NanogramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.NanogramPerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 pg/dl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PicogramsPerDeciliter, PicogramsPerDeciliterTolerance); - Assert.Equal(DensityUnit.PicogramPerDeciliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 pg/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PicogramsPerLiter, PicogramsPerLiterTolerance); - Assert.Equal(DensityUnit.PicogramPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 pg/ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PicogramsPerMilliliter, PicogramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.PicogramPerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 lb/cm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicCentimeter, PoundsPerCubicCentimeterTolerance); - Assert.Equal(DensityUnit.PoundPerCubicCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 lbm/cm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicCentimeter, PoundsPerCubicCentimeterTolerance); - Assert.Equal(DensityUnit.PoundPerCubicCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 lb/ft³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicFoot, PoundsPerCubicFootTolerance); - Assert.Equal(DensityUnit.PoundPerCubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 lbm/ft³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicFoot, PoundsPerCubicFootTolerance); - Assert.Equal(DensityUnit.PoundPerCubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 lb/in³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicInch, PoundsPerCubicInchTolerance); - Assert.Equal(DensityUnit.PoundPerCubicInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 lbm/in³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicInch, PoundsPerCubicInchTolerance); - Assert.Equal(DensityUnit.PoundPerCubicInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 lb/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicMeter, PoundsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.PoundPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 lbm/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicMeter, PoundsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.PoundPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 lb/mm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicMillimeter, PoundsPerCubicMillimeterTolerance); - Assert.Equal(DensityUnit.PoundPerCubicMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 lbm/mm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicMillimeter, PoundsPerCubicMillimeterTolerance); - Assert.Equal(DensityUnit.PoundPerCubicMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 lb/yd³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicYard, PoundsPerCubicYardTolerance); - Assert.Equal(DensityUnit.PoundPerCubicYard, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 lbm/yd³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicYard, PoundsPerCubicYardTolerance); - Assert.Equal(DensityUnit.PoundPerCubicYard, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 ppg (imp.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerImperialGallon, PoundsPerImperialGallonTolerance); - Assert.Equal(DensityUnit.PoundPerImperialGallon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 ppg (U.S.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerUSGallon, PoundsPerUSGallonTolerance); - Assert.Equal(DensityUnit.PoundPerUSGallon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 slug/cm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SlugsPerCubicCentimeter, SlugsPerCubicCentimeterTolerance); - Assert.Equal(DensityUnit.SlugPerCubicCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 slug/ft³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SlugsPerCubicFoot, SlugsPerCubicFootTolerance); - Assert.Equal(DensityUnit.SlugPerCubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 slug/in³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SlugsPerCubicInch, SlugsPerCubicInchTolerance); - Assert.Equal(DensityUnit.SlugPerCubicInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 slug/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SlugsPerCubicMeter, SlugsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.SlugPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 slug/mm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SlugsPerCubicMillimeter, SlugsPerCubicMillimeterTolerance); - Assert.Equal(DensityUnit.SlugPerCubicMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 t/cm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonnesPerCubicCentimeter, TonnesPerCubicCentimeterTolerance); - Assert.Equal(DensityUnit.TonnePerCubicCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 t/ft³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonnesPerCubicFoot, TonnesPerCubicFootTolerance); - Assert.Equal(DensityUnit.TonnePerCubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 t/in³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonnesPerCubicInch, TonnesPerCubicInchTolerance); - Assert.Equal(DensityUnit.TonnePerCubicInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 t/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonnesPerCubicMeter, TonnesPerCubicMeterTolerance); - Assert.Equal(DensityUnit.TonnePerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Density.Parse("1 t/mm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonnesPerCubicMillimeter, TonnesPerCubicMillimeterTolerance); - Assert.Equal(DensityUnit.TonnePerCubicMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Density.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 cg/dl", DensityUnit.CentigramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 cg/l", DensityUnit.CentigramPerLiter, 4.2)] + [InlineData("en-US", "4.2 cg/ml", DensityUnit.CentigramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 dg/dl", DensityUnit.DecigramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 dg/l", DensityUnit.DecigramPerLiter, 4.2)] + [InlineData("en-US", "4.2 dg/ml", DensityUnit.DecigramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 fg/dl", DensityUnit.FemtogramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 fg/l", DensityUnit.FemtogramPerLiter, 4.2)] + [InlineData("en-US", "4.2 fg/ml", DensityUnit.FemtogramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 g/cm³", DensityUnit.GramPerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 g/ft³", DensityUnit.GramPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 g/in³", DensityUnit.GramPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 g/m³", DensityUnit.GramPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 g/mm³", DensityUnit.GramPerCubicMillimeter, 4.2)] + [InlineData("en-US", "4.2 g/dl", DensityUnit.GramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 g/l", DensityUnit.GramPerLiter, 4.2)] + [InlineData("en-US", "4.2 g/ml", DensityUnit.GramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 kg/cm³", DensityUnit.KilogramPerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 kg/m³", DensityUnit.KilogramPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 kg/mm³", DensityUnit.KilogramPerCubicMillimeter, 4.2)] + [InlineData("en-US", "4.2 kg/l", DensityUnit.KilogramPerLiter, 4.2)] + [InlineData("en-US", "4.2 kip/ft³", DensityUnit.KilopoundPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 kip/in³", DensityUnit.KilopoundPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 kip/yd³", DensityUnit.KilopoundPerCubicYard, 4.2)] + [InlineData("en-US", "4.2 µg/m³", DensityUnit.MicrogramPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 µg/dl", DensityUnit.MicrogramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 µg/l", DensityUnit.MicrogramPerLiter, 4.2)] + [InlineData("en-US", "4.2 µg/ml", DensityUnit.MicrogramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 mg/m³", DensityUnit.MilligramPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 mg/dl", DensityUnit.MilligramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 mg/l", DensityUnit.MilligramPerLiter, 4.2)] + [InlineData("en-US", "4.2 mg/ml", DensityUnit.MilligramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 ng/dl", DensityUnit.NanogramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 ng/l", DensityUnit.NanogramPerLiter, 4.2)] + [InlineData("en-US", "4.2 ng/ml", DensityUnit.NanogramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 pg/dl", DensityUnit.PicogramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 pg/l", DensityUnit.PicogramPerLiter, 4.2)] + [InlineData("en-US", "4.2 pg/ml", DensityUnit.PicogramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 lb/cm³", DensityUnit.PoundPerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 lbm/cm³", DensityUnit.PoundPerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 lb/ft³", DensityUnit.PoundPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 lbm/ft³", DensityUnit.PoundPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 lb/in³", DensityUnit.PoundPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 lbm/in³", DensityUnit.PoundPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 lb/m³", DensityUnit.PoundPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 lbm/m³", DensityUnit.PoundPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 lb/mm³", DensityUnit.PoundPerCubicMillimeter, 4.2)] + [InlineData("en-US", "4.2 lbm/mm³", DensityUnit.PoundPerCubicMillimeter, 4.2)] + [InlineData("en-US", "4.2 lb/yd³", DensityUnit.PoundPerCubicYard, 4.2)] + [InlineData("en-US", "4.2 lbm/yd³", DensityUnit.PoundPerCubicYard, 4.2)] + [InlineData("en-US", "4.2 ppg (imp.)", DensityUnit.PoundPerImperialGallon, 4.2)] + [InlineData("en-US", "4.2 ppg (U.S.)", DensityUnit.PoundPerUSGallon, 4.2)] + [InlineData("en-US", "4.2 slug/cm³", DensityUnit.SlugPerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 slug/ft³", DensityUnit.SlugPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 slug/in³", DensityUnit.SlugPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 slug/m³", DensityUnit.SlugPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 slug/mm³", DensityUnit.SlugPerCubicMillimeter, 4.2)] + [InlineData("en-US", "4.2 t/cm³", DensityUnit.TonnePerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 t/ft³", DensityUnit.TonnePerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 t/in³", DensityUnit.TonnePerCubicInch, 4.2)] + [InlineData("en-US", "4.2 t/m³", DensityUnit.TonnePerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 t/mm³", DensityUnit.TonnePerCubicMillimeter, 4.2)] + [InlineData("ru-RU", "4,2 г/м³", DensityUnit.GramPerCubicMeter, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(Density.TryParse("1 cg/dl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentigramsPerDeciliter, CentigramsPerDeciliterTolerance); - Assert.Equal(DensityUnit.CentigramPerDeciliter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 cg/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentigramsPerLiter, CentigramsPerLiterTolerance); - Assert.Equal(DensityUnit.CentigramPerLiter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 cg/ml", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentigramsPerMilliliter, CentigramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.CentigramPerMilliliter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 dg/dl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecigramsPerDeciliter, DecigramsPerDeciliterTolerance); - Assert.Equal(DensityUnit.DecigramPerDeciliter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 dg/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecigramsPerLiter, DecigramsPerLiterTolerance); - Assert.Equal(DensityUnit.DecigramPerLiter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 dg/ml", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecigramsPerMilliliter, DecigramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.DecigramPerMilliliter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 fg/dl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.FemtogramsPerDeciliter, FemtogramsPerDeciliterTolerance); - Assert.Equal(DensityUnit.FemtogramPerDeciliter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 fg/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.FemtogramsPerLiter, FemtogramsPerLiterTolerance); - Assert.Equal(DensityUnit.FemtogramPerLiter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 fg/ml", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.FemtogramsPerMilliliter, FemtogramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.FemtogramPerMilliliter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 g/cm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerCubicCentimeter, GramsPerCubicCentimeterTolerance); - Assert.Equal(DensityUnit.GramPerCubicCentimeter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 g/ft³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerCubicFoot, GramsPerCubicFootTolerance); - Assert.Equal(DensityUnit.GramPerCubicFoot, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 g/in³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerCubicInch, GramsPerCubicInchTolerance); - Assert.Equal(DensityUnit.GramPerCubicInch, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 g/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerCubicMeter, GramsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.GramPerCubicMeter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 г/м³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerCubicMeter, GramsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.GramPerCubicMeter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 g/mm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerCubicMillimeter, GramsPerCubicMillimeterTolerance); - Assert.Equal(DensityUnit.GramPerCubicMillimeter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 g/dl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerDeciliter, GramsPerDeciliterTolerance); - Assert.Equal(DensityUnit.GramPerDeciliter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 g/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerLiter, GramsPerLiterTolerance); - Assert.Equal(DensityUnit.GramPerLiter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 g/ml", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerMilliliter, GramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.GramPerMilliliter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 kg/cm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerCubicCentimeter, KilogramsPerCubicCentimeterTolerance); - Assert.Equal(DensityUnit.KilogramPerCubicCentimeter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 kg/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.KilogramPerCubicMeter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 кг/м³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.KilogramPerCubicMeter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 kg/mm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerCubicMillimeter, KilogramsPerCubicMillimeterTolerance); - Assert.Equal(DensityUnit.KilogramPerCubicMillimeter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 kg/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerLiter, KilogramsPerLiterTolerance); - Assert.Equal(DensityUnit.KilogramPerLiter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 kip/ft³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsPerCubicFoot, KilopoundsPerCubicFootTolerance); - Assert.Equal(DensityUnit.KilopoundPerCubicFoot, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 kip/in³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsPerCubicInch, KilopoundsPerCubicInchTolerance); - Assert.Equal(DensityUnit.KilopoundPerCubicInch, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 kip/yd³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsPerCubicYard, KilopoundsPerCubicYardTolerance); - Assert.Equal(DensityUnit.KilopoundPerCubicYard, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 µg/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerCubicMeter, MicrogramsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.MicrogramPerCubicMeter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 мкг/м³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerCubicMeter, MicrogramsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.MicrogramPerCubicMeter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 µg/dl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerDeciliter, MicrogramsPerDeciliterTolerance); - Assert.Equal(DensityUnit.MicrogramPerDeciliter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 µg/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerLiter, MicrogramsPerLiterTolerance); - Assert.Equal(DensityUnit.MicrogramPerLiter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 µg/ml", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerMilliliter, MicrogramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.MicrogramPerMilliliter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 mg/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligramsPerCubicMeter, MilligramsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.MilligramPerCubicMeter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 мг/м³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligramsPerCubicMeter, MilligramsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.MilligramPerCubicMeter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 mg/dl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligramsPerDeciliter, MilligramsPerDeciliterTolerance); - Assert.Equal(DensityUnit.MilligramPerDeciliter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 mg/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligramsPerLiter, MilligramsPerLiterTolerance); - Assert.Equal(DensityUnit.MilligramPerLiter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 mg/ml", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligramsPerMilliliter, MilligramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.MilligramPerMilliliter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 ng/dl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanogramsPerDeciliter, NanogramsPerDeciliterTolerance); - Assert.Equal(DensityUnit.NanogramPerDeciliter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 ng/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanogramsPerLiter, NanogramsPerLiterTolerance); - Assert.Equal(DensityUnit.NanogramPerLiter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 ng/ml", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanogramsPerMilliliter, NanogramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.NanogramPerMilliliter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 pg/dl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PicogramsPerDeciliter, PicogramsPerDeciliterTolerance); - Assert.Equal(DensityUnit.PicogramPerDeciliter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 pg/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PicogramsPerLiter, PicogramsPerLiterTolerance); - Assert.Equal(DensityUnit.PicogramPerLiter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 pg/ml", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PicogramsPerMilliliter, PicogramsPerMilliliterTolerance); - Assert.Equal(DensityUnit.PicogramPerMilliliter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 lb/cm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicCentimeter, PoundsPerCubicCentimeterTolerance); - Assert.Equal(DensityUnit.PoundPerCubicCentimeter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 lbm/cm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicCentimeter, PoundsPerCubicCentimeterTolerance); - Assert.Equal(DensityUnit.PoundPerCubicCentimeter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 lb/ft³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicFoot, PoundsPerCubicFootTolerance); - Assert.Equal(DensityUnit.PoundPerCubicFoot, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 lbm/ft³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicFoot, PoundsPerCubicFootTolerance); - Assert.Equal(DensityUnit.PoundPerCubicFoot, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 lb/in³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicInch, PoundsPerCubicInchTolerance); - Assert.Equal(DensityUnit.PoundPerCubicInch, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 lbm/in³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicInch, PoundsPerCubicInchTolerance); - Assert.Equal(DensityUnit.PoundPerCubicInch, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 lb/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicMeter, PoundsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.PoundPerCubicMeter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 lbm/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicMeter, PoundsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.PoundPerCubicMeter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 lb/mm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicMillimeter, PoundsPerCubicMillimeterTolerance); - Assert.Equal(DensityUnit.PoundPerCubicMillimeter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 lbm/mm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicMillimeter, PoundsPerCubicMillimeterTolerance); - Assert.Equal(DensityUnit.PoundPerCubicMillimeter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 lb/yd³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicYard, PoundsPerCubicYardTolerance); - Assert.Equal(DensityUnit.PoundPerCubicYard, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 lbm/yd³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicYard, PoundsPerCubicYardTolerance); - Assert.Equal(DensityUnit.PoundPerCubicYard, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 ppg (imp.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerImperialGallon, PoundsPerImperialGallonTolerance); - Assert.Equal(DensityUnit.PoundPerImperialGallon, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 ppg (U.S.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerUSGallon, PoundsPerUSGallonTolerance); - Assert.Equal(DensityUnit.PoundPerUSGallon, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 slug/cm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SlugsPerCubicCentimeter, SlugsPerCubicCentimeterTolerance); - Assert.Equal(DensityUnit.SlugPerCubicCentimeter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 slug/ft³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SlugsPerCubicFoot, SlugsPerCubicFootTolerance); - Assert.Equal(DensityUnit.SlugPerCubicFoot, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 slug/in³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SlugsPerCubicInch, SlugsPerCubicInchTolerance); - Assert.Equal(DensityUnit.SlugPerCubicInch, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 slug/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SlugsPerCubicMeter, SlugsPerCubicMeterTolerance); - Assert.Equal(DensityUnit.SlugPerCubicMeter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 slug/mm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SlugsPerCubicMillimeter, SlugsPerCubicMillimeterTolerance); - Assert.Equal(DensityUnit.SlugPerCubicMillimeter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 t/cm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonnesPerCubicCentimeter, TonnesPerCubicCentimeterTolerance); - Assert.Equal(DensityUnit.TonnePerCubicCentimeter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 t/ft³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonnesPerCubicFoot, TonnesPerCubicFootTolerance); - Assert.Equal(DensityUnit.TonnePerCubicFoot, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 t/in³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonnesPerCubicInch, TonnesPerCubicInchTolerance); - Assert.Equal(DensityUnit.TonnePerCubicInch, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 t/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonnesPerCubicMeter, TonnesPerCubicMeterTolerance); - Assert.Equal(DensityUnit.TonnePerCubicMeter, parsed.Unit); - } - - { - Assert.True(Density.TryParse("1 t/mm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonnesPerCubicMillimeter, TonnesPerCubicMillimeterTolerance); - Assert.Equal(DensityUnit.TonnePerCubicMillimeter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Density.TryParse(quantityString, out Density parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -2263,6 +1563,86 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Densit Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", DensityUnit.CentigramPerDeciliter, "cg/dl")] + [InlineData("en-US", DensityUnit.CentigramPerLiter, "cg/l")] + [InlineData("en-US", DensityUnit.CentigramPerMilliliter, "cg/ml")] + [InlineData("en-US", DensityUnit.DecigramPerDeciliter, "dg/dl")] + [InlineData("en-US", DensityUnit.DecigramPerLiter, "dg/l")] + [InlineData("en-US", DensityUnit.DecigramPerMilliliter, "dg/ml")] + [InlineData("en-US", DensityUnit.FemtogramPerDeciliter, "fg/dl")] + [InlineData("en-US", DensityUnit.FemtogramPerLiter, "fg/l")] + [InlineData("en-US", DensityUnit.FemtogramPerMilliliter, "fg/ml")] + [InlineData("en-US", DensityUnit.GramPerCubicCentimeter, "g/cm³")] + [InlineData("en-US", DensityUnit.GramPerCubicFoot, "g/ft³")] + [InlineData("en-US", DensityUnit.GramPerCubicInch, "g/in³")] + [InlineData("en-US", DensityUnit.GramPerCubicMeter, "g/m³")] + [InlineData("en-US", DensityUnit.GramPerCubicMillimeter, "g/mm³")] + [InlineData("en-US", DensityUnit.GramPerDeciliter, "g/dl")] + [InlineData("en-US", DensityUnit.GramPerLiter, "g/l")] + [InlineData("en-US", DensityUnit.GramPerMilliliter, "g/ml")] + [InlineData("en-US", DensityUnit.KilogramPerCubicCentimeter, "kg/cm³")] + [InlineData("en-US", DensityUnit.KilogramPerCubicMeter, "kg/m³")] + [InlineData("en-US", DensityUnit.KilogramPerCubicMillimeter, "kg/mm³")] + [InlineData("en-US", DensityUnit.KilogramPerLiter, "kg/l")] + [InlineData("en-US", DensityUnit.KilopoundPerCubicFoot, "kip/ft³")] + [InlineData("en-US", DensityUnit.KilopoundPerCubicInch, "kip/in³")] + [InlineData("en-US", DensityUnit.KilopoundPerCubicYard, "kip/yd³")] + [InlineData("en-US", DensityUnit.MicrogramPerCubicMeter, "µg/m³")] + [InlineData("en-US", DensityUnit.MicrogramPerDeciliter, "µg/dl")] + [InlineData("en-US", DensityUnit.MicrogramPerLiter, "µg/l")] + [InlineData("en-US", DensityUnit.MicrogramPerMilliliter, "µg/ml")] + [InlineData("en-US", DensityUnit.MilligramPerCubicMeter, "mg/m³")] + [InlineData("en-US", DensityUnit.MilligramPerDeciliter, "mg/dl")] + [InlineData("en-US", DensityUnit.MilligramPerLiter, "mg/l")] + [InlineData("en-US", DensityUnit.MilligramPerMilliliter, "mg/ml")] + [InlineData("en-US", DensityUnit.NanogramPerDeciliter, "ng/dl")] + [InlineData("en-US", DensityUnit.NanogramPerLiter, "ng/l")] + [InlineData("en-US", DensityUnit.NanogramPerMilliliter, "ng/ml")] + [InlineData("en-US", DensityUnit.PicogramPerDeciliter, "pg/dl")] + [InlineData("en-US", DensityUnit.PicogramPerLiter, "pg/l")] + [InlineData("en-US", DensityUnit.PicogramPerMilliliter, "pg/ml")] + [InlineData("en-US", DensityUnit.PoundPerCubicCentimeter, "lb/cm³")] + [InlineData("en-US", DensityUnit.PoundPerCubicFoot, "lb/ft³")] + [InlineData("en-US", DensityUnit.PoundPerCubicInch, "lb/in³")] + [InlineData("en-US", DensityUnit.PoundPerCubicMeter, "lb/m³")] + [InlineData("en-US", DensityUnit.PoundPerCubicMillimeter, "lb/mm³")] + [InlineData("en-US", DensityUnit.PoundPerCubicYard, "lb/yd³")] + [InlineData("en-US", DensityUnit.PoundPerImperialGallon, "ppg (imp.)")] + [InlineData("en-US", DensityUnit.PoundPerUSGallon, "ppg (U.S.)")] + [InlineData("en-US", DensityUnit.SlugPerCubicCentimeter, "slug/cm³")] + [InlineData("en-US", DensityUnit.SlugPerCubicFoot, "slug/ft³")] + [InlineData("en-US", DensityUnit.SlugPerCubicInch, "slug/in³")] + [InlineData("en-US", DensityUnit.SlugPerCubicMeter, "slug/m³")] + [InlineData("en-US", DensityUnit.SlugPerCubicMillimeter, "slug/mm³")] + [InlineData("en-US", DensityUnit.TonnePerCubicCentimeter, "t/cm³")] + [InlineData("en-US", DensityUnit.TonnePerCubicFoot, "t/ft³")] + [InlineData("en-US", DensityUnit.TonnePerCubicInch, "t/in³")] + [InlineData("en-US", DensityUnit.TonnePerCubicMeter, "t/m³")] + [InlineData("en-US", DensityUnit.TonnePerCubicMillimeter, "t/mm³")] + [InlineData("ru-RU", DensityUnit.GramPerCubicMeter, "г/м³")] + [InlineData("ru-RU", DensityUnit.KilogramPerCubicMeter, "кг/м³")] + [InlineData("ru-RU", DensityUnit.MicrogramPerCubicMeter, "мкг/м³")] + [InlineData("ru-RU", DensityUnit.MilligramPerCubicMeter, "мг/м³")] + public void GetAbbreviationForCulture(string culture, DensityUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Density.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Density.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Density.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(DensityUnit unit) @@ -2293,6 +1673,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); }); } @@ -2316,87 +1697,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] @@ -2442,8 +1825,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); @@ -2480,23 +1861,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = Density.FromKilogramsPerCubicMeter(1); - Assert.True(v.Equals(Density.FromKilogramsPerCubicMeter(1), KilogramsPerCubicMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Density.Zero, KilogramsPerCubicMeterTolerance, ComparisonType.Relative)); - Assert.True(Density.FromKilogramsPerCubicMeter(100).Equals(Density.FromKilogramsPerCubicMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(Density.FromKilogramsPerCubicMeter(100).Equals(Density.FromKilogramsPerCubicMeter(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = Density.FromKilogramsPerCubicMeter(1); - Assert.Throws(() => v.Equals(Density.FromKilogramsPerCubicMeter(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -2511,6 +1875,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(kilogrampercubicmeter.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = Density.FromKilogramsPerCubicMeter(1); + var negativeTolerance = Density.FromKilogramsPerCubicMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -2527,6 +1917,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() { @@ -2695,158 +2097,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Density))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(DensityUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal(Density.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal(Density.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal(new {Density.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 311dc0a652..1f11a1dc60 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/DoseAreaProductTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/DoseAreaProductTestsBase.g.cs @@ -172,7 +172,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new DoseAreaProduct(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -185,15 +185,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void DoseAreaProduct_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + DoseAreaProductUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new DoseAreaProduct(1, DoseAreaProductUnit.GraySquareMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(DoseAreaProduct.Zero, quantityInfo.Zero); Assert.Equal("DoseAreaProduct", quantityInfo.Name); + Assert.Equal(DoseAreaProduct.Zero, quantityInfo.Zero); + Assert.Equal(DoseAreaProduct.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(DoseAreaProduct.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void DoseAreaProductInfo_CreateWithCustomUnitInfos() + { + DoseAreaProductUnit[] expectedUnits = [DoseAreaProductUnit.GraySquareMeter]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -226,83 +244,83 @@ public void GraySquareMeterToDoseAreaProductUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = DoseAreaProduct.From(1, DoseAreaProductUnit.CentigraySquareCentimeter); - AssertEx.EqualTolerance(1, quantity00.CentigraySquareCentimeters, CentigraySquareCentimetersTolerance); + Assert.Equal(1, quantity00.CentigraySquareCentimeters); Assert.Equal(DoseAreaProductUnit.CentigraySquareCentimeter, quantity00.Unit); var quantity01 = DoseAreaProduct.From(1, DoseAreaProductUnit.CentigraySquareDecimeter); - AssertEx.EqualTolerance(1, quantity01.CentigraySquareDecimeters, CentigraySquareDecimetersTolerance); + Assert.Equal(1, quantity01.CentigraySquareDecimeters); Assert.Equal(DoseAreaProductUnit.CentigraySquareDecimeter, quantity01.Unit); var quantity02 = DoseAreaProduct.From(1, DoseAreaProductUnit.CentigraySquareMeter); - AssertEx.EqualTolerance(1, quantity02.CentigraySquareMeters, CentigraySquareMetersTolerance); + Assert.Equal(1, quantity02.CentigraySquareMeters); Assert.Equal(DoseAreaProductUnit.CentigraySquareMeter, quantity02.Unit); var quantity03 = DoseAreaProduct.From(1, DoseAreaProductUnit.CentigraySquareMillimeter); - AssertEx.EqualTolerance(1, quantity03.CentigraySquareMillimeters, CentigraySquareMillimetersTolerance); + Assert.Equal(1, quantity03.CentigraySquareMillimeters); Assert.Equal(DoseAreaProductUnit.CentigraySquareMillimeter, quantity03.Unit); var quantity04 = DoseAreaProduct.From(1, DoseAreaProductUnit.DecigraySquareCentimeter); - AssertEx.EqualTolerance(1, quantity04.DecigraySquareCentimeters, DecigraySquareCentimetersTolerance); + Assert.Equal(1, quantity04.DecigraySquareCentimeters); Assert.Equal(DoseAreaProductUnit.DecigraySquareCentimeter, quantity04.Unit); var quantity05 = DoseAreaProduct.From(1, DoseAreaProductUnit.DecigraySquareDecimeter); - AssertEx.EqualTolerance(1, quantity05.DecigraySquareDecimeters, DecigraySquareDecimetersTolerance); + Assert.Equal(1, quantity05.DecigraySquareDecimeters); Assert.Equal(DoseAreaProductUnit.DecigraySquareDecimeter, quantity05.Unit); var quantity06 = DoseAreaProduct.From(1, DoseAreaProductUnit.DecigraySquareMeter); - AssertEx.EqualTolerance(1, quantity06.DecigraySquareMeters, DecigraySquareMetersTolerance); + Assert.Equal(1, quantity06.DecigraySquareMeters); Assert.Equal(DoseAreaProductUnit.DecigraySquareMeter, quantity06.Unit); var quantity07 = DoseAreaProduct.From(1, DoseAreaProductUnit.DecigraySquareMillimeter); - AssertEx.EqualTolerance(1, quantity07.DecigraySquareMillimeters, DecigraySquareMillimetersTolerance); + Assert.Equal(1, quantity07.DecigraySquareMillimeters); Assert.Equal(DoseAreaProductUnit.DecigraySquareMillimeter, quantity07.Unit); var quantity08 = DoseAreaProduct.From(1, DoseAreaProductUnit.GraySquareCentimeter); - AssertEx.EqualTolerance(1, quantity08.GraySquareCentimeters, GraySquareCentimetersTolerance); + Assert.Equal(1, quantity08.GraySquareCentimeters); Assert.Equal(DoseAreaProductUnit.GraySquareCentimeter, quantity08.Unit); var quantity09 = DoseAreaProduct.From(1, DoseAreaProductUnit.GraySquareDecimeter); - AssertEx.EqualTolerance(1, quantity09.GraySquareDecimeters, GraySquareDecimetersTolerance); + Assert.Equal(1, quantity09.GraySquareDecimeters); Assert.Equal(DoseAreaProductUnit.GraySquareDecimeter, quantity09.Unit); var quantity10 = DoseAreaProduct.From(1, DoseAreaProductUnit.GraySquareMeter); - AssertEx.EqualTolerance(1, quantity10.GraySquareMeters, GraySquareMetersTolerance); + Assert.Equal(1, quantity10.GraySquareMeters); Assert.Equal(DoseAreaProductUnit.GraySquareMeter, quantity10.Unit); var quantity11 = DoseAreaProduct.From(1, DoseAreaProductUnit.GraySquareMillimeter); - AssertEx.EqualTolerance(1, quantity11.GraySquareMillimeters, GraySquareMillimetersTolerance); + Assert.Equal(1, quantity11.GraySquareMillimeters); Assert.Equal(DoseAreaProductUnit.GraySquareMillimeter, quantity11.Unit); var quantity12 = DoseAreaProduct.From(1, DoseAreaProductUnit.MicrograySquareCentimeter); - AssertEx.EqualTolerance(1, quantity12.MicrograySquareCentimeters, MicrograySquareCentimetersTolerance); + Assert.Equal(1, quantity12.MicrograySquareCentimeters); Assert.Equal(DoseAreaProductUnit.MicrograySquareCentimeter, quantity12.Unit); var quantity13 = DoseAreaProduct.From(1, DoseAreaProductUnit.MicrograySquareDecimeter); - AssertEx.EqualTolerance(1, quantity13.MicrograySquareDecimeters, MicrograySquareDecimetersTolerance); + Assert.Equal(1, quantity13.MicrograySquareDecimeters); Assert.Equal(DoseAreaProductUnit.MicrograySquareDecimeter, quantity13.Unit); var quantity14 = DoseAreaProduct.From(1, DoseAreaProductUnit.MicrograySquareMeter); - AssertEx.EqualTolerance(1, quantity14.MicrograySquareMeters, MicrograySquareMetersTolerance); + Assert.Equal(1, quantity14.MicrograySquareMeters); Assert.Equal(DoseAreaProductUnit.MicrograySquareMeter, quantity14.Unit); var quantity15 = DoseAreaProduct.From(1, DoseAreaProductUnit.MicrograySquareMillimeter); - AssertEx.EqualTolerance(1, quantity15.MicrograySquareMillimeters, MicrograySquareMillimetersTolerance); + Assert.Equal(1, quantity15.MicrograySquareMillimeters); Assert.Equal(DoseAreaProductUnit.MicrograySquareMillimeter, quantity15.Unit); var quantity16 = DoseAreaProduct.From(1, DoseAreaProductUnit.MilligraySquareCentimeter); - AssertEx.EqualTolerance(1, quantity16.MilligraySquareCentimeters, MilligraySquareCentimetersTolerance); + Assert.Equal(1, quantity16.MilligraySquareCentimeters); Assert.Equal(DoseAreaProductUnit.MilligraySquareCentimeter, quantity16.Unit); var quantity17 = DoseAreaProduct.From(1, DoseAreaProductUnit.MilligraySquareDecimeter); - AssertEx.EqualTolerance(1, quantity17.MilligraySquareDecimeters, MilligraySquareDecimetersTolerance); + Assert.Equal(1, quantity17.MilligraySquareDecimeters); Assert.Equal(DoseAreaProductUnit.MilligraySquareDecimeter, quantity17.Unit); var quantity18 = DoseAreaProduct.From(1, DoseAreaProductUnit.MilligraySquareMeter); - AssertEx.EqualTolerance(1, quantity18.MilligraySquareMeters, MilligraySquareMetersTolerance); + Assert.Equal(1, quantity18.MilligraySquareMeters); Assert.Equal(DoseAreaProductUnit.MilligraySquareMeter, quantity18.Unit); var quantity19 = DoseAreaProduct.From(1, DoseAreaProductUnit.MilligraySquareMillimeter); - AssertEx.EqualTolerance(1, quantity19.MilligraySquareMillimeters, MilligraySquareMillimetersTolerance); + Assert.Equal(1, quantity19.MilligraySquareMillimeters); Assert.Equal(DoseAreaProductUnit.MilligraySquareMillimeter, quantity19.Unit); } @@ -457,534 +475,102 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 cGy·cm²", DoseAreaProductUnit.CentigraySquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 cGy·dm²", DoseAreaProductUnit.CentigraySquareDecimeter, 4.2)] + [InlineData("en-US", "4.2 cGy·m²", DoseAreaProductUnit.CentigraySquareMeter, 4.2)] + [InlineData("en-US", "4.2 cGy·mm²", DoseAreaProductUnit.CentigraySquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 dGy·cm²", DoseAreaProductUnit.DecigraySquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 dGy·dm²", DoseAreaProductUnit.DecigraySquareDecimeter, 4.2)] + [InlineData("en-US", "4.2 dGy·m²", DoseAreaProductUnit.DecigraySquareMeter, 4.2)] + [InlineData("en-US", "4.2 dGy·mm²", DoseAreaProductUnit.DecigraySquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 Gy·cm²", DoseAreaProductUnit.GraySquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 Gy·dm²", DoseAreaProductUnit.GraySquareDecimeter, 4.2)] + [InlineData("en-US", "4.2 Gy·m²", DoseAreaProductUnit.GraySquareMeter, 4.2)] + [InlineData("en-US", "4.2 Gy·mm²", DoseAreaProductUnit.GraySquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 µGy·cm²", DoseAreaProductUnit.MicrograySquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 µGy·dm²", DoseAreaProductUnit.MicrograySquareDecimeter, 4.2)] + [InlineData("en-US", "4.2 µGy·m²", DoseAreaProductUnit.MicrograySquareMeter, 4.2)] + [InlineData("en-US", "4.2 µGy·mm²", DoseAreaProductUnit.MicrograySquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 mGy·cm²", DoseAreaProductUnit.MilligraySquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 mGy·dm²", DoseAreaProductUnit.MilligraySquareDecimeter, 4.2)] + [InlineData("en-US", "4.2 mGy·m²", DoseAreaProductUnit.MilligraySquareMeter, 4.2)] + [InlineData("en-US", "4.2 mGy·mm²", DoseAreaProductUnit.MilligraySquareMillimeter, 4.2)] + [InlineData("ru-RU", "4,2 сГр·см²", DoseAreaProductUnit.CentigraySquareCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 сГр·дм²", DoseAreaProductUnit.CentigraySquareDecimeter, 4.2)] + [InlineData("ru-RU", "4,2 сГр·м²", DoseAreaProductUnit.CentigraySquareMeter, 4.2)] + [InlineData("ru-RU", "4,2 сГр·мм²", DoseAreaProductUnit.CentigraySquareMillimeter, 4.2)] + [InlineData("ru-RU", "4,2 дГр·см²", DoseAreaProductUnit.DecigraySquareCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 дГр·дм²", DoseAreaProductUnit.DecigraySquareDecimeter, 4.2)] + [InlineData("ru-RU", "4,2 дГр·м²", DoseAreaProductUnit.DecigraySquareMeter, 4.2)] + [InlineData("ru-RU", "4,2 дГр·мм²", DoseAreaProductUnit.DecigraySquareMillimeter, 4.2)] + [InlineData("ru-RU", "4,2 Гр·см²", DoseAreaProductUnit.GraySquareCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 Гр·дм²", DoseAreaProductUnit.GraySquareDecimeter, 4.2)] + [InlineData("ru-RU", "4,2 Гр·м²", DoseAreaProductUnit.GraySquareMeter, 4.2)] + [InlineData("ru-RU", "4,2 Гр·мм²", DoseAreaProductUnit.GraySquareMillimeter, 4.2)] + [InlineData("ru-RU", "4,2 мкГр·см²", DoseAreaProductUnit.MicrograySquareCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 мкГр·дм²", DoseAreaProductUnit.MicrograySquareDecimeter, 4.2)] + [InlineData("ru-RU", "4,2 мкГр·м²", DoseAreaProductUnit.MicrograySquareMeter, 4.2)] + [InlineData("ru-RU", "4,2 мкГр·мм²", DoseAreaProductUnit.MicrograySquareMillimeter, 4.2)] + [InlineData("ru-RU", "4,2 мГр·см²", DoseAreaProductUnit.MilligraySquareCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 мГр·дм²", DoseAreaProductUnit.MilligraySquareDecimeter, 4.2)] + [InlineData("ru-RU", "4,2 мГр·м²", DoseAreaProductUnit.MilligraySquareMeter, 4.2)] + [InlineData("ru-RU", "4,2 мГр·мм²", DoseAreaProductUnit.MilligraySquareMillimeter, 4.2)] + public void Parse(string culture, string quantityString, DoseAreaProductUnit expectedUnit, decimal expectedValue) { - try - { - var parsed = DoseAreaProduct.Parse("1 cGy·cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentigraySquareCentimeters, CentigraySquareCentimetersTolerance); - Assert.Equal(DoseAreaProductUnit.CentigraySquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 сГр·см²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CentigraySquareCentimeters, CentigraySquareCentimetersTolerance); - Assert.Equal(DoseAreaProductUnit.CentigraySquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 cGy·dm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentigraySquareDecimeters, CentigraySquareDecimetersTolerance); - Assert.Equal(DoseAreaProductUnit.CentigraySquareDecimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 сГр·дм²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CentigraySquareDecimeters, CentigraySquareDecimetersTolerance); - Assert.Equal(DoseAreaProductUnit.CentigraySquareDecimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 cGy·m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentigraySquareMeters, CentigraySquareMetersTolerance); - Assert.Equal(DoseAreaProductUnit.CentigraySquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 сГр·м²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CentigraySquareMeters, CentigraySquareMetersTolerance); - Assert.Equal(DoseAreaProductUnit.CentigraySquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 cGy·mm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentigraySquareMillimeters, CentigraySquareMillimetersTolerance); - Assert.Equal(DoseAreaProductUnit.CentigraySquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 сГр·мм²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CentigraySquareMillimeters, CentigraySquareMillimetersTolerance); - Assert.Equal(DoseAreaProductUnit.CentigraySquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 dGy·cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecigraySquareCentimeters, DecigraySquareCentimetersTolerance); - Assert.Equal(DoseAreaProductUnit.DecigraySquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 дГр·см²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.DecigraySquareCentimeters, DecigraySquareCentimetersTolerance); - Assert.Equal(DoseAreaProductUnit.DecigraySquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 dGy·dm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecigraySquareDecimeters, DecigraySquareDecimetersTolerance); - Assert.Equal(DoseAreaProductUnit.DecigraySquareDecimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 дГр·дм²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.DecigraySquareDecimeters, DecigraySquareDecimetersTolerance); - Assert.Equal(DoseAreaProductUnit.DecigraySquareDecimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 dGy·m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecigraySquareMeters, DecigraySquareMetersTolerance); - Assert.Equal(DoseAreaProductUnit.DecigraySquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 дГр·м²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.DecigraySquareMeters, DecigraySquareMetersTolerance); - Assert.Equal(DoseAreaProductUnit.DecigraySquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 dGy·mm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecigraySquareMillimeters, DecigraySquareMillimetersTolerance); - Assert.Equal(DoseAreaProductUnit.DecigraySquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 дГр·мм²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.DecigraySquareMillimeters, DecigraySquareMillimetersTolerance); - Assert.Equal(DoseAreaProductUnit.DecigraySquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 Gy·cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GraySquareCentimeters, GraySquareCentimetersTolerance); - Assert.Equal(DoseAreaProductUnit.GraySquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 Гр·см²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.GraySquareCentimeters, GraySquareCentimetersTolerance); - Assert.Equal(DoseAreaProductUnit.GraySquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 Gy·dm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GraySquareDecimeters, GraySquareDecimetersTolerance); - Assert.Equal(DoseAreaProductUnit.GraySquareDecimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 Гр·дм²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.GraySquareDecimeters, GraySquareDecimetersTolerance); - Assert.Equal(DoseAreaProductUnit.GraySquareDecimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 Gy·m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GraySquareMeters, GraySquareMetersTolerance); - Assert.Equal(DoseAreaProductUnit.GraySquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 Гр·м²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.GraySquareMeters, GraySquareMetersTolerance); - Assert.Equal(DoseAreaProductUnit.GraySquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 Gy·mm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GraySquareMillimeters, GraySquareMillimetersTolerance); - Assert.Equal(DoseAreaProductUnit.GraySquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 Гр·мм²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.GraySquareMillimeters, GraySquareMillimetersTolerance); - Assert.Equal(DoseAreaProductUnit.GraySquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 µGy·cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrograySquareCentimeters, MicrograySquareCentimetersTolerance); - Assert.Equal(DoseAreaProductUnit.MicrograySquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 мкГр·см²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MicrograySquareCentimeters, MicrograySquareCentimetersTolerance); - Assert.Equal(DoseAreaProductUnit.MicrograySquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 µGy·dm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrograySquareDecimeters, MicrograySquareDecimetersTolerance); - Assert.Equal(DoseAreaProductUnit.MicrograySquareDecimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 мкГр·дм²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MicrograySquareDecimeters, MicrograySquareDecimetersTolerance); - Assert.Equal(DoseAreaProductUnit.MicrograySquareDecimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 µGy·m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrograySquareMeters, MicrograySquareMetersTolerance); - Assert.Equal(DoseAreaProductUnit.MicrograySquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 мкГр·м²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MicrograySquareMeters, MicrograySquareMetersTolerance); - Assert.Equal(DoseAreaProductUnit.MicrograySquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 µGy·mm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrograySquareMillimeters, MicrograySquareMillimetersTolerance); - Assert.Equal(DoseAreaProductUnit.MicrograySquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 мкГр·мм²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MicrograySquareMillimeters, MicrograySquareMillimetersTolerance); - Assert.Equal(DoseAreaProductUnit.MicrograySquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 mGy·cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligraySquareCentimeters, MilligraySquareCentimetersTolerance); - Assert.Equal(DoseAreaProductUnit.MilligraySquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 мГр·см²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MilligraySquareCentimeters, MilligraySquareCentimetersTolerance); - Assert.Equal(DoseAreaProductUnit.MilligraySquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 mGy·dm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligraySquareDecimeters, MilligraySquareDecimetersTolerance); - Assert.Equal(DoseAreaProductUnit.MilligraySquareDecimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 мГр·дм²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MilligraySquareDecimeters, MilligraySquareDecimetersTolerance); - Assert.Equal(DoseAreaProductUnit.MilligraySquareDecimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 mGy·m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligraySquareMeters, MilligraySquareMetersTolerance); - Assert.Equal(DoseAreaProductUnit.MilligraySquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 мГр·м²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MilligraySquareMeters, MilligraySquareMetersTolerance); - Assert.Equal(DoseAreaProductUnit.MilligraySquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 mGy·mm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligraySquareMillimeters, MilligraySquareMillimetersTolerance); - Assert.Equal(DoseAreaProductUnit.MilligraySquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DoseAreaProduct.Parse("1 мГр·мм²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MilligraySquareMillimeters, MilligraySquareMillimetersTolerance); - Assert.Equal(DoseAreaProductUnit.MilligraySquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = DoseAreaProduct.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 cGy·cm²", DoseAreaProductUnit.CentigraySquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 cGy·dm²", DoseAreaProductUnit.CentigraySquareDecimeter, 4.2)] + [InlineData("en-US", "4.2 cGy·m²", DoseAreaProductUnit.CentigraySquareMeter, 4.2)] + [InlineData("en-US", "4.2 cGy·mm²", DoseAreaProductUnit.CentigraySquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 dGy·cm²", DoseAreaProductUnit.DecigraySquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 dGy·dm²", DoseAreaProductUnit.DecigraySquareDecimeter, 4.2)] + [InlineData("en-US", "4.2 dGy·m²", DoseAreaProductUnit.DecigraySquareMeter, 4.2)] + [InlineData("en-US", "4.2 dGy·mm²", DoseAreaProductUnit.DecigraySquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 Gy·cm²", DoseAreaProductUnit.GraySquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 Gy·dm²", DoseAreaProductUnit.GraySquareDecimeter, 4.2)] + [InlineData("en-US", "4.2 Gy·m²", DoseAreaProductUnit.GraySquareMeter, 4.2)] + [InlineData("en-US", "4.2 Gy·mm²", DoseAreaProductUnit.GraySquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 µGy·cm²", DoseAreaProductUnit.MicrograySquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 µGy·dm²", DoseAreaProductUnit.MicrograySquareDecimeter, 4.2)] + [InlineData("en-US", "4.2 µGy·m²", DoseAreaProductUnit.MicrograySquareMeter, 4.2)] + [InlineData("en-US", "4.2 µGy·mm²", DoseAreaProductUnit.MicrograySquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 mGy·cm²", DoseAreaProductUnit.MilligraySquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 mGy·dm²", DoseAreaProductUnit.MilligraySquareDecimeter, 4.2)] + [InlineData("en-US", "4.2 mGy·m²", DoseAreaProductUnit.MilligraySquareMeter, 4.2)] + [InlineData("en-US", "4.2 mGy·mm²", DoseAreaProductUnit.MilligraySquareMillimeter, 4.2)] + [InlineData("ru-RU", "4,2 сГр·см²", DoseAreaProductUnit.CentigraySquareCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 сГр·дм²", DoseAreaProductUnit.CentigraySquareDecimeter, 4.2)] + [InlineData("ru-RU", "4,2 сГр·м²", DoseAreaProductUnit.CentigraySquareMeter, 4.2)] + [InlineData("ru-RU", "4,2 сГр·мм²", DoseAreaProductUnit.CentigraySquareMillimeter, 4.2)] + [InlineData("ru-RU", "4,2 дГр·см²", DoseAreaProductUnit.DecigraySquareCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 дГр·дм²", DoseAreaProductUnit.DecigraySquareDecimeter, 4.2)] + [InlineData("ru-RU", "4,2 дГр·м²", DoseAreaProductUnit.DecigraySquareMeter, 4.2)] + [InlineData("ru-RU", "4,2 дГр·мм²", DoseAreaProductUnit.DecigraySquareMillimeter, 4.2)] + [InlineData("ru-RU", "4,2 Гр·см²", DoseAreaProductUnit.GraySquareCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 Гр·дм²", DoseAreaProductUnit.GraySquareDecimeter, 4.2)] + [InlineData("ru-RU", "4,2 Гр·м²", DoseAreaProductUnit.GraySquareMeter, 4.2)] + [InlineData("ru-RU", "4,2 Гр·мм²", DoseAreaProductUnit.GraySquareMillimeter, 4.2)] + [InlineData("ru-RU", "4,2 мкГр·см²", DoseAreaProductUnit.MicrograySquareCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 мкГр·дм²", DoseAreaProductUnit.MicrograySquareDecimeter, 4.2)] + [InlineData("ru-RU", "4,2 мкГр·м²", DoseAreaProductUnit.MicrograySquareMeter, 4.2)] + [InlineData("ru-RU", "4,2 мкГр·мм²", DoseAreaProductUnit.MicrograySquareMillimeter, 4.2)] + [InlineData("ru-RU", "4,2 мГр·см²", DoseAreaProductUnit.MilligraySquareCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 мГр·дм²", DoseAreaProductUnit.MilligraySquareDecimeter, 4.2)] + [InlineData("ru-RU", "4,2 мГр·м²", DoseAreaProductUnit.MilligraySquareMeter, 4.2)] + [InlineData("ru-RU", "4,2 мГр·мм²", DoseAreaProductUnit.MilligraySquareMillimeter, 4.2)] + public void TryParse(string culture, string quantityString, DoseAreaProductUnit expectedUnit, decimal expectedValue) { - { - Assert.True(DoseAreaProduct.TryParse("1 cGy·cm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentigraySquareCentimeters, CentigraySquareCentimetersTolerance); - Assert.Equal(DoseAreaProductUnit.CentigraySquareCentimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 сГр·см²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentigraySquareCentimeters, CentigraySquareCentimetersTolerance); - Assert.Equal(DoseAreaProductUnit.CentigraySquareCentimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 cGy·dm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentigraySquareDecimeters, CentigraySquareDecimetersTolerance); - Assert.Equal(DoseAreaProductUnit.CentigraySquareDecimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 сГр·дм²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentigraySquareDecimeters, CentigraySquareDecimetersTolerance); - Assert.Equal(DoseAreaProductUnit.CentigraySquareDecimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 cGy·m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentigraySquareMeters, CentigraySquareMetersTolerance); - Assert.Equal(DoseAreaProductUnit.CentigraySquareMeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 сГр·м²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentigraySquareMeters, CentigraySquareMetersTolerance); - Assert.Equal(DoseAreaProductUnit.CentigraySquareMeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 cGy·mm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentigraySquareMillimeters, CentigraySquareMillimetersTolerance); - Assert.Equal(DoseAreaProductUnit.CentigraySquareMillimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 сГр·мм²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentigraySquareMillimeters, CentigraySquareMillimetersTolerance); - Assert.Equal(DoseAreaProductUnit.CentigraySquareMillimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 dGy·cm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecigraySquareCentimeters, DecigraySquareCentimetersTolerance); - Assert.Equal(DoseAreaProductUnit.DecigraySquareCentimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 дГр·см²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecigraySquareCentimeters, DecigraySquareCentimetersTolerance); - Assert.Equal(DoseAreaProductUnit.DecigraySquareCentimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 dGy·dm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecigraySquareDecimeters, DecigraySquareDecimetersTolerance); - Assert.Equal(DoseAreaProductUnit.DecigraySquareDecimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 дГр·дм²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecigraySquareDecimeters, DecigraySquareDecimetersTolerance); - Assert.Equal(DoseAreaProductUnit.DecigraySquareDecimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 dGy·m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecigraySquareMeters, DecigraySquareMetersTolerance); - Assert.Equal(DoseAreaProductUnit.DecigraySquareMeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 дГр·м²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecigraySquareMeters, DecigraySquareMetersTolerance); - Assert.Equal(DoseAreaProductUnit.DecigraySquareMeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 dGy·mm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecigraySquareMillimeters, DecigraySquareMillimetersTolerance); - Assert.Equal(DoseAreaProductUnit.DecigraySquareMillimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 дГр·мм²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecigraySquareMillimeters, DecigraySquareMillimetersTolerance); - Assert.Equal(DoseAreaProductUnit.DecigraySquareMillimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 Gy·cm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GraySquareCentimeters, GraySquareCentimetersTolerance); - Assert.Equal(DoseAreaProductUnit.GraySquareCentimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 Гр·см²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GraySquareCentimeters, GraySquareCentimetersTolerance); - Assert.Equal(DoseAreaProductUnit.GraySquareCentimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 Gy·dm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GraySquareDecimeters, GraySquareDecimetersTolerance); - Assert.Equal(DoseAreaProductUnit.GraySquareDecimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 Гр·дм²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GraySquareDecimeters, GraySquareDecimetersTolerance); - Assert.Equal(DoseAreaProductUnit.GraySquareDecimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 Gy·m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GraySquareMeters, GraySquareMetersTolerance); - Assert.Equal(DoseAreaProductUnit.GraySquareMeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 Гр·м²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GraySquareMeters, GraySquareMetersTolerance); - Assert.Equal(DoseAreaProductUnit.GraySquareMeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 Gy·mm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GraySquareMillimeters, GraySquareMillimetersTolerance); - Assert.Equal(DoseAreaProductUnit.GraySquareMillimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 Гр·мм²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GraySquareMillimeters, GraySquareMillimetersTolerance); - Assert.Equal(DoseAreaProductUnit.GraySquareMillimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 µGy·cm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrograySquareCentimeters, MicrograySquareCentimetersTolerance); - Assert.Equal(DoseAreaProductUnit.MicrograySquareCentimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 мкГр·см²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrograySquareCentimeters, MicrograySquareCentimetersTolerance); - Assert.Equal(DoseAreaProductUnit.MicrograySquareCentimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 µGy·dm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrograySquareDecimeters, MicrograySquareDecimetersTolerance); - Assert.Equal(DoseAreaProductUnit.MicrograySquareDecimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 мкГр·дм²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrograySquareDecimeters, MicrograySquareDecimetersTolerance); - Assert.Equal(DoseAreaProductUnit.MicrograySquareDecimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 µGy·m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrograySquareMeters, MicrograySquareMetersTolerance); - Assert.Equal(DoseAreaProductUnit.MicrograySquareMeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 мкГр·м²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrograySquareMeters, MicrograySquareMetersTolerance); - Assert.Equal(DoseAreaProductUnit.MicrograySquareMeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 µGy·mm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrograySquareMillimeters, MicrograySquareMillimetersTolerance); - Assert.Equal(DoseAreaProductUnit.MicrograySquareMillimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 мкГр·мм²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrograySquareMillimeters, MicrograySquareMillimetersTolerance); - Assert.Equal(DoseAreaProductUnit.MicrograySquareMillimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 mGy·cm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligraySquareCentimeters, MilligraySquareCentimetersTolerance); - Assert.Equal(DoseAreaProductUnit.MilligraySquareCentimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 мГр·см²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligraySquareCentimeters, MilligraySquareCentimetersTolerance); - Assert.Equal(DoseAreaProductUnit.MilligraySquareCentimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 mGy·dm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligraySquareDecimeters, MilligraySquareDecimetersTolerance); - Assert.Equal(DoseAreaProductUnit.MilligraySquareDecimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 мГр·дм²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligraySquareDecimeters, MilligraySquareDecimetersTolerance); - Assert.Equal(DoseAreaProductUnit.MilligraySquareDecimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 mGy·m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligraySquareMeters, MilligraySquareMetersTolerance); - Assert.Equal(DoseAreaProductUnit.MilligraySquareMeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 мГр·м²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligraySquareMeters, MilligraySquareMetersTolerance); - Assert.Equal(DoseAreaProductUnit.MilligraySquareMeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 mGy·mm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligraySquareMillimeters, MilligraySquareMillimetersTolerance); - Assert.Equal(DoseAreaProductUnit.MilligraySquareMillimeter, parsed.Unit); - } - - { - Assert.True(DoseAreaProduct.TryParse("1 мГр·мм²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligraySquareMillimeters, MilligraySquareMillimetersTolerance); - Assert.Equal(DoseAreaProductUnit.MilligraySquareMillimeter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(DoseAreaProduct.TryParse(quantityString, out DoseAreaProduct parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -1293,6 +879,66 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, DoseAr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", DoseAreaProductUnit.CentigraySquareCentimeter, "cGy·cm²")] + [InlineData("en-US", DoseAreaProductUnit.CentigraySquareDecimeter, "cGy·dm²")] + [InlineData("en-US", DoseAreaProductUnit.CentigraySquareMeter, "cGy·m²")] + [InlineData("en-US", DoseAreaProductUnit.CentigraySquareMillimeter, "cGy·mm²")] + [InlineData("en-US", DoseAreaProductUnit.DecigraySquareCentimeter, "dGy·cm²")] + [InlineData("en-US", DoseAreaProductUnit.DecigraySquareDecimeter, "dGy·dm²")] + [InlineData("en-US", DoseAreaProductUnit.DecigraySquareMeter, "dGy·m²")] + [InlineData("en-US", DoseAreaProductUnit.DecigraySquareMillimeter, "dGy·mm²")] + [InlineData("en-US", DoseAreaProductUnit.GraySquareCentimeter, "Gy·cm²")] + [InlineData("en-US", DoseAreaProductUnit.GraySquareDecimeter, "Gy·dm²")] + [InlineData("en-US", DoseAreaProductUnit.GraySquareMeter, "Gy·m²")] + [InlineData("en-US", DoseAreaProductUnit.GraySquareMillimeter, "Gy·mm²")] + [InlineData("en-US", DoseAreaProductUnit.MicrograySquareCentimeter, "µGy·cm²")] + [InlineData("en-US", DoseAreaProductUnit.MicrograySquareDecimeter, "µGy·dm²")] + [InlineData("en-US", DoseAreaProductUnit.MicrograySquareMeter, "µGy·m²")] + [InlineData("en-US", DoseAreaProductUnit.MicrograySquareMillimeter, "µGy·mm²")] + [InlineData("en-US", DoseAreaProductUnit.MilligraySquareCentimeter, "mGy·cm²")] + [InlineData("en-US", DoseAreaProductUnit.MilligraySquareDecimeter, "mGy·dm²")] + [InlineData("en-US", DoseAreaProductUnit.MilligraySquareMeter, "mGy·m²")] + [InlineData("en-US", DoseAreaProductUnit.MilligraySquareMillimeter, "mGy·mm²")] + [InlineData("ru-RU", DoseAreaProductUnit.CentigraySquareCentimeter, "сГр·см²")] + [InlineData("ru-RU", DoseAreaProductUnit.CentigraySquareDecimeter, "сГр·дм²")] + [InlineData("ru-RU", DoseAreaProductUnit.CentigraySquareMeter, "сГр·м²")] + [InlineData("ru-RU", DoseAreaProductUnit.CentigraySquareMillimeter, "сГр·мм²")] + [InlineData("ru-RU", DoseAreaProductUnit.DecigraySquareCentimeter, "дГр·см²")] + [InlineData("ru-RU", DoseAreaProductUnit.DecigraySquareDecimeter, "дГр·дм²")] + [InlineData("ru-RU", DoseAreaProductUnit.DecigraySquareMeter, "дГр·м²")] + [InlineData("ru-RU", DoseAreaProductUnit.DecigraySquareMillimeter, "дГр·мм²")] + [InlineData("ru-RU", DoseAreaProductUnit.GraySquareCentimeter, "Гр·см²")] + [InlineData("ru-RU", DoseAreaProductUnit.GraySquareDecimeter, "Гр·дм²")] + [InlineData("ru-RU", DoseAreaProductUnit.GraySquareMeter, "Гр·м²")] + [InlineData("ru-RU", DoseAreaProductUnit.GraySquareMillimeter, "Гр·мм²")] + [InlineData("ru-RU", DoseAreaProductUnit.MicrograySquareCentimeter, "мкГр·см²")] + [InlineData("ru-RU", DoseAreaProductUnit.MicrograySquareDecimeter, "мкГр·дм²")] + [InlineData("ru-RU", DoseAreaProductUnit.MicrograySquareMeter, "мкГр·м²")] + [InlineData("ru-RU", DoseAreaProductUnit.MicrograySquareMillimeter, "мкГр·мм²")] + [InlineData("ru-RU", DoseAreaProductUnit.MilligraySquareCentimeter, "мГр·см²")] + [InlineData("ru-RU", DoseAreaProductUnit.MilligraySquareDecimeter, "мГр·дм²")] + [InlineData("ru-RU", DoseAreaProductUnit.MilligraySquareMeter, "мГр·м²")] + [InlineData("ru-RU", DoseAreaProductUnit.MilligraySquareMillimeter, "мГр·мм²")] + public void GetAbbreviationForCulture(string culture, DoseAreaProductUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = DoseAreaProduct.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(DoseAreaProduct.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = DoseAreaProduct.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(DoseAreaProductUnit unit) @@ -1323,6 +969,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); }); } @@ -1346,51 +993,53 @@ 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.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.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.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.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.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.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.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.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.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.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] @@ -1436,8 +1085,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); @@ -1474,23 +1121,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = DoseAreaProduct.FromGraySquareMeters(1); - Assert.True(v.Equals(DoseAreaProduct.FromGraySquareMeters(1), GraySquareMetersTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(DoseAreaProduct.Zero, GraySquareMetersTolerance, ComparisonType.Relative)); - Assert.True(DoseAreaProduct.FromGraySquareMeters(100).Equals(DoseAreaProduct.FromGraySquareMeters(120), 0.3, ComparisonType.Relative)); - Assert.False(DoseAreaProduct.FromGraySquareMeters(100).Equals(DoseAreaProduct.FromGraySquareMeters(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = DoseAreaProduct.FromGraySquareMeters(1); - Assert.Throws(() => v.Equals(DoseAreaProduct.FromGraySquareMeters(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1505,6 +1135,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(graysquaremeter.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = DoseAreaProduct.FromGraySquareMeters(1); + var negativeTolerance = DoseAreaProduct.FromGraySquareMeters(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1521,6 +1177,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() { @@ -1617,158 +1285,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = DoseAreaProduct.FromGraySquareMeters(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = DoseAreaProduct.FromGraySquareMeters(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = DoseAreaProduct.FromGraySquareMeters(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = DoseAreaProduct.FromGraySquareMeters(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = DoseAreaProduct.FromGraySquareMeters(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = DoseAreaProduct.FromGraySquareMeters(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = DoseAreaProduct.FromGraySquareMeters(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = DoseAreaProduct.FromGraySquareMeters(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = DoseAreaProduct.FromGraySquareMeters(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = DoseAreaProduct.FromGraySquareMeters(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = DoseAreaProduct.FromGraySquareMeters(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = DoseAreaProduct.FromGraySquareMeters(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = DoseAreaProduct.FromGraySquareMeters(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = DoseAreaProduct.FromGraySquareMeters(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = DoseAreaProduct.FromGraySquareMeters(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = DoseAreaProduct.FromGraySquareMeters(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(DoseAreaProduct))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = DoseAreaProduct.FromGraySquareMeters(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(DoseAreaProductUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = DoseAreaProduct.FromGraySquareMeters(1.0); - Assert.Equal(DoseAreaProduct.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = DoseAreaProduct.FromGraySquareMeters(1.0); - Assert.Equal(DoseAreaProduct.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = DoseAreaProduct.FromGraySquareMeters(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = DoseAreaProduct.FromGraySquareMeters(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = DoseAreaProduct.FromGraySquareMeters(1.0); - Assert.Equal(new {DoseAreaProduct.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 4f8baa3f68..0f3da62177 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/DurationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/DurationTestsBase.g.cs @@ -140,7 +140,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Duration(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -153,15 +153,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Duration_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + DurationUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Duration(1, DurationUnit.Second); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Duration.Zero, quantityInfo.Zero); Assert.Equal("Duration", quantityInfo.Name); + Assert.Equal(Duration.Zero, quantityInfo.Zero); + Assert.Equal(Duration.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Duration.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void DurationInfo_CreateWithCustomUnitInfos() + { + DurationUnit[] expectedUnits = [DurationUnit.Second]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -186,51 +204,51 @@ public void SecondToDurationUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Duration.From(1, DurationUnit.Day); - AssertEx.EqualTolerance(1, quantity00.Days, DaysTolerance); + Assert.Equal(1, quantity00.Days); Assert.Equal(DurationUnit.Day, quantity00.Unit); var quantity01 = Duration.From(1, DurationUnit.Hour); - AssertEx.EqualTolerance(1, quantity01.Hours, HoursTolerance); + Assert.Equal(1, quantity01.Hours); Assert.Equal(DurationUnit.Hour, quantity01.Unit); var quantity02 = Duration.From(1, DurationUnit.JulianYear); - AssertEx.EqualTolerance(1, quantity02.JulianYears, JulianYearsTolerance); + Assert.Equal(1, quantity02.JulianYears); Assert.Equal(DurationUnit.JulianYear, quantity02.Unit); var quantity03 = Duration.From(1, DurationUnit.Microsecond); - AssertEx.EqualTolerance(1, quantity03.Microseconds, MicrosecondsTolerance); + Assert.Equal(1, quantity03.Microseconds); Assert.Equal(DurationUnit.Microsecond, quantity03.Unit); var quantity04 = Duration.From(1, DurationUnit.Millisecond); - AssertEx.EqualTolerance(1, quantity04.Milliseconds, MillisecondsTolerance); + Assert.Equal(1, quantity04.Milliseconds); Assert.Equal(DurationUnit.Millisecond, quantity04.Unit); var quantity05 = Duration.From(1, DurationUnit.Minute); - AssertEx.EqualTolerance(1, quantity05.Minutes, MinutesTolerance); + Assert.Equal(1, quantity05.Minutes); Assert.Equal(DurationUnit.Minute, quantity05.Unit); var quantity06 = Duration.From(1, DurationUnit.Month30); - AssertEx.EqualTolerance(1, quantity06.Months30, Months30Tolerance); + Assert.Equal(1, quantity06.Months30); Assert.Equal(DurationUnit.Month30, quantity06.Unit); var quantity07 = Duration.From(1, DurationUnit.Nanosecond); - AssertEx.EqualTolerance(1, quantity07.Nanoseconds, NanosecondsTolerance); + Assert.Equal(1, quantity07.Nanoseconds); Assert.Equal(DurationUnit.Nanosecond, quantity07.Unit); var quantity08 = Duration.From(1, DurationUnit.Second); - AssertEx.EqualTolerance(1, quantity08.Seconds, SecondsTolerance); + Assert.Equal(1, quantity08.Seconds); Assert.Equal(DurationUnit.Second, quantity08.Unit); var quantity09 = Duration.From(1, DurationUnit.Sol); - AssertEx.EqualTolerance(1, quantity09.Sols, SolsTolerance); + Assert.Equal(1, quantity09.Sols); Assert.Equal(DurationUnit.Sol, quantity09.Unit); var quantity10 = Duration.From(1, DurationUnit.Week); - AssertEx.EqualTolerance(1, quantity10.Weeks, WeeksTolerance); + Assert.Equal(1, quantity10.Weeks); Assert.Equal(DurationUnit.Week, quantity10.Unit); var quantity11 = Duration.From(1, DurationUnit.Year365); - AssertEx.EqualTolerance(1, quantity11.Years365, Years365Tolerance); + Assert.Equal(1, quantity11.Years365); Assert.Equal(DurationUnit.Year365, quantity11.Unit); } @@ -377,807 +395,144 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 d", DurationUnit.Day, 4.2)] + [InlineData("en-US", "4.2 day", DurationUnit.Day, 4.2)] + [InlineData("en-US", "4.2 days", DurationUnit.Day, 4.2)] + [InlineData("en-US", "4.2 h", DurationUnit.Hour, 4.2)] + [InlineData("en-US", "4.2 hr", DurationUnit.Hour, 4.2)] + [InlineData("en-US", "4.2 hrs", DurationUnit.Hour, 4.2)] + [InlineData("en-US", "4.2 hour", DurationUnit.Hour, 4.2)] + [InlineData("en-US", "4.2 hours", DurationUnit.Hour, 4.2)] + [InlineData("en-US", "4.2 jyr", DurationUnit.JulianYear, 4.2)] + [InlineData("en-US", "4.2 jyear", DurationUnit.JulianYear, 4.2)] + [InlineData("en-US", "4.2 jyears", DurationUnit.JulianYear, 4.2)] + [InlineData("en-US", "4.2 µs", DurationUnit.Microsecond, 4.2)] + [InlineData("en-US", "4.2 µsec", DurationUnit.Microsecond, 4.2)] + [InlineData("en-US", "4.2 µsecs", DurationUnit.Microsecond, 4.2)] + [InlineData("en-US", "4.2 µsecond", DurationUnit.Microsecond, 4.2)] + [InlineData("en-US", "4.2 µseconds", DurationUnit.Microsecond, 4.2)] + [InlineData("en-US", "4.2 ms", DurationUnit.Millisecond, 4.2)] + [InlineData("en-US", "4.2 msec", DurationUnit.Millisecond, 4.2)] + [InlineData("en-US", "4.2 msecs", DurationUnit.Millisecond, 4.2)] + [InlineData("en-US", "4.2 msecond", DurationUnit.Millisecond, 4.2)] + [InlineData("en-US", "4.2 mseconds", DurationUnit.Millisecond, 4.2)] + [InlineData("en-US", "4.2 m", DurationUnit.Minute, 4.2)] + [InlineData("en-US", "4.2 min", DurationUnit.Minute, 4.2)] + [InlineData("en-US", "4.2 minute", DurationUnit.Minute, 4.2)] + [InlineData("en-US", "4.2 minutes", DurationUnit.Minute, 4.2)] + [InlineData("en-US", "4.2 mo", DurationUnit.Month30, 4.2)] + [InlineData("en-US", "4.2 month", DurationUnit.Month30, 4.2)] + [InlineData("en-US", "4.2 months", DurationUnit.Month30, 4.2)] + [InlineData("en-US", "4.2 ns", DurationUnit.Nanosecond, 4.2)] + [InlineData("en-US", "4.2 nsec", DurationUnit.Nanosecond, 4.2)] + [InlineData("en-US", "4.2 nsecs", DurationUnit.Nanosecond, 4.2)] + [InlineData("en-US", "4.2 nsecond", DurationUnit.Nanosecond, 4.2)] + [InlineData("en-US", "4.2 nseconds", DurationUnit.Nanosecond, 4.2)] + [InlineData("en-US", "4.2 s", DurationUnit.Second, 4.2)] + [InlineData("en-US", "4.2 sec", DurationUnit.Second, 4.2)] + [InlineData("en-US", "4.2 secs", DurationUnit.Second, 4.2)] + [InlineData("en-US", "4.2 second", DurationUnit.Second, 4.2)] + [InlineData("en-US", "4.2 seconds", DurationUnit.Second, 4.2)] + [InlineData("en-US", "4.2 sol", DurationUnit.Sol, 4.2)] + [InlineData("en-US", "4.2 wk", DurationUnit.Week, 4.2)] + [InlineData("en-US", "4.2 week", DurationUnit.Week, 4.2)] + [InlineData("en-US", "4.2 weeks", DurationUnit.Week, 4.2)] + [InlineData("en-US", "4.2 yr", DurationUnit.Year365, 4.2)] + [InlineData("en-US", "4.2 year", DurationUnit.Year365, 4.2)] + [InlineData("en-US", "4.2 years", DurationUnit.Year365, 4.2)] + [InlineData("ru-RU", "4,2 сут", DurationUnit.Day, 4.2)] + [InlineData("ru-RU", "4,2 д", DurationUnit.Day, 4.2)] + [InlineData("ru-RU", "4,2 ч", DurationUnit.Hour, 4.2)] + [InlineData("ru-RU", "4,2 час", DurationUnit.Hour, 4.2)] + [InlineData("ru-RU", "4,2 мксек", DurationUnit.Microsecond, 4.2)] + [InlineData("ru-RU", "4,2 мкс", DurationUnit.Microsecond, 4.2)] + [InlineData("ru-RU", "4,2 мсек", DurationUnit.Millisecond, 4.2)] + [InlineData("ru-RU", "4,2 мс", DurationUnit.Millisecond, 4.2)] + [InlineData("ru-RU", "4,2 мин", DurationUnit.Minute, 4.2)] + [InlineData("ru-RU", "4,2 месяц", DurationUnit.Month30, 4.2)] + [InlineData("ru-RU", "4,2 нсек", DurationUnit.Nanosecond, 4.2)] + [InlineData("ru-RU", "4,2 нс", DurationUnit.Nanosecond, 4.2)] + [InlineData("ru-RU", "4,2 сек", DurationUnit.Second, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = Duration.Parse("1 d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Days, DaysTolerance); - Assert.Equal(DurationUnit.Day, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 day", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Days, DaysTolerance); - Assert.Equal(DurationUnit.Day, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 days", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Days, DaysTolerance); - Assert.Equal(DurationUnit.Day, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 сут", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Days, DaysTolerance); - Assert.Equal(DurationUnit.Day, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 д", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Days, DaysTolerance); - Assert.Equal(DurationUnit.Day, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Hours, HoursTolerance); - Assert.Equal(DurationUnit.Hour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 hr", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Hours, HoursTolerance); - Assert.Equal(DurationUnit.Hour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 hrs", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Hours, HoursTolerance); - Assert.Equal(DurationUnit.Hour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 hour", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Hours, HoursTolerance); - Assert.Equal(DurationUnit.Hour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 hours", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Hours, HoursTolerance); - Assert.Equal(DurationUnit.Hour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Hours, HoursTolerance); - Assert.Equal(DurationUnit.Hour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 час", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Hours, HoursTolerance); - Assert.Equal(DurationUnit.Hour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 jyr", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.JulianYears, JulianYearsTolerance); - Assert.Equal(DurationUnit.JulianYear, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 jyear", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.JulianYears, JulianYearsTolerance); - Assert.Equal(DurationUnit.JulianYear, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 jyears", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.JulianYears, JulianYearsTolerance); - Assert.Equal(DurationUnit.JulianYear, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 µs", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microseconds, MicrosecondsTolerance); - Assert.Equal(DurationUnit.Microsecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 µsec", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microseconds, MicrosecondsTolerance); - Assert.Equal(DurationUnit.Microsecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 µsecs", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microseconds, MicrosecondsTolerance); - Assert.Equal(DurationUnit.Microsecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 µsecond", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microseconds, MicrosecondsTolerance); - Assert.Equal(DurationUnit.Microsecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 µseconds", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microseconds, MicrosecondsTolerance); - Assert.Equal(DurationUnit.Microsecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 мксек", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Microseconds, MicrosecondsTolerance); - Assert.Equal(DurationUnit.Microsecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 мкс", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Microseconds, MicrosecondsTolerance); - Assert.Equal(DurationUnit.Microsecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 ms", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Milliseconds, MillisecondsTolerance); - Assert.Equal(DurationUnit.Millisecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 msec", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Milliseconds, MillisecondsTolerance); - Assert.Equal(DurationUnit.Millisecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 msecs", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Milliseconds, MillisecondsTolerance); - Assert.Equal(DurationUnit.Millisecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 msecond", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Milliseconds, MillisecondsTolerance); - Assert.Equal(DurationUnit.Millisecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 mseconds", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Milliseconds, MillisecondsTolerance); - Assert.Equal(DurationUnit.Millisecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 мсек", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Milliseconds, MillisecondsTolerance); - Assert.Equal(DurationUnit.Millisecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 мс", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Milliseconds, MillisecondsTolerance); - Assert.Equal(DurationUnit.Millisecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Minutes, MinutesTolerance); - Assert.Equal(DurationUnit.Minute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Minutes, MinutesTolerance); - Assert.Equal(DurationUnit.Minute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 minute", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Minutes, MinutesTolerance); - Assert.Equal(DurationUnit.Minute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 minutes", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Minutes, MinutesTolerance); - Assert.Equal(DurationUnit.Minute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Minutes, MinutesTolerance); - Assert.Equal(DurationUnit.Minute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 mo", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Months30, Months30Tolerance); - Assert.Equal(DurationUnit.Month30, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 month", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Months30, Months30Tolerance); - Assert.Equal(DurationUnit.Month30, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 months", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Months30, Months30Tolerance); - Assert.Equal(DurationUnit.Month30, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 месяц", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Months30, Months30Tolerance); - Assert.Equal(DurationUnit.Month30, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 ns", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanoseconds, NanosecondsTolerance); - Assert.Equal(DurationUnit.Nanosecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 nsec", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanoseconds, NanosecondsTolerance); - Assert.Equal(DurationUnit.Nanosecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 nsecs", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanoseconds, NanosecondsTolerance); - Assert.Equal(DurationUnit.Nanosecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 nsecond", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanoseconds, NanosecondsTolerance); - Assert.Equal(DurationUnit.Nanosecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 nseconds", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanoseconds, NanosecondsTolerance); - Assert.Equal(DurationUnit.Nanosecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 нсек", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Nanoseconds, NanosecondsTolerance); - Assert.Equal(DurationUnit.Nanosecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 нс", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Nanoseconds, NanosecondsTolerance); - Assert.Equal(DurationUnit.Nanosecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Seconds, SecondsTolerance); - Assert.Equal(DurationUnit.Second, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 sec", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Seconds, SecondsTolerance); - Assert.Equal(DurationUnit.Second, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 secs", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Seconds, SecondsTolerance); - Assert.Equal(DurationUnit.Second, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 second", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Seconds, SecondsTolerance); - Assert.Equal(DurationUnit.Second, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 seconds", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Seconds, SecondsTolerance); - Assert.Equal(DurationUnit.Second, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 сек", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Seconds, SecondsTolerance); - Assert.Equal(DurationUnit.Second, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Seconds, SecondsTolerance); - Assert.Equal(DurationUnit.Second, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 sol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Sols, SolsTolerance); - Assert.Equal(DurationUnit.Sol, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 wk", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Weeks, WeeksTolerance); - Assert.Equal(DurationUnit.Week, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 week", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Weeks, WeeksTolerance); - Assert.Equal(DurationUnit.Week, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 weeks", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Weeks, WeeksTolerance); - Assert.Equal(DurationUnit.Week, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 нед", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Weeks, WeeksTolerance); - Assert.Equal(DurationUnit.Week, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 yr", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Years365, Years365Tolerance); - Assert.Equal(DurationUnit.Year365, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 year", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Years365, Years365Tolerance); - Assert.Equal(DurationUnit.Year365, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 years", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Years365, Years365Tolerance); - Assert.Equal(DurationUnit.Year365, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Duration.Parse("1 год", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Years365, Years365Tolerance); - Assert.Equal(DurationUnit.Year365, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Duration.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 d", DurationUnit.Day, 4.2)] + [InlineData("en-US", "4.2 day", DurationUnit.Day, 4.2)] + [InlineData("en-US", "4.2 days", DurationUnit.Day, 4.2)] + [InlineData("en-US", "4.2 h", DurationUnit.Hour, 4.2)] + [InlineData("en-US", "4.2 hr", DurationUnit.Hour, 4.2)] + [InlineData("en-US", "4.2 hrs", DurationUnit.Hour, 4.2)] + [InlineData("en-US", "4.2 hour", DurationUnit.Hour, 4.2)] + [InlineData("en-US", "4.2 hours", DurationUnit.Hour, 4.2)] + [InlineData("en-US", "4.2 jyr", DurationUnit.JulianYear, 4.2)] + [InlineData("en-US", "4.2 jyear", DurationUnit.JulianYear, 4.2)] + [InlineData("en-US", "4.2 jyears", DurationUnit.JulianYear, 4.2)] + [InlineData("en-US", "4.2 µs", DurationUnit.Microsecond, 4.2)] + [InlineData("en-US", "4.2 µsec", DurationUnit.Microsecond, 4.2)] + [InlineData("en-US", "4.2 µsecs", DurationUnit.Microsecond, 4.2)] + [InlineData("en-US", "4.2 µsecond", DurationUnit.Microsecond, 4.2)] + [InlineData("en-US", "4.2 µseconds", DurationUnit.Microsecond, 4.2)] + [InlineData("en-US", "4.2 ms", DurationUnit.Millisecond, 4.2)] + [InlineData("en-US", "4.2 msec", DurationUnit.Millisecond, 4.2)] + [InlineData("en-US", "4.2 msecs", DurationUnit.Millisecond, 4.2)] + [InlineData("en-US", "4.2 msecond", DurationUnit.Millisecond, 4.2)] + [InlineData("en-US", "4.2 mseconds", DurationUnit.Millisecond, 4.2)] + [InlineData("en-US", "4.2 m", DurationUnit.Minute, 4.2)] + [InlineData("en-US", "4.2 min", DurationUnit.Minute, 4.2)] + [InlineData("en-US", "4.2 minute", DurationUnit.Minute, 4.2)] + [InlineData("en-US", "4.2 minutes", DurationUnit.Minute, 4.2)] + [InlineData("en-US", "4.2 mo", DurationUnit.Month30, 4.2)] + [InlineData("en-US", "4.2 month", DurationUnit.Month30, 4.2)] + [InlineData("en-US", "4.2 months", DurationUnit.Month30, 4.2)] + [InlineData("en-US", "4.2 ns", DurationUnit.Nanosecond, 4.2)] + [InlineData("en-US", "4.2 nsec", DurationUnit.Nanosecond, 4.2)] + [InlineData("en-US", "4.2 nsecs", DurationUnit.Nanosecond, 4.2)] + [InlineData("en-US", "4.2 nsecond", DurationUnit.Nanosecond, 4.2)] + [InlineData("en-US", "4.2 nseconds", DurationUnit.Nanosecond, 4.2)] + [InlineData("en-US", "4.2 s", DurationUnit.Second, 4.2)] + [InlineData("en-US", "4.2 sec", DurationUnit.Second, 4.2)] + [InlineData("en-US", "4.2 secs", DurationUnit.Second, 4.2)] + [InlineData("en-US", "4.2 second", DurationUnit.Second, 4.2)] + [InlineData("en-US", "4.2 seconds", DurationUnit.Second, 4.2)] + [InlineData("en-US", "4.2 sol", DurationUnit.Sol, 4.2)] + [InlineData("en-US", "4.2 wk", DurationUnit.Week, 4.2)] + [InlineData("en-US", "4.2 week", DurationUnit.Week, 4.2)] + [InlineData("en-US", "4.2 weeks", DurationUnit.Week, 4.2)] + [InlineData("en-US", "4.2 yr", DurationUnit.Year365, 4.2)] + [InlineData("en-US", "4.2 year", DurationUnit.Year365, 4.2)] + [InlineData("en-US", "4.2 years", DurationUnit.Year365, 4.2)] + [InlineData("ru-RU", "4,2 сут", DurationUnit.Day, 4.2)] + [InlineData("ru-RU", "4,2 д", DurationUnit.Day, 4.2)] + [InlineData("ru-RU", "4,2 ч", DurationUnit.Hour, 4.2)] + [InlineData("ru-RU", "4,2 час", DurationUnit.Hour, 4.2)] + [InlineData("ru-RU", "4,2 мксек", DurationUnit.Microsecond, 4.2)] + [InlineData("ru-RU", "4,2 мкс", DurationUnit.Microsecond, 4.2)] + [InlineData("ru-RU", "4,2 мсек", DurationUnit.Millisecond, 4.2)] + [InlineData("ru-RU", "4,2 мс", DurationUnit.Millisecond, 4.2)] + [InlineData("ru-RU", "4,2 мин", DurationUnit.Minute, 4.2)] + [InlineData("ru-RU", "4,2 месяц", DurationUnit.Month30, 4.2)] + [InlineData("ru-RU", "4,2 нсек", DurationUnit.Nanosecond, 4.2)] + [InlineData("ru-RU", "4,2 нс", DurationUnit.Nanosecond, 4.2)] + [InlineData("ru-RU", "4,2 сек", DurationUnit.Second, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(Duration.TryParse("1 d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Days, DaysTolerance); - Assert.Equal(DurationUnit.Day, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 day", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Days, DaysTolerance); - Assert.Equal(DurationUnit.Day, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 days", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Days, DaysTolerance); - Assert.Equal(DurationUnit.Day, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 сут", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Days, DaysTolerance); - Assert.Equal(DurationUnit.Day, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 д", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Days, DaysTolerance); - Assert.Equal(DurationUnit.Day, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Hours, HoursTolerance); - Assert.Equal(DurationUnit.Hour, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 hr", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Hours, HoursTolerance); - Assert.Equal(DurationUnit.Hour, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 hrs", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Hours, HoursTolerance); - Assert.Equal(DurationUnit.Hour, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 hour", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Hours, HoursTolerance); - Assert.Equal(DurationUnit.Hour, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 hours", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Hours, HoursTolerance); - Assert.Equal(DurationUnit.Hour, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 ч", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Hours, HoursTolerance); - Assert.Equal(DurationUnit.Hour, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 час", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Hours, HoursTolerance); - Assert.Equal(DurationUnit.Hour, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 jyr", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.JulianYears, JulianYearsTolerance); - Assert.Equal(DurationUnit.JulianYear, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 jyear", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.JulianYears, JulianYearsTolerance); - Assert.Equal(DurationUnit.JulianYear, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 jyears", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.JulianYears, JulianYearsTolerance); - Assert.Equal(DurationUnit.JulianYear, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 µs", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microseconds, MicrosecondsTolerance); - Assert.Equal(DurationUnit.Microsecond, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 µsec", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microseconds, MicrosecondsTolerance); - Assert.Equal(DurationUnit.Microsecond, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 µsecs", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microseconds, MicrosecondsTolerance); - Assert.Equal(DurationUnit.Microsecond, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 µsecond", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microseconds, MicrosecondsTolerance); - Assert.Equal(DurationUnit.Microsecond, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 µseconds", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microseconds, MicrosecondsTolerance); - Assert.Equal(DurationUnit.Microsecond, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 мксек", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microseconds, MicrosecondsTolerance); - Assert.Equal(DurationUnit.Microsecond, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 мкс", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microseconds, MicrosecondsTolerance); - Assert.Equal(DurationUnit.Microsecond, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 ms", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Milliseconds, MillisecondsTolerance); - Assert.Equal(DurationUnit.Millisecond, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 msec", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Milliseconds, MillisecondsTolerance); - Assert.Equal(DurationUnit.Millisecond, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 msecs", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Milliseconds, MillisecondsTolerance); - Assert.Equal(DurationUnit.Millisecond, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 msecond", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Milliseconds, MillisecondsTolerance); - Assert.Equal(DurationUnit.Millisecond, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 mseconds", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Milliseconds, MillisecondsTolerance); - Assert.Equal(DurationUnit.Millisecond, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 мсек", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Milliseconds, MillisecondsTolerance); - Assert.Equal(DurationUnit.Millisecond, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 мс", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Milliseconds, MillisecondsTolerance); - Assert.Equal(DurationUnit.Millisecond, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Minutes, MinutesTolerance); - Assert.Equal(DurationUnit.Minute, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Minutes, MinutesTolerance); - Assert.Equal(DurationUnit.Minute, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 minute", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Minutes, MinutesTolerance); - Assert.Equal(DurationUnit.Minute, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 minutes", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Minutes, MinutesTolerance); - Assert.Equal(DurationUnit.Minute, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Minutes, MinutesTolerance); - Assert.Equal(DurationUnit.Minute, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 mo", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Months30, Months30Tolerance); - Assert.Equal(DurationUnit.Month30, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 month", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Months30, Months30Tolerance); - Assert.Equal(DurationUnit.Month30, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 months", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Months30, Months30Tolerance); - Assert.Equal(DurationUnit.Month30, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 месяц", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Months30, Months30Tolerance); - Assert.Equal(DurationUnit.Month30, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 ns", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanoseconds, NanosecondsTolerance); - Assert.Equal(DurationUnit.Nanosecond, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 nsec", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanoseconds, NanosecondsTolerance); - Assert.Equal(DurationUnit.Nanosecond, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 nsecs", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanoseconds, NanosecondsTolerance); - Assert.Equal(DurationUnit.Nanosecond, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 nsecond", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanoseconds, NanosecondsTolerance); - Assert.Equal(DurationUnit.Nanosecond, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 nseconds", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanoseconds, NanosecondsTolerance); - Assert.Equal(DurationUnit.Nanosecond, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 нсек", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanoseconds, NanosecondsTolerance); - Assert.Equal(DurationUnit.Nanosecond, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 нс", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanoseconds, NanosecondsTolerance); - Assert.Equal(DurationUnit.Nanosecond, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Seconds, SecondsTolerance); - Assert.Equal(DurationUnit.Second, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 sec", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Seconds, SecondsTolerance); - Assert.Equal(DurationUnit.Second, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 secs", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Seconds, SecondsTolerance); - Assert.Equal(DurationUnit.Second, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 second", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Seconds, SecondsTolerance); - Assert.Equal(DurationUnit.Second, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 seconds", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Seconds, SecondsTolerance); - Assert.Equal(DurationUnit.Second, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 сек", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Seconds, SecondsTolerance); - Assert.Equal(DurationUnit.Second, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Seconds, SecondsTolerance); - Assert.Equal(DurationUnit.Second, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 sol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Sols, SolsTolerance); - Assert.Equal(DurationUnit.Sol, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 wk", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Weeks, WeeksTolerance); - Assert.Equal(DurationUnit.Week, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 week", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Weeks, WeeksTolerance); - Assert.Equal(DurationUnit.Week, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 weeks", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Weeks, WeeksTolerance); - Assert.Equal(DurationUnit.Week, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 нед", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Weeks, WeeksTolerance); - Assert.Equal(DurationUnit.Week, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 yr", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Years365, Years365Tolerance); - Assert.Equal(DurationUnit.Year365, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 year", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Years365, Years365Tolerance); - Assert.Equal(DurationUnit.Year365, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 years", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Years365, Years365Tolerance); - Assert.Equal(DurationUnit.Year365, parsed.Unit); - } - - { - Assert.True(Duration.TryParse("1 год", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Years365, Years365Tolerance); - Assert.Equal(DurationUnit.Year365, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Duration.TryParse(quantityString, out Duration parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -1670,6 +1025,48 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Durati Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", DurationUnit.Day, "d")] + [InlineData("en-US", DurationUnit.Hour, "h")] + [InlineData("en-US", DurationUnit.JulianYear, "jyr")] + [InlineData("en-US", DurationUnit.Microsecond, "µs")] + [InlineData("en-US", DurationUnit.Millisecond, "ms")] + [InlineData("en-US", DurationUnit.Minute, "m")] + [InlineData("en-US", DurationUnit.Month30, "mo")] + [InlineData("en-US", DurationUnit.Nanosecond, "ns")] + [InlineData("en-US", DurationUnit.Second, "s")] + [InlineData("en-US", DurationUnit.Sol, "sol")] + [InlineData("en-US", DurationUnit.Week, "wk")] + [InlineData("en-US", DurationUnit.Year365, "yr")] + [InlineData("ru-RU", DurationUnit.Day, "сут")] + [InlineData("ru-RU", DurationUnit.Hour, "ч")] + [InlineData("ru-RU", DurationUnit.Microsecond, "мксек")] + [InlineData("ru-RU", DurationUnit.Millisecond, "мсек")] + [InlineData("ru-RU", DurationUnit.Minute, "мин")] + [InlineData("ru-RU", DurationUnit.Month30, "месяц")] + [InlineData("ru-RU", DurationUnit.Nanosecond, "нсек")] + [InlineData("ru-RU", DurationUnit.Second, "сек")] + [InlineData("ru-RU", DurationUnit.Week, "нед")] + [InlineData("ru-RU", DurationUnit.Year365, "год")] + public void GetAbbreviationForCulture(string culture, DurationUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Duration.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Duration.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Duration.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(DurationUnit unit) @@ -1700,6 +1097,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); }); } @@ -1723,43 +1121,45 @@ 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.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.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] @@ -1805,8 +1205,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); @@ -1843,23 +1241,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = Duration.FromSeconds(1); - Assert.True(v.Equals(Duration.FromSeconds(1), SecondsTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Duration.Zero, SecondsTolerance, ComparisonType.Relative)); - Assert.True(Duration.FromSeconds(100).Equals(Duration.FromSeconds(120), 0.3, ComparisonType.Relative)); - Assert.False(Duration.FromSeconds(100).Equals(Duration.FromSeconds(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = Duration.FromSeconds(1); - Assert.Throws(() => v.Equals(Duration.FromSeconds(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1874,6 +1255,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(second.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = Duration.FromSeconds(1); + var negativeTolerance = Duration.FromSeconds(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1890,6 +1297,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() { @@ -1970,158 +1389,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Duration.FromSeconds(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Duration.FromSeconds(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Duration.FromSeconds(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Duration.FromSeconds(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Duration.FromSeconds(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Duration.FromSeconds(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Duration.FromSeconds(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Duration.FromSeconds(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Duration.FromSeconds(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Duration.FromSeconds(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Duration.FromSeconds(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Duration.FromSeconds(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Duration.FromSeconds(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Duration.FromSeconds(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Duration.FromSeconds(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Duration.FromSeconds(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Duration))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Duration.FromSeconds(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(DurationUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Duration.FromSeconds(1.0); - Assert.Equal(Duration.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Duration.FromSeconds(1.0); - Assert.Equal(Duration.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Duration.FromSeconds(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Duration.FromSeconds(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Duration.FromSeconds(1.0); - Assert.Equal(new {Duration.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 2ff7d00a15..bdaeb4a7f5 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/DynamicViscosityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/DynamicViscosityTestsBase.g.cs @@ -132,7 +132,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new DynamicViscosity(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -145,15 +145,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void DynamicViscosity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + DynamicViscosityUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new DynamicViscosity(1, DynamicViscosityUnit.NewtonSecondPerMeterSquared); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(DynamicViscosity.Zero, quantityInfo.Zero); Assert.Equal("DynamicViscosity", quantityInfo.Name); + Assert.Equal(DynamicViscosity.Zero, quantityInfo.Zero); + Assert.Equal(DynamicViscosity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(DynamicViscosity.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -176,43 +194,43 @@ public void NewtonSecondPerMeterSquaredToDynamicViscosityUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = DynamicViscosity.From(1, DynamicViscosityUnit.Centipoise); - AssertEx.EqualTolerance(1, quantity00.Centipoise, CentipoiseTolerance); + Assert.Equal(1, quantity00.Centipoise); Assert.Equal(DynamicViscosityUnit.Centipoise, quantity00.Unit); var quantity01 = DynamicViscosity.From(1, DynamicViscosityUnit.MicropascalSecond); - AssertEx.EqualTolerance(1, quantity01.MicropascalSeconds, MicropascalSecondsTolerance); + Assert.Equal(1, quantity01.MicropascalSeconds); Assert.Equal(DynamicViscosityUnit.MicropascalSecond, quantity01.Unit); var quantity02 = DynamicViscosity.From(1, DynamicViscosityUnit.MillipascalSecond); - AssertEx.EqualTolerance(1, quantity02.MillipascalSeconds, MillipascalSecondsTolerance); + Assert.Equal(1, quantity02.MillipascalSeconds); Assert.Equal(DynamicViscosityUnit.MillipascalSecond, quantity02.Unit); var quantity03 = DynamicViscosity.From(1, DynamicViscosityUnit.NewtonSecondPerMeterSquared); - AssertEx.EqualTolerance(1, quantity03.NewtonSecondsPerMeterSquared, NewtonSecondsPerMeterSquaredTolerance); + Assert.Equal(1, quantity03.NewtonSecondsPerMeterSquared); Assert.Equal(DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity03.Unit); var quantity04 = DynamicViscosity.From(1, DynamicViscosityUnit.PascalSecond); - AssertEx.EqualTolerance(1, quantity04.PascalSeconds, PascalSecondsTolerance); + Assert.Equal(1, quantity04.PascalSeconds); Assert.Equal(DynamicViscosityUnit.PascalSecond, quantity04.Unit); var quantity05 = DynamicViscosity.From(1, DynamicViscosityUnit.Poise); - AssertEx.EqualTolerance(1, quantity05.Poise, PoiseTolerance); + Assert.Equal(1, quantity05.Poise); Assert.Equal(DynamicViscosityUnit.Poise, quantity05.Unit); var quantity06 = DynamicViscosity.From(1, DynamicViscosityUnit.PoundForceSecondPerSquareFoot); - AssertEx.EqualTolerance(1, quantity06.PoundsForceSecondPerSquareFoot, PoundsForceSecondPerSquareFootTolerance); + Assert.Equal(1, quantity06.PoundsForceSecondPerSquareFoot); Assert.Equal(DynamicViscosityUnit.PoundForceSecondPerSquareFoot, quantity06.Unit); var quantity07 = DynamicViscosity.From(1, DynamicViscosityUnit.PoundForceSecondPerSquareInch); - AssertEx.EqualTolerance(1, quantity07.PoundsForceSecondPerSquareInch, PoundsForceSecondPerSquareInchTolerance); + Assert.Equal(1, quantity07.PoundsForceSecondPerSquareInch); Assert.Equal(DynamicViscosityUnit.PoundForceSecondPerSquareInch, quantity07.Unit); var quantity08 = DynamicViscosity.From(1, DynamicViscosityUnit.PoundPerFootSecond); - AssertEx.EqualTolerance(1, quantity08.PoundsPerFootSecond, PoundsPerFootSecondTolerance); + Assert.Equal(1, quantity08.PoundsPerFootSecond); Assert.Equal(DynamicViscosityUnit.PoundPerFootSecond, quantity08.Unit); var quantity09 = DynamicViscosity.From(1, DynamicViscosityUnit.Reyn); - AssertEx.EqualTolerance(1, quantity09.Reyns, ReynsTolerance); + Assert.Equal(1, quantity09.Reyns); Assert.Equal(DynamicViscosityUnit.Reyn, quantity09.Unit); } @@ -357,183 +375,48 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 cP", DynamicViscosityUnit.Centipoise, 4.2)] + [InlineData("en-US", "4.2 µPa·s", DynamicViscosityUnit.MicropascalSecond, 4.2)] + [InlineData("en-US", "4.2 µPaS", DynamicViscosityUnit.MicropascalSecond, 4.2)] + [InlineData("en-US", "4.2 mPa·s", DynamicViscosityUnit.MillipascalSecond, 4.2)] + [InlineData("en-US", "4.2 mPaS", DynamicViscosityUnit.MillipascalSecond, 4.2)] + [InlineData("en-US", "4.2 Ns/m²", DynamicViscosityUnit.NewtonSecondPerMeterSquared, 4.2)] + [InlineData("en-US", "4.2 Pa·s", DynamicViscosityUnit.PascalSecond, 4.2)] + [InlineData("en-US", "4.2 PaS", DynamicViscosityUnit.PascalSecond, 4.2)] + [InlineData("en-US", "4.2 P", DynamicViscosityUnit.Poise, 4.2)] + [InlineData("en-US", "4.2 lbf·s/ft²", DynamicViscosityUnit.PoundForceSecondPerSquareFoot, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = DynamicViscosity.Parse("1 cP", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Centipoise, CentipoiseTolerance); - Assert.Equal(DynamicViscosityUnit.Centipoise, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DynamicViscosity.Parse("1 µPa·s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicropascalSeconds, MicropascalSecondsTolerance); - Assert.Equal(DynamicViscosityUnit.MicropascalSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DynamicViscosity.Parse("1 µPaS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicropascalSeconds, MicropascalSecondsTolerance); - Assert.Equal(DynamicViscosityUnit.MicropascalSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DynamicViscosity.Parse("1 mPa·s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillipascalSeconds, MillipascalSecondsTolerance); - Assert.Equal(DynamicViscosityUnit.MillipascalSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DynamicViscosity.Parse("1 mPaS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillipascalSeconds, MillipascalSecondsTolerance); - Assert.Equal(DynamicViscosityUnit.MillipascalSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DynamicViscosity.Parse("1 Ns/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonSecondsPerMeterSquared, NewtonSecondsPerMeterSquaredTolerance); - Assert.Equal(DynamicViscosityUnit.NewtonSecondPerMeterSquared, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DynamicViscosity.Parse("1 Pa·s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PascalSeconds, PascalSecondsTolerance); - Assert.Equal(DynamicViscosityUnit.PascalSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DynamicViscosity.Parse("1 PaS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PascalSeconds, PascalSecondsTolerance); - Assert.Equal(DynamicViscosityUnit.PascalSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DynamicViscosity.Parse("1 P", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Poise, PoiseTolerance); - Assert.Equal(DynamicViscosityUnit.Poise, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DynamicViscosity.Parse("1 lbf·s/ft²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsForceSecondPerSquareFoot, PoundsForceSecondPerSquareFootTolerance); - Assert.Equal(DynamicViscosityUnit.PoundForceSecondPerSquareFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DynamicViscosity.Parse("1 lbf·s/in²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsForceSecondPerSquareInch, PoundsForceSecondPerSquareInchTolerance); - Assert.Equal(DynamicViscosityUnit.PoundForceSecondPerSquareInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DynamicViscosity.Parse("1 lb/(ft·s)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerFootSecond, PoundsPerFootSecondTolerance); - Assert.Equal(DynamicViscosityUnit.PoundPerFootSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = DynamicViscosity.Parse("1 reyn", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Reyns, ReynsTolerance); - Assert.Equal(DynamicViscosityUnit.Reyn, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = DynamicViscosity.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 cP", DynamicViscosityUnit.Centipoise, 4.2)] + [InlineData("en-US", "4.2 µPa·s", DynamicViscosityUnit.MicropascalSecond, 4.2)] + [InlineData("en-US", "4.2 µPaS", DynamicViscosityUnit.MicropascalSecond, 4.2)] + [InlineData("en-US", "4.2 mPa·s", DynamicViscosityUnit.MillipascalSecond, 4.2)] + [InlineData("en-US", "4.2 mPaS", DynamicViscosityUnit.MillipascalSecond, 4.2)] + [InlineData("en-US", "4.2 Ns/m²", DynamicViscosityUnit.NewtonSecondPerMeterSquared, 4.2)] + [InlineData("en-US", "4.2 Pa·s", DynamicViscosityUnit.PascalSecond, 4.2)] + [InlineData("en-US", "4.2 PaS", DynamicViscosityUnit.PascalSecond, 4.2)] + [InlineData("en-US", "4.2 P", DynamicViscosityUnit.Poise, 4.2)] + [InlineData("en-US", "4.2 lbf·s/ft²", DynamicViscosityUnit.PoundForceSecondPerSquareFoot, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(DynamicViscosity.TryParse("1 cP", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Centipoise, CentipoiseTolerance); - Assert.Equal(DynamicViscosityUnit.Centipoise, parsed.Unit); - } - - { - Assert.True(DynamicViscosity.TryParse("1 µPa·s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicropascalSeconds, MicropascalSecondsTolerance); - Assert.Equal(DynamicViscosityUnit.MicropascalSecond, parsed.Unit); - } - - { - Assert.True(DynamicViscosity.TryParse("1 µPaS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicropascalSeconds, MicropascalSecondsTolerance); - Assert.Equal(DynamicViscosityUnit.MicropascalSecond, parsed.Unit); - } - - { - Assert.True(DynamicViscosity.TryParse("1 mPa·s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillipascalSeconds, MillipascalSecondsTolerance); - Assert.Equal(DynamicViscosityUnit.MillipascalSecond, parsed.Unit); - } - - { - Assert.True(DynamicViscosity.TryParse("1 mPaS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillipascalSeconds, MillipascalSecondsTolerance); - Assert.Equal(DynamicViscosityUnit.MillipascalSecond, parsed.Unit); - } - - { - Assert.True(DynamicViscosity.TryParse("1 Ns/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonSecondsPerMeterSquared, NewtonSecondsPerMeterSquaredTolerance); - Assert.Equal(DynamicViscosityUnit.NewtonSecondPerMeterSquared, parsed.Unit); - } - - { - Assert.True(DynamicViscosity.TryParse("1 Pa·s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PascalSeconds, PascalSecondsTolerance); - Assert.Equal(DynamicViscosityUnit.PascalSecond, parsed.Unit); - } - - { - Assert.True(DynamicViscosity.TryParse("1 PaS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PascalSeconds, PascalSecondsTolerance); - Assert.Equal(DynamicViscosityUnit.PascalSecond, parsed.Unit); - } - - { - Assert.True(DynamicViscosity.TryParse("1 P", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Poise, PoiseTolerance); - Assert.Equal(DynamicViscosityUnit.Poise, parsed.Unit); - } - - { - Assert.True(DynamicViscosity.TryParse("1 lbf·s/ft²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsForceSecondPerSquareFoot, PoundsForceSecondPerSquareFootTolerance); - Assert.Equal(DynamicViscosityUnit.PoundForceSecondPerSquareFoot, parsed.Unit); - } - - { - Assert.True(DynamicViscosity.TryParse("1 lbf·s/in²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsForceSecondPerSquareInch, PoundsForceSecondPerSquareInchTolerance); - Assert.Equal(DynamicViscosityUnit.PoundForceSecondPerSquareInch, parsed.Unit); - } - - { - Assert.True(DynamicViscosity.TryParse("1 lb/(ft·s)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerFootSecond, PoundsPerFootSecondTolerance); - Assert.Equal(DynamicViscosityUnit.PoundPerFootSecond, parsed.Unit); - } - - { - Assert.True(DynamicViscosity.TryParse("1 reyn", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Reyns, ReynsTolerance); - Assert.Equal(DynamicViscosityUnit.Reyn, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(DynamicViscosity.TryParse(quantityString, out DynamicViscosity parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -706,6 +589,36 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Dynami Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", DynamicViscosityUnit.Centipoise, "cP")] + [InlineData("en-US", DynamicViscosityUnit.MicropascalSecond, "µPa·s")] + [InlineData("en-US", DynamicViscosityUnit.MillipascalSecond, "mPa·s")] + [InlineData("en-US", DynamicViscosityUnit.NewtonSecondPerMeterSquared, "Ns/m²")] + [InlineData("en-US", DynamicViscosityUnit.PascalSecond, "Pa·s")] + [InlineData("en-US", DynamicViscosityUnit.Poise, "P")] + [InlineData("en-US", DynamicViscosityUnit.PoundForceSecondPerSquareFoot, "lbf·s/ft²")] + [InlineData("en-US", DynamicViscosityUnit.PoundForceSecondPerSquareInch, "lbf·s/in²")] + [InlineData("en-US", DynamicViscosityUnit.PoundPerFootSecond, "lb/(ft·s)")] + [InlineData("en-US", DynamicViscosityUnit.Reyn, "reyn")] + public void GetAbbreviationForCulture(string culture, DynamicViscosityUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = DynamicViscosity.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(DynamicViscosity.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = DynamicViscosity.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(DynamicViscosityUnit unit) @@ -736,6 +649,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); }); } @@ -759,41 +673,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] @@ -839,8 +755,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); @@ -878,34 +792,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1); - Assert.True(v.Equals(DynamicViscosity.FromNewtonSecondsPerMeterSquared(1), NewtonSecondsPerMeterSquaredTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(DynamicViscosity.Zero, NewtonSecondsPerMeterSquaredTolerance, ComparisonType.Relative)); - Assert.True(DynamicViscosity.FromNewtonSecondsPerMeterSquared(100).Equals(DynamicViscosity.FromNewtonSecondsPerMeterSquared(120), 0.3, ComparisonType.Relative)); - Assert.False(DynamicViscosity.FromNewtonSecondsPerMeterSquared(100).Equals(DynamicViscosity.FromNewtonSecondsPerMeterSquared(120), 0.1, ComparisonType.Relative)); + DynamicViscosity newtonsecondpermetersquared = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1); + Assert.False(newtonsecondpermetersquared.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1); - Assert.Throws(() => v.Equals(DynamicViscosity.FromNewtonSecondsPerMeterSquared(1), -1, ComparisonType.Relative)); + DynamicViscosity newtonsecondpermetersquared = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1); + Assert.False(newtonsecondpermetersquared.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - DynamicViscosity newtonsecondpermetersquared = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1); - Assert.False(newtonsecondpermetersquared.Equals(new object())); + var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(firstValue); + var otherQuantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(secondValue); + DynamicViscosity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - DynamicViscosity newtonsecondpermetersquared = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1); - Assert.False(newtonsecondpermetersquared.Equals(null)); + var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1); + var negativeTolerance = DynamicViscosity.FromNewtonSecondsPerMeterSquared(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -924,6 +847,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() { @@ -1000,158 +935,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(DynamicViscosity))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(DynamicViscosityUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal(DynamicViscosity.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal(DynamicViscosity.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal(new {DynamicViscosity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 b750695927..6b950454c9 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricAdmittanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricAdmittanceTestsBase.g.cs @@ -156,7 +156,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ElectricAdmittance(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -169,15 +169,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ElectricAdmittance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ElectricAdmittanceUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ElectricAdmittance(1, ElectricAdmittanceUnit.Siemens); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ElectricAdmittance.Zero, quantityInfo.Zero); Assert.Equal("ElectricAdmittance", quantityInfo.Name); + Assert.Equal(ElectricAdmittance.Zero, quantityInfo.Zero); + Assert.Equal(ElectricAdmittance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ElectricAdmittance.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -206,67 +224,67 @@ public void SiemensToElectricAdmittanceUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ElectricAdmittance.From(1, ElectricAdmittanceUnit.Gigamho); - AssertEx.EqualTolerance(1, quantity00.Gigamhos, GigamhosTolerance); + Assert.Equal(1, quantity00.Gigamhos); Assert.Equal(ElectricAdmittanceUnit.Gigamho, quantity00.Unit); var quantity01 = ElectricAdmittance.From(1, ElectricAdmittanceUnit.Gigasiemens); - AssertEx.EqualTolerance(1, quantity01.Gigasiemens, GigasiemensTolerance); + Assert.Equal(1, quantity01.Gigasiemens); Assert.Equal(ElectricAdmittanceUnit.Gigasiemens, quantity01.Unit); var quantity02 = ElectricAdmittance.From(1, ElectricAdmittanceUnit.Kilomho); - AssertEx.EqualTolerance(1, quantity02.Kilomhos, KilomhosTolerance); + Assert.Equal(1, quantity02.Kilomhos); Assert.Equal(ElectricAdmittanceUnit.Kilomho, quantity02.Unit); var quantity03 = ElectricAdmittance.From(1, ElectricAdmittanceUnit.Kilosiemens); - AssertEx.EqualTolerance(1, quantity03.Kilosiemens, KilosiemensTolerance); + Assert.Equal(1, quantity03.Kilosiemens); Assert.Equal(ElectricAdmittanceUnit.Kilosiemens, quantity03.Unit); var quantity04 = ElectricAdmittance.From(1, ElectricAdmittanceUnit.Megamho); - AssertEx.EqualTolerance(1, quantity04.Megamhos, MegamhosTolerance); + Assert.Equal(1, quantity04.Megamhos); Assert.Equal(ElectricAdmittanceUnit.Megamho, quantity04.Unit); var quantity05 = ElectricAdmittance.From(1, ElectricAdmittanceUnit.Megasiemens); - AssertEx.EqualTolerance(1, quantity05.Megasiemens, MegasiemensTolerance); + Assert.Equal(1, quantity05.Megasiemens); Assert.Equal(ElectricAdmittanceUnit.Megasiemens, quantity05.Unit); var quantity06 = ElectricAdmittance.From(1, ElectricAdmittanceUnit.Mho); - AssertEx.EqualTolerance(1, quantity06.Mhos, MhosTolerance); + Assert.Equal(1, quantity06.Mhos); Assert.Equal(ElectricAdmittanceUnit.Mho, quantity06.Unit); var quantity07 = ElectricAdmittance.From(1, ElectricAdmittanceUnit.Micromho); - AssertEx.EqualTolerance(1, quantity07.Micromhos, MicromhosTolerance); + Assert.Equal(1, quantity07.Micromhos); Assert.Equal(ElectricAdmittanceUnit.Micromho, quantity07.Unit); var quantity08 = ElectricAdmittance.From(1, ElectricAdmittanceUnit.Microsiemens); - AssertEx.EqualTolerance(1, quantity08.Microsiemens, MicrosiemensTolerance); + Assert.Equal(1, quantity08.Microsiemens); Assert.Equal(ElectricAdmittanceUnit.Microsiemens, quantity08.Unit); var quantity09 = ElectricAdmittance.From(1, ElectricAdmittanceUnit.Millimho); - AssertEx.EqualTolerance(1, quantity09.Millimhos, MillimhosTolerance); + Assert.Equal(1, quantity09.Millimhos); Assert.Equal(ElectricAdmittanceUnit.Millimho, quantity09.Unit); var quantity10 = ElectricAdmittance.From(1, ElectricAdmittanceUnit.Millisiemens); - AssertEx.EqualTolerance(1, quantity10.Millisiemens, MillisiemensTolerance); + Assert.Equal(1, quantity10.Millisiemens); Assert.Equal(ElectricAdmittanceUnit.Millisiemens, quantity10.Unit); var quantity11 = ElectricAdmittance.From(1, ElectricAdmittanceUnit.Nanomho); - AssertEx.EqualTolerance(1, quantity11.Nanomhos, NanomhosTolerance); + Assert.Equal(1, quantity11.Nanomhos); Assert.Equal(ElectricAdmittanceUnit.Nanomho, quantity11.Unit); var quantity12 = ElectricAdmittance.From(1, ElectricAdmittanceUnit.Nanosiemens); - AssertEx.EqualTolerance(1, quantity12.Nanosiemens, NanosiemensTolerance); + Assert.Equal(1, quantity12.Nanosiemens); Assert.Equal(ElectricAdmittanceUnit.Nanosiemens, quantity12.Unit); var quantity13 = ElectricAdmittance.From(1, ElectricAdmittanceUnit.Siemens); - AssertEx.EqualTolerance(1, quantity13.Siemens, SiemensTolerance); + Assert.Equal(1, quantity13.Siemens); Assert.Equal(ElectricAdmittanceUnit.Siemens, quantity13.Unit); var quantity14 = ElectricAdmittance.From(1, ElectricAdmittanceUnit.Teramho); - AssertEx.EqualTolerance(1, quantity14.Teramhos, TeramhosTolerance); + Assert.Equal(1, quantity14.Teramhos); Assert.Equal(ElectricAdmittanceUnit.Teramho, quantity14.Unit); var quantity15 = ElectricAdmittance.From(1, ElectricAdmittanceUnit.Terasiemens); - AssertEx.EqualTolerance(1, quantity15.Terasiemens, TerasiemensTolerance); + Assert.Equal(1, quantity15.Terasiemens); Assert.Equal(ElectricAdmittanceUnit.Terasiemens, quantity15.Unit); } @@ -417,198 +435,54 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 G℧", ElectricAdmittanceUnit.Gigamho, 4.2)] + [InlineData("en-US", "4.2 GS", ElectricAdmittanceUnit.Gigasiemens, 4.2)] + [InlineData("en-US", "4.2 k℧", ElectricAdmittanceUnit.Kilomho, 4.2)] + [InlineData("en-US", "4.2 kS", ElectricAdmittanceUnit.Kilosiemens, 4.2)] + [InlineData("en-US", "4.2 M℧", ElectricAdmittanceUnit.Megamho, 4.2)] + [InlineData("en-US", "4.2 MS", ElectricAdmittanceUnit.Megasiemens, 4.2)] + [InlineData("en-US", "4.2 ℧", ElectricAdmittanceUnit.Mho, 4.2)] + [InlineData("en-US", "4.2 µ℧", ElectricAdmittanceUnit.Micromho, 4.2)] + [InlineData("en-US", "4.2 µS", ElectricAdmittanceUnit.Microsiemens, 4.2)] + [InlineData("en-US", "4.2 m℧", ElectricAdmittanceUnit.Millimho, 4.2)] + [InlineData("en-US", "4.2 mS", ElectricAdmittanceUnit.Millisiemens, 4.2)] + [InlineData("en-US", "4.2 n℧", ElectricAdmittanceUnit.Nanomho, 4.2)] + [InlineData("en-US", "4.2 nS", ElectricAdmittanceUnit.Nanosiemens, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = ElectricAdmittance.Parse("1 G℧", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Gigamhos, GigamhosTolerance); - Assert.Equal(ElectricAdmittanceUnit.Gigamho, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricAdmittance.Parse("1 GS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Gigasiemens, GigasiemensTolerance); - Assert.Equal(ElectricAdmittanceUnit.Gigasiemens, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricAdmittance.Parse("1 k℧", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilomhos, KilomhosTolerance); - Assert.Equal(ElectricAdmittanceUnit.Kilomho, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricAdmittance.Parse("1 kS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilosiemens, KilosiemensTolerance); - Assert.Equal(ElectricAdmittanceUnit.Kilosiemens, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricAdmittance.Parse("1 M℧", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megamhos, MegamhosTolerance); - Assert.Equal(ElectricAdmittanceUnit.Megamho, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricAdmittance.Parse("1 MS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megasiemens, MegasiemensTolerance); - Assert.Equal(ElectricAdmittanceUnit.Megasiemens, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricAdmittance.Parse("1 ℧", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Mhos, MhosTolerance); - Assert.Equal(ElectricAdmittanceUnit.Mho, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricAdmittance.Parse("1 µ℧", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Micromhos, MicromhosTolerance); - Assert.Equal(ElectricAdmittanceUnit.Micromho, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricAdmittance.Parse("1 µS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microsiemens, MicrosiemensTolerance); - Assert.Equal(ElectricAdmittanceUnit.Microsiemens, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricAdmittance.Parse("1 m℧", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millimhos, MillimhosTolerance); - Assert.Equal(ElectricAdmittanceUnit.Millimho, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricAdmittance.Parse("1 mS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millisiemens, MillisiemensTolerance); - Assert.Equal(ElectricAdmittanceUnit.Millisiemens, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricAdmittance.Parse("1 n℧", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanomhos, NanomhosTolerance); - Assert.Equal(ElectricAdmittanceUnit.Nanomho, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricAdmittance.Parse("1 nS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanosiemens, NanosiemensTolerance); - Assert.Equal(ElectricAdmittanceUnit.Nanosiemens, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricAdmittance.Parse("1 S", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Siemens, SiemensTolerance); - Assert.Equal(ElectricAdmittanceUnit.Siemens, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricAdmittance.Parse("1 T℧", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Teramhos, TeramhosTolerance); - Assert.Equal(ElectricAdmittanceUnit.Teramho, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricAdmittance.Parse("1 TS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Terasiemens, TerasiemensTolerance); - Assert.Equal(ElectricAdmittanceUnit.Terasiemens, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ElectricAdmittance.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 G℧", ElectricAdmittanceUnit.Gigamho, 4.2)] + [InlineData("en-US", "4.2 GS", ElectricAdmittanceUnit.Gigasiemens, 4.2)] + [InlineData("en-US", "4.2 k℧", ElectricAdmittanceUnit.Kilomho, 4.2)] + [InlineData("en-US", "4.2 kS", ElectricAdmittanceUnit.Kilosiemens, 4.2)] + [InlineData("en-US", "4.2 M℧", ElectricAdmittanceUnit.Megamho, 4.2)] + [InlineData("en-US", "4.2 MS", ElectricAdmittanceUnit.Megasiemens, 4.2)] + [InlineData("en-US", "4.2 ℧", ElectricAdmittanceUnit.Mho, 4.2)] + [InlineData("en-US", "4.2 µ℧", ElectricAdmittanceUnit.Micromho, 4.2)] + [InlineData("en-US", "4.2 µS", ElectricAdmittanceUnit.Microsiemens, 4.2)] + [InlineData("en-US", "4.2 m℧", ElectricAdmittanceUnit.Millimho, 4.2)] + [InlineData("en-US", "4.2 mS", ElectricAdmittanceUnit.Millisiemens, 4.2)] + [InlineData("en-US", "4.2 n℧", ElectricAdmittanceUnit.Nanomho, 4.2)] + [InlineData("en-US", "4.2 nS", ElectricAdmittanceUnit.Nanosiemens, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(ElectricAdmittance.TryParse("1 G℧", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gigamhos, GigamhosTolerance); - Assert.Equal(ElectricAdmittanceUnit.Gigamho, parsed.Unit); - } - - { - Assert.True(ElectricAdmittance.TryParse("1 GS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gigasiemens, GigasiemensTolerance); - Assert.Equal(ElectricAdmittanceUnit.Gigasiemens, parsed.Unit); - } - - { - Assert.True(ElectricAdmittance.TryParse("1 k℧", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilomhos, KilomhosTolerance); - Assert.Equal(ElectricAdmittanceUnit.Kilomho, parsed.Unit); - } - - { - Assert.True(ElectricAdmittance.TryParse("1 kS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilosiemens, KilosiemensTolerance); - Assert.Equal(ElectricAdmittanceUnit.Kilosiemens, parsed.Unit); - } - - { - Assert.True(ElectricAdmittance.TryParse("1 ℧", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Mhos, MhosTolerance); - Assert.Equal(ElectricAdmittanceUnit.Mho, parsed.Unit); - } - - { - Assert.True(ElectricAdmittance.TryParse("1 µ℧", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Micromhos, MicromhosTolerance); - Assert.Equal(ElectricAdmittanceUnit.Micromho, parsed.Unit); - } - - { - Assert.True(ElectricAdmittance.TryParse("1 µS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microsiemens, MicrosiemensTolerance); - Assert.Equal(ElectricAdmittanceUnit.Microsiemens, parsed.Unit); - } - - { - Assert.True(ElectricAdmittance.TryParse("1 n℧", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanomhos, NanomhosTolerance); - Assert.Equal(ElectricAdmittanceUnit.Nanomho, parsed.Unit); - } - - { - Assert.True(ElectricAdmittance.TryParse("1 nS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanosiemens, NanosiemensTolerance); - Assert.Equal(ElectricAdmittanceUnit.Nanosiemens, parsed.Unit); - } - - { - Assert.True(ElectricAdmittance.TryParse("1 S", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Siemens, SiemensTolerance); - Assert.Equal(ElectricAdmittanceUnit.Siemens, parsed.Unit); - } - - { - Assert.True(ElectricAdmittance.TryParse("1 T℧", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Teramhos, TeramhosTolerance); - Assert.Equal(ElectricAdmittanceUnit.Teramho, parsed.Unit); - } - - { - Assert.True(ElectricAdmittance.TryParse("1 TS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Terasiemens, TerasiemensTolerance); - Assert.Equal(ElectricAdmittanceUnit.Terasiemens, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ElectricAdmittance.TryParse(quantityString, out ElectricAdmittance parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -805,6 +679,42 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Electr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ElectricAdmittanceUnit.Gigamho, "G℧")] + [InlineData("en-US", ElectricAdmittanceUnit.Gigasiemens, "GS")] + [InlineData("en-US", ElectricAdmittanceUnit.Kilomho, "k℧")] + [InlineData("en-US", ElectricAdmittanceUnit.Kilosiemens, "kS")] + [InlineData("en-US", ElectricAdmittanceUnit.Megamho, "M℧")] + [InlineData("en-US", ElectricAdmittanceUnit.Megasiemens, "MS")] + [InlineData("en-US", ElectricAdmittanceUnit.Mho, "℧")] + [InlineData("en-US", ElectricAdmittanceUnit.Micromho, "µ℧")] + [InlineData("en-US", ElectricAdmittanceUnit.Microsiemens, "µS")] + [InlineData("en-US", ElectricAdmittanceUnit.Millimho, "m℧")] + [InlineData("en-US", ElectricAdmittanceUnit.Millisiemens, "mS")] + [InlineData("en-US", ElectricAdmittanceUnit.Nanomho, "n℧")] + [InlineData("en-US", ElectricAdmittanceUnit.Nanosiemens, "nS")] + [InlineData("en-US", ElectricAdmittanceUnit.Siemens, "S")] + [InlineData("en-US", ElectricAdmittanceUnit.Teramho, "T℧")] + [InlineData("en-US", ElectricAdmittanceUnit.Terasiemens, "TS")] + public void GetAbbreviationForCulture(string culture, ElectricAdmittanceUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ElectricAdmittance.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ElectricAdmittance.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ElectricAdmittance.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricAdmittanceUnit unit) @@ -835,6 +745,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); }); } @@ -858,47 +769,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] @@ -944,8 +857,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); @@ -982,23 +893,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = ElectricAdmittance.FromSiemens(1); - Assert.True(v.Equals(ElectricAdmittance.FromSiemens(1), SiemensTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ElectricAdmittance.Zero, SiemensTolerance, ComparisonType.Relative)); - Assert.True(ElectricAdmittance.FromSiemens(100).Equals(ElectricAdmittance.FromSiemens(120), 0.3, ComparisonType.Relative)); - Assert.False(ElectricAdmittance.FromSiemens(100).Equals(ElectricAdmittance.FromSiemens(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = ElectricAdmittance.FromSiemens(1); - Assert.Throws(() => v.Equals(ElectricAdmittance.FromSiemens(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1013,6 +907,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(siemens.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = ElectricAdmittance.FromSiemens(1); + var negativeTolerance = ElectricAdmittance.FromSiemens(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1029,6 +949,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() { @@ -1117,158 +1049,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ElectricAdmittance))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricAdmittanceUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal(ElectricAdmittance.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal(ElectricAdmittance.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal(new {ElectricAdmittance.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 fab911cf10..5540ec690c 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricApparentEnergyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricApparentEnergyTestsBase.g.cs @@ -104,7 +104,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ElectricApparentEnergy(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -117,15 +117,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ElectricApparentEnergy_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ElectricApparentEnergyUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ElectricApparentEnergy(1, ElectricApparentEnergyUnit.VoltampereHour); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ElectricApparentEnergy.Zero, quantityInfo.Zero); Assert.Equal("ElectricApparentEnergy", quantityInfo.Name); + Assert.Equal(ElectricApparentEnergy.Zero, quantityInfo.Zero); + Assert.Equal(ElectricApparentEnergy.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ElectricApparentEnergy.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void ElectricApparentEnergyInfo_CreateWithCustomUnitInfos() + { + ElectricApparentEnergyUnit[] expectedUnits = [ElectricApparentEnergyUnit.VoltampereHour]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -141,15 +159,15 @@ public void VoltampereHourToElectricApparentEnergyUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ElectricApparentEnergy.From(1, ElectricApparentEnergyUnit.KilovoltampereHour); - AssertEx.EqualTolerance(1, quantity00.KilovoltampereHours, KilovoltampereHoursTolerance); + Assert.Equal(1, quantity00.KilovoltampereHours); Assert.Equal(ElectricApparentEnergyUnit.KilovoltampereHour, quantity00.Unit); var quantity01 = ElectricApparentEnergy.From(1, ElectricApparentEnergyUnit.MegavoltampereHour); - AssertEx.EqualTolerance(1, quantity01.MegavoltampereHours, MegavoltampereHoursTolerance); + Assert.Equal(1, quantity01.MegavoltampereHours); Assert.Equal(ElectricApparentEnergyUnit.MegavoltampereHour, quantity01.Unit); var quantity02 = ElectricApparentEnergy.From(1, ElectricApparentEnergyUnit.VoltampereHour); - AssertEx.EqualTolerance(1, quantity02.VoltampereHours, VoltampereHoursTolerance); + Assert.Equal(1, quantity02.VoltampereHours); Assert.Equal(ElectricApparentEnergyUnit.VoltampereHour, quantity02.Unit); } @@ -287,53 +305,28 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [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, decimal expectedValue) { - try - { - var parsed = ElectricApparentEnergy.Parse("1 kVAh", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilovoltampereHours, KilovoltampereHoursTolerance); - Assert.Equal(ElectricApparentEnergyUnit.KilovoltampereHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricApparentEnergy.Parse("1 MVAh", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegavoltampereHours, MegavoltampereHoursTolerance); - Assert.Equal(ElectricApparentEnergyUnit.MegavoltampereHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricApparentEnergy.Parse("1 VAh", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.VoltampereHours, VoltampereHoursTolerance); - Assert.Equal(ElectricApparentEnergyUnit.VoltampereHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ElectricApparentEnergy.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [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, decimal expectedValue) { - { - Assert.True(ElectricApparentEnergy.TryParse("1 kVAh", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilovoltampereHours, KilovoltampereHoursTolerance); - Assert.Equal(ElectricApparentEnergyUnit.KilovoltampereHour, parsed.Unit); - } - - { - Assert.True(ElectricApparentEnergy.TryParse("1 MVAh", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegavoltampereHours, MegavoltampereHoursTolerance); - Assert.Equal(ElectricApparentEnergyUnit.MegavoltampereHour, parsed.Unit); - } - - { - Assert.True(ElectricApparentEnergy.TryParse("1 VAh", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.VoltampereHours, VoltampereHoursTolerance); - Assert.Equal(ElectricApparentEnergyUnit.VoltampereHour, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ElectricApparentEnergy.TryParse(quantityString, out ElectricApparentEnergy parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -426,6 +419,29 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Electr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ElectricApparentEnergyUnit.KilovoltampereHour, "kVAh")] + [InlineData("en-US", ElectricApparentEnergyUnit.MegavoltampereHour, "MVAh")] + [InlineData("en-US", ElectricApparentEnergyUnit.VoltampereHour, "VAh")] + public void GetAbbreviationForCulture(string culture, ElectricApparentEnergyUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ElectricApparentEnergy.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ElectricApparentEnergy.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ElectricApparentEnergy.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricApparentEnergyUnit unit) @@ -456,6 +472,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); }); } @@ -479,34 +496,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] @@ -552,8 +571,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); @@ -591,34 +608,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = ElectricApparentEnergy.FromVoltampereHours(1); - Assert.True(v.Equals(ElectricApparentEnergy.FromVoltampereHours(1), VoltampereHoursTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ElectricApparentEnergy.Zero, VoltampereHoursTolerance, ComparisonType.Relative)); - Assert.True(ElectricApparentEnergy.FromVoltampereHours(100).Equals(ElectricApparentEnergy.FromVoltampereHours(120), 0.3, ComparisonType.Relative)); - Assert.False(ElectricApparentEnergy.FromVoltampereHours(100).Equals(ElectricApparentEnergy.FromVoltampereHours(120), 0.1, ComparisonType.Relative)); + ElectricApparentEnergy voltamperehour = ElectricApparentEnergy.FromVoltampereHours(1); + Assert.False(voltamperehour.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = ElectricApparentEnergy.FromVoltampereHours(1); - Assert.Throws(() => v.Equals(ElectricApparentEnergy.FromVoltampereHours(1), -1, ComparisonType.Relative)); + ElectricApparentEnergy voltamperehour = ElectricApparentEnergy.FromVoltampereHours(1); + Assert.False(voltamperehour.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - ElectricApparentEnergy voltamperehour = ElectricApparentEnergy.FromVoltampereHours(1); - Assert.False(voltamperehour.Equals(new object())); + var quantity = ElectricApparentEnergy.FromVoltampereHours(firstValue); + var otherQuantity = ElectricApparentEnergy.FromVoltampereHours(secondValue); + ElectricApparentEnergy maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - ElectricApparentEnergy voltamperehour = ElectricApparentEnergy.FromVoltampereHours(1); - Assert.False(voltamperehour.Equals(null)); + var quantity = ElectricApparentEnergy.FromVoltampereHours(1); + var negativeTolerance = ElectricApparentEnergy.FromVoltampereHours(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -637,6 +663,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() { @@ -699,158 +737,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ElectricApparentEnergy.FromVoltampereHours(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ElectricApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ElectricApparentEnergy.FromVoltampereHours(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ElectricApparentEnergy.FromVoltampereHours(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ElectricApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ElectricApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ElectricApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ElectricApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ElectricApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ElectricApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ElectricApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ElectricApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ElectricApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ElectricApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ElectricApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ElectricApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ElectricApparentEnergy))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ElectricApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricApparentEnergyUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ElectricApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal(ElectricApparentEnergy.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ElectricApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal(ElectricApparentEnergy.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ElectricApparentEnergy.FromVoltampereHours(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ElectricApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ElectricApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal(new {ElectricApparentEnergy.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 dab5c9ebc7..3cb2179fa5 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricApparentPowerTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricApparentPowerTestsBase.g.cs @@ -116,7 +116,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ElectricApparentPower(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -129,15 +129,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ElectricApparentPower_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ElectricApparentPowerUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ElectricApparentPower(1, ElectricApparentPowerUnit.Voltampere); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ElectricApparentPower.Zero, quantityInfo.Zero); Assert.Equal("ElectricApparentPower", quantityInfo.Name); + Assert.Equal(ElectricApparentPower.Zero, quantityInfo.Zero); + Assert.Equal(ElectricApparentPower.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ElectricApparentPower.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void ElectricApparentPowerInfo_CreateWithCustomUnitInfos() + { + ElectricApparentPowerUnit[] expectedUnits = [ElectricApparentPowerUnit.Voltampere]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -156,27 +174,27 @@ public void VoltampereToElectricApparentPowerUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ElectricApparentPower.From(1, ElectricApparentPowerUnit.Gigavoltampere); - AssertEx.EqualTolerance(1, quantity00.Gigavoltamperes, GigavoltamperesTolerance); + Assert.Equal(1, quantity00.Gigavoltamperes); Assert.Equal(ElectricApparentPowerUnit.Gigavoltampere, quantity00.Unit); var quantity01 = ElectricApparentPower.From(1, ElectricApparentPowerUnit.Kilovoltampere); - AssertEx.EqualTolerance(1, quantity01.Kilovoltamperes, KilovoltamperesTolerance); + Assert.Equal(1, quantity01.Kilovoltamperes); Assert.Equal(ElectricApparentPowerUnit.Kilovoltampere, quantity01.Unit); var quantity02 = ElectricApparentPower.From(1, ElectricApparentPowerUnit.Megavoltampere); - AssertEx.EqualTolerance(1, quantity02.Megavoltamperes, MegavoltamperesTolerance); + Assert.Equal(1, quantity02.Megavoltamperes); Assert.Equal(ElectricApparentPowerUnit.Megavoltampere, quantity02.Unit); var quantity03 = ElectricApparentPower.From(1, ElectricApparentPowerUnit.Microvoltampere); - AssertEx.EqualTolerance(1, quantity03.Microvoltamperes, MicrovoltamperesTolerance); + Assert.Equal(1, quantity03.Microvoltamperes); Assert.Equal(ElectricApparentPowerUnit.Microvoltampere, quantity03.Unit); var quantity04 = ElectricApparentPower.From(1, ElectricApparentPowerUnit.Millivoltampere); - AssertEx.EqualTolerance(1, quantity04.Millivoltamperes, MillivoltamperesTolerance); + Assert.Equal(1, quantity04.Millivoltamperes); Assert.Equal(ElectricApparentPowerUnit.Millivoltampere, quantity04.Unit); var quantity05 = ElectricApparentPower.From(1, ElectricApparentPowerUnit.Voltampere); - AssertEx.EqualTolerance(1, quantity05.Voltamperes, VoltamperesTolerance); + Assert.Equal(1, quantity05.Voltamperes); Assert.Equal(ElectricApparentPowerUnit.Voltampere, quantity05.Unit); } @@ -317,80 +335,34 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 GVA", ElectricApparentPowerUnit.Gigavoltampere, 4.2)] + [InlineData("en-US", "4.2 kVA", ElectricApparentPowerUnit.Kilovoltampere, 4.2)] + [InlineData("en-US", "4.2 MVA", ElectricApparentPowerUnit.Megavoltampere, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = ElectricApparentPower.Parse("1 GVA", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Gigavoltamperes, GigavoltamperesTolerance); - Assert.Equal(ElectricApparentPowerUnit.Gigavoltampere, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricApparentPower.Parse("1 kVA", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilovoltamperes, KilovoltamperesTolerance); - Assert.Equal(ElectricApparentPowerUnit.Kilovoltampere, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricApparentPower.Parse("1 MVA", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megavoltamperes, MegavoltamperesTolerance); - Assert.Equal(ElectricApparentPowerUnit.Megavoltampere, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricApparentPower.Parse("1 µVA", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microvoltamperes, MicrovoltamperesTolerance); - Assert.Equal(ElectricApparentPowerUnit.Microvoltampere, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricApparentPower.Parse("1 mVA", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millivoltamperes, MillivoltamperesTolerance); - Assert.Equal(ElectricApparentPowerUnit.Millivoltampere, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricApparentPower.Parse("1 VA", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Voltamperes, VoltamperesTolerance); - Assert.Equal(ElectricApparentPowerUnit.Voltampere, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ElectricApparentPower.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 GVA", ElectricApparentPowerUnit.Gigavoltampere, 4.2)] + [InlineData("en-US", "4.2 kVA", ElectricApparentPowerUnit.Kilovoltampere, 4.2)] + [InlineData("en-US", "4.2 MVA", ElectricApparentPowerUnit.Megavoltampere, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(ElectricApparentPower.TryParse("1 GVA", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gigavoltamperes, GigavoltamperesTolerance); - Assert.Equal(ElectricApparentPowerUnit.Gigavoltampere, parsed.Unit); - } - - { - Assert.True(ElectricApparentPower.TryParse("1 kVA", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilovoltamperes, KilovoltamperesTolerance); - Assert.Equal(ElectricApparentPowerUnit.Kilovoltampere, parsed.Unit); - } - - { - Assert.True(ElectricApparentPower.TryParse("1 µVA", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microvoltamperes, MicrovoltamperesTolerance); - Assert.Equal(ElectricApparentPowerUnit.Microvoltampere, parsed.Unit); - } - - { - Assert.True(ElectricApparentPower.TryParse("1 VA", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Voltamperes, VoltamperesTolerance); - Assert.Equal(ElectricApparentPowerUnit.Voltampere, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ElectricApparentPower.TryParse(quantityString, out ElectricApparentPower parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -507,6 +479,32 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Electr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ElectricApparentPowerUnit.Gigavoltampere, "GVA")] + [InlineData("en-US", ElectricApparentPowerUnit.Kilovoltampere, "kVA")] + [InlineData("en-US", ElectricApparentPowerUnit.Megavoltampere, "MVA")] + [InlineData("en-US", ElectricApparentPowerUnit.Microvoltampere, "µVA")] + [InlineData("en-US", ElectricApparentPowerUnit.Millivoltampere, "mVA")] + [InlineData("en-US", ElectricApparentPowerUnit.Voltampere, "VA")] + public void GetAbbreviationForCulture(string culture, ElectricApparentPowerUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ElectricApparentPower.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ElectricApparentPower.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ElectricApparentPower.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricApparentPowerUnit unit) @@ -537,6 +535,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); }); } @@ -560,37 +559,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] @@ -636,8 +637,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); @@ -675,34 +674,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = ElectricApparentPower.FromVoltamperes(1); - Assert.True(v.Equals(ElectricApparentPower.FromVoltamperes(1), VoltamperesTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ElectricApparentPower.Zero, VoltamperesTolerance, ComparisonType.Relative)); - Assert.True(ElectricApparentPower.FromVoltamperes(100).Equals(ElectricApparentPower.FromVoltamperes(120), 0.3, ComparisonType.Relative)); - Assert.False(ElectricApparentPower.FromVoltamperes(100).Equals(ElectricApparentPower.FromVoltamperes(120), 0.1, ComparisonType.Relative)); + ElectricApparentPower voltampere = ElectricApparentPower.FromVoltamperes(1); + Assert.False(voltampere.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = ElectricApparentPower.FromVoltamperes(1); - Assert.Throws(() => v.Equals(ElectricApparentPower.FromVoltamperes(1), -1, ComparisonType.Relative)); + ElectricApparentPower voltampere = ElectricApparentPower.FromVoltamperes(1); + Assert.False(voltampere.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - ElectricApparentPower voltampere = ElectricApparentPower.FromVoltamperes(1); - Assert.False(voltampere.Equals(new object())); + var quantity = ElectricApparentPower.FromVoltamperes(firstValue); + var otherQuantity = ElectricApparentPower.FromVoltamperes(secondValue); + ElectricApparentPower maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - ElectricApparentPower voltampere = ElectricApparentPower.FromVoltamperes(1); - Assert.False(voltampere.Equals(null)); + var quantity = ElectricApparentPower.FromVoltamperes(1); + var negativeTolerance = ElectricApparentPower.FromVoltamperes(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -721,6 +729,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() { @@ -789,158 +809,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ElectricApparentPower.FromVoltamperes(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ElectricApparentPower.FromVoltamperes(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ElectricApparentPower.FromVoltamperes(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ElectricApparentPower.FromVoltamperes(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ElectricApparentPower.FromVoltamperes(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ElectricApparentPower.FromVoltamperes(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ElectricApparentPower.FromVoltamperes(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ElectricApparentPower.FromVoltamperes(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ElectricApparentPower.FromVoltamperes(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ElectricApparentPower.FromVoltamperes(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ElectricApparentPower.FromVoltamperes(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ElectricApparentPower.FromVoltamperes(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ElectricApparentPower.FromVoltamperes(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ElectricApparentPower.FromVoltamperes(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ElectricApparentPower.FromVoltamperes(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ElectricApparentPower.FromVoltamperes(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ElectricApparentPower))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ElectricApparentPower.FromVoltamperes(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricApparentPowerUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ElectricApparentPower.FromVoltamperes(1.0); - Assert.Equal(ElectricApparentPower.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ElectricApparentPower.FromVoltamperes(1.0); - Assert.Equal(ElectricApparentPower.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ElectricApparentPower.FromVoltamperes(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ElectricApparentPower.FromVoltamperes(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ElectricApparentPower.FromVoltamperes(1.0); - Assert.Equal(new {ElectricApparentPower.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 8c650179c5..0dd2e82980 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCapacitanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCapacitanceTestsBase.g.cs @@ -120,7 +120,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ElectricCapacitance(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -133,15 +133,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ElectricCapacitance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ElectricCapacitanceUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ElectricCapacitance(1, ElectricCapacitanceUnit.Farad); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ElectricCapacitance.Zero, quantityInfo.Zero); Assert.Equal("ElectricCapacitance", quantityInfo.Name); + Assert.Equal(ElectricCapacitance.Zero, quantityInfo.Zero); + Assert.Equal(ElectricCapacitance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ElectricCapacitance.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void ElectricCapacitanceInfo_CreateWithCustomUnitInfos() + { + ElectricCapacitanceUnit[] expectedUnits = [ElectricCapacitanceUnit.Farad]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -161,31 +179,31 @@ public void FaradToElectricCapacitanceUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ElectricCapacitance.From(1, ElectricCapacitanceUnit.Farad); - AssertEx.EqualTolerance(1, quantity00.Farads, FaradsTolerance); + Assert.Equal(1, quantity00.Farads); Assert.Equal(ElectricCapacitanceUnit.Farad, quantity00.Unit); var quantity01 = ElectricCapacitance.From(1, ElectricCapacitanceUnit.Kilofarad); - AssertEx.EqualTolerance(1, quantity01.Kilofarads, KilofaradsTolerance); + Assert.Equal(1, quantity01.Kilofarads); Assert.Equal(ElectricCapacitanceUnit.Kilofarad, quantity01.Unit); var quantity02 = ElectricCapacitance.From(1, ElectricCapacitanceUnit.Megafarad); - AssertEx.EqualTolerance(1, quantity02.Megafarads, MegafaradsTolerance); + Assert.Equal(1, quantity02.Megafarads); Assert.Equal(ElectricCapacitanceUnit.Megafarad, quantity02.Unit); var quantity03 = ElectricCapacitance.From(1, ElectricCapacitanceUnit.Microfarad); - AssertEx.EqualTolerance(1, quantity03.Microfarads, MicrofaradsTolerance); + Assert.Equal(1, quantity03.Microfarads); Assert.Equal(ElectricCapacitanceUnit.Microfarad, quantity03.Unit); var quantity04 = ElectricCapacitance.From(1, ElectricCapacitanceUnit.Millifarad); - AssertEx.EqualTolerance(1, quantity04.Millifarads, MillifaradsTolerance); + Assert.Equal(1, quantity04.Millifarads); Assert.Equal(ElectricCapacitanceUnit.Millifarad, quantity04.Unit); var quantity05 = ElectricCapacitance.From(1, ElectricCapacitanceUnit.Nanofarad); - AssertEx.EqualTolerance(1, quantity05.Nanofarads, NanofaradsTolerance); + Assert.Equal(1, quantity05.Nanofarads); Assert.Equal(ElectricCapacitanceUnit.Nanofarad, quantity05.Unit); var quantity06 = ElectricCapacitance.From(1, ElectricCapacitanceUnit.Picofarad); - AssertEx.EqualTolerance(1, quantity06.Picofarads, PicofaradsTolerance); + Assert.Equal(1, quantity06.Picofarads); Assert.Equal(ElectricCapacitanceUnit.Picofarad, quantity06.Unit); } @@ -327,93 +345,36 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 F", ElectricCapacitanceUnit.Farad, 4.2)] + [InlineData("en-US", "4.2 kF", ElectricCapacitanceUnit.Kilofarad, 4.2)] + [InlineData("en-US", "4.2 MF", ElectricCapacitanceUnit.Megafarad, 4.2)] + [InlineData("en-US", "4.2 µF", ElectricCapacitanceUnit.Microfarad, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = ElectricCapacitance.Parse("1 F", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Farads, FaradsTolerance); - Assert.Equal(ElectricCapacitanceUnit.Farad, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCapacitance.Parse("1 kF", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilofarads, KilofaradsTolerance); - Assert.Equal(ElectricCapacitanceUnit.Kilofarad, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCapacitance.Parse("1 MF", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megafarads, MegafaradsTolerance); - Assert.Equal(ElectricCapacitanceUnit.Megafarad, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCapacitance.Parse("1 µF", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microfarads, MicrofaradsTolerance); - Assert.Equal(ElectricCapacitanceUnit.Microfarad, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCapacitance.Parse("1 mF", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millifarads, MillifaradsTolerance); - Assert.Equal(ElectricCapacitanceUnit.Millifarad, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCapacitance.Parse("1 nF", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanofarads, NanofaradsTolerance); - Assert.Equal(ElectricCapacitanceUnit.Nanofarad, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCapacitance.Parse("1 pF", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Picofarads, PicofaradsTolerance); - Assert.Equal(ElectricCapacitanceUnit.Picofarad, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ElectricCapacitance.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 F", ElectricCapacitanceUnit.Farad, 4.2)] + [InlineData("en-US", "4.2 kF", ElectricCapacitanceUnit.Kilofarad, 4.2)] + [InlineData("en-US", "4.2 MF", ElectricCapacitanceUnit.Megafarad, 4.2)] + [InlineData("en-US", "4.2 µF", ElectricCapacitanceUnit.Microfarad, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(ElectricCapacitance.TryParse("1 F", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Farads, FaradsTolerance); - Assert.Equal(ElectricCapacitanceUnit.Farad, parsed.Unit); - } - - { - Assert.True(ElectricCapacitance.TryParse("1 kF", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilofarads, KilofaradsTolerance); - Assert.Equal(ElectricCapacitanceUnit.Kilofarad, parsed.Unit); - } - - { - Assert.True(ElectricCapacitance.TryParse("1 µF", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microfarads, MicrofaradsTolerance); - Assert.Equal(ElectricCapacitanceUnit.Microfarad, parsed.Unit); - } - - { - Assert.True(ElectricCapacitance.TryParse("1 nF", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanofarads, NanofaradsTolerance); - Assert.Equal(ElectricCapacitanceUnit.Nanofarad, parsed.Unit); - } - - { - Assert.True(ElectricCapacitance.TryParse("1 pF", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Picofarads, PicofaradsTolerance); - Assert.Equal(ElectricCapacitanceUnit.Picofarad, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ElectricCapacitance.TryParse(quantityString, out ElectricCapacitance parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -538,6 +499,33 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Electr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ElectricCapacitanceUnit.Farad, "F")] + [InlineData("en-US", ElectricCapacitanceUnit.Kilofarad, "kF")] + [InlineData("en-US", ElectricCapacitanceUnit.Megafarad, "MF")] + [InlineData("en-US", ElectricCapacitanceUnit.Microfarad, "µF")] + [InlineData("en-US", ElectricCapacitanceUnit.Millifarad, "mF")] + [InlineData("en-US", ElectricCapacitanceUnit.Nanofarad, "nF")] + [InlineData("en-US", ElectricCapacitanceUnit.Picofarad, "pF")] + public void GetAbbreviationForCulture(string culture, ElectricCapacitanceUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ElectricCapacitance.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ElectricCapacitance.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ElectricCapacitance.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricCapacitanceUnit unit) @@ -568,6 +556,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); }); } @@ -591,38 +580,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] @@ -668,8 +659,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); @@ -707,34 +696,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = ElectricCapacitance.FromFarads(1); - Assert.True(v.Equals(ElectricCapacitance.FromFarads(1), FaradsTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ElectricCapacitance.Zero, FaradsTolerance, ComparisonType.Relative)); - Assert.True(ElectricCapacitance.FromFarads(100).Equals(ElectricCapacitance.FromFarads(120), 0.3, ComparisonType.Relative)); - Assert.False(ElectricCapacitance.FromFarads(100).Equals(ElectricCapacitance.FromFarads(120), 0.1, ComparisonType.Relative)); + ElectricCapacitance farad = ElectricCapacitance.FromFarads(1); + Assert.False(farad.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = ElectricCapacitance.FromFarads(1); - Assert.Throws(() => v.Equals(ElectricCapacitance.FromFarads(1), -1, ComparisonType.Relative)); + ElectricCapacitance farad = ElectricCapacitance.FromFarads(1); + Assert.False(farad.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - ElectricCapacitance farad = ElectricCapacitance.FromFarads(1); - Assert.False(farad.Equals(new object())); + var quantity = ElectricCapacitance.FromFarads(firstValue); + var otherQuantity = ElectricCapacitance.FromFarads(secondValue); + ElectricCapacitance maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - ElectricCapacitance farad = ElectricCapacitance.FromFarads(1); - Assert.False(farad.Equals(null)); + var quantity = ElectricCapacitance.FromFarads(1); + var negativeTolerance = ElectricCapacitance.FromFarads(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -753,6 +751,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() { @@ -823,158 +833,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ElectricCapacitance.FromFarads(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ElectricCapacitance.FromFarads(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ElectricCapacitance.FromFarads(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ElectricCapacitance.FromFarads(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ElectricCapacitance.FromFarads(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ElectricCapacitance.FromFarads(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ElectricCapacitance.FromFarads(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ElectricCapacitance.FromFarads(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ElectricCapacitance.FromFarads(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ElectricCapacitance.FromFarads(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ElectricCapacitance.FromFarads(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ElectricCapacitance.FromFarads(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ElectricCapacitance.FromFarads(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ElectricCapacitance.FromFarads(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ElectricCapacitance.FromFarads(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ElectricCapacitance.FromFarads(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ElectricCapacitance))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ElectricCapacitance.FromFarads(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricCapacitanceUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ElectricCapacitance.FromFarads(1.0); - Assert.Equal(ElectricCapacitance.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ElectricCapacitance.FromFarads(1.0); - Assert.Equal(ElectricCapacitance.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ElectricCapacitance.FromFarads(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ElectricCapacitance.FromFarads(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ElectricCapacitance.FromFarads(1.0); - Assert.Equal(new {ElectricCapacitance.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 a821d4445d..14abe4c8c0 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeDensityTestsBase.g.cs @@ -96,7 +96,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ElectricChargeDensity(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -109,15 +109,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ElectricChargeDensity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ElectricChargeDensityUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ElectricChargeDensity(1, ElectricChargeDensityUnit.CoulombPerCubicMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ElectricChargeDensity.Zero, quantityInfo.Zero); Assert.Equal("ElectricChargeDensity", quantityInfo.Name); + Assert.Equal(ElectricChargeDensity.Zero, quantityInfo.Zero); + Assert.Equal(ElectricChargeDensity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ElectricChargeDensity.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -131,7 +149,7 @@ public void CoulombPerCubicMeterToElectricChargeDensityUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ElectricChargeDensity.From(1, ElectricChargeDensityUnit.CoulombPerCubicMeter); - AssertEx.EqualTolerance(1, quantity00.CoulombsPerCubicMeter, CoulombsPerCubicMeterTolerance); + Assert.Equal(1, quantity00.CoulombsPerCubicMeter); Assert.Equal(ElectricChargeDensityUnit.CoulombPerCubicMeter, quantity00.Unit); } @@ -267,27 +285,24 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 C/m³", ElectricChargeDensityUnit.CoulombPerCubicMeter, 4.2)] + public void Parse(string culture, string quantityString, ElectricChargeDensityUnit expectedUnit, decimal expectedValue) { - try - { - var parsed = ElectricChargeDensity.Parse("1 C/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CoulombsPerCubicMeter, CoulombsPerCubicMeterTolerance); - Assert.Equal(ElectricChargeDensityUnit.CoulombPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ElectricChargeDensity.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 C/m³", ElectricChargeDensityUnit.CoulombPerCubicMeter, 4.2)] + public void TryParse(string culture, string quantityString, ElectricChargeDensityUnit expectedUnit, decimal expectedValue) { - { - Assert.True(ElectricChargeDensity.TryParse("1 C/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CoulombsPerCubicMeter, CoulombsPerCubicMeterTolerance); - Assert.Equal(ElectricChargeDensityUnit.CoulombPerCubicMeter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ElectricChargeDensity.TryParse(quantityString, out ElectricChargeDensity parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -364,6 +379,27 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Electr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ElectricChargeDensityUnit.CoulombPerCubicMeter, "C/m³")] + public void GetAbbreviationForCulture(string culture, ElectricChargeDensityUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ElectricChargeDensity.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ElectricChargeDensity.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ElectricChargeDensity.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricChargeDensityUnit unit) @@ -394,6 +430,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); }); } @@ -417,32 +454,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] @@ -488,7 +527,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); @@ -526,34 +564,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = ElectricChargeDensity.FromCoulombsPerCubicMeter(1); - Assert.True(v.Equals(ElectricChargeDensity.FromCoulombsPerCubicMeter(1), CoulombsPerCubicMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ElectricChargeDensity.Zero, CoulombsPerCubicMeterTolerance, ComparisonType.Relative)); - Assert.True(ElectricChargeDensity.FromCoulombsPerCubicMeter(100).Equals(ElectricChargeDensity.FromCoulombsPerCubicMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(ElectricChargeDensity.FromCoulombsPerCubicMeter(100).Equals(ElectricChargeDensity.FromCoulombsPerCubicMeter(120), 0.1, ComparisonType.Relative)); + ElectricChargeDensity coulombpercubicmeter = ElectricChargeDensity.FromCoulombsPerCubicMeter(1); + Assert.False(coulombpercubicmeter.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = ElectricChargeDensity.FromCoulombsPerCubicMeter(1); - Assert.Throws(() => v.Equals(ElectricChargeDensity.FromCoulombsPerCubicMeter(1), -1, ComparisonType.Relative)); + ElectricChargeDensity coulombpercubicmeter = ElectricChargeDensity.FromCoulombsPerCubicMeter(1); + Assert.False(coulombpercubicmeter.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - ElectricChargeDensity coulombpercubicmeter = ElectricChargeDensity.FromCoulombsPerCubicMeter(1); - Assert.False(coulombpercubicmeter.Equals(new object())); + var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(firstValue); + var otherQuantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(secondValue); + ElectricChargeDensity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - ElectricChargeDensity coulombpercubicmeter = ElectricChargeDensity.FromCoulombsPerCubicMeter(1); - Assert.False(coulombpercubicmeter.Equals(null)); + var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1); + var negativeTolerance = ElectricChargeDensity.FromCoulombsPerCubicMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -572,6 +619,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() { @@ -630,158 +689,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ElectricChargeDensity))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricChargeDensityUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal(ElectricChargeDensity.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal(ElectricChargeDensity.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal(new {ElectricChargeDensity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 1d98fc8612..91f81b168b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeTestsBase.g.cs @@ -136,7 +136,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ElectricCharge(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -149,15 +149,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ElectricCharge_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ElectricChargeUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ElectricCharge(1, ElectricChargeUnit.Coulomb); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ElectricCharge.Zero, quantityInfo.Zero); Assert.Equal("ElectricCharge", quantityInfo.Name); + Assert.Equal(ElectricCharge.Zero, quantityInfo.Zero); + Assert.Equal(ElectricCharge.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ElectricCharge.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -181,47 +199,47 @@ public void CoulombToElectricChargeUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ElectricCharge.From(1, ElectricChargeUnit.AmpereHour); - AssertEx.EqualTolerance(1, quantity00.AmpereHours, AmpereHoursTolerance); + Assert.Equal(1, quantity00.AmpereHours); Assert.Equal(ElectricChargeUnit.AmpereHour, quantity00.Unit); var quantity01 = ElectricCharge.From(1, ElectricChargeUnit.Coulomb); - AssertEx.EqualTolerance(1, quantity01.Coulombs, CoulombsTolerance); + Assert.Equal(1, quantity01.Coulombs); Assert.Equal(ElectricChargeUnit.Coulomb, quantity01.Unit); var quantity02 = ElectricCharge.From(1, ElectricChargeUnit.KiloampereHour); - AssertEx.EqualTolerance(1, quantity02.KiloampereHours, KiloampereHoursTolerance); + Assert.Equal(1, quantity02.KiloampereHours); Assert.Equal(ElectricChargeUnit.KiloampereHour, quantity02.Unit); var quantity03 = ElectricCharge.From(1, ElectricChargeUnit.Kilocoulomb); - AssertEx.EqualTolerance(1, quantity03.Kilocoulombs, KilocoulombsTolerance); + Assert.Equal(1, quantity03.Kilocoulombs); Assert.Equal(ElectricChargeUnit.Kilocoulomb, quantity03.Unit); var quantity04 = ElectricCharge.From(1, ElectricChargeUnit.MegaampereHour); - AssertEx.EqualTolerance(1, quantity04.MegaampereHours, MegaampereHoursTolerance); + Assert.Equal(1, quantity04.MegaampereHours); Assert.Equal(ElectricChargeUnit.MegaampereHour, quantity04.Unit); var quantity05 = ElectricCharge.From(1, ElectricChargeUnit.Megacoulomb); - AssertEx.EqualTolerance(1, quantity05.Megacoulombs, MegacoulombsTolerance); + Assert.Equal(1, quantity05.Megacoulombs); Assert.Equal(ElectricChargeUnit.Megacoulomb, quantity05.Unit); var quantity06 = ElectricCharge.From(1, ElectricChargeUnit.Microcoulomb); - AssertEx.EqualTolerance(1, quantity06.Microcoulombs, MicrocoulombsTolerance); + Assert.Equal(1, quantity06.Microcoulombs); Assert.Equal(ElectricChargeUnit.Microcoulomb, quantity06.Unit); var quantity07 = ElectricCharge.From(1, ElectricChargeUnit.MilliampereHour); - AssertEx.EqualTolerance(1, quantity07.MilliampereHours, MilliampereHoursTolerance); + Assert.Equal(1, quantity07.MilliampereHours); Assert.Equal(ElectricChargeUnit.MilliampereHour, quantity07.Unit); var quantity08 = ElectricCharge.From(1, ElectricChargeUnit.Millicoulomb); - AssertEx.EqualTolerance(1, quantity08.Millicoulombs, MillicoulombsTolerance); + Assert.Equal(1, quantity08.Millicoulombs); Assert.Equal(ElectricChargeUnit.Millicoulomb, quantity08.Unit); var quantity09 = ElectricCharge.From(1, ElectricChargeUnit.Nanocoulomb); - AssertEx.EqualTolerance(1, quantity09.Nanocoulombs, NanocoulombsTolerance); + Assert.Equal(1, quantity09.Nanocoulombs); Assert.Equal(ElectricChargeUnit.Nanocoulomb, quantity09.Unit); var quantity10 = ElectricCharge.From(1, ElectricChargeUnit.Picocoulomb); - AssertEx.EqualTolerance(1, quantity10.Picocoulombs, PicocoulombsTolerance); + Assert.Equal(1, quantity10.Picocoulombs); Assert.Equal(ElectricChargeUnit.Picocoulomb, quantity10.Unit); } @@ -367,173 +385,52 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 A-h", ElectricChargeUnit.AmpereHour, 4.2)] + [InlineData("en-US", "4.2 Ah", ElectricChargeUnit.AmpereHour, 4.2)] + [InlineData("en-US", "4.2 C", ElectricChargeUnit.Coulomb, 4.2)] + [InlineData("en-US", "4.2 kA-h", ElectricChargeUnit.KiloampereHour, 4.2)] + [InlineData("en-US", "4.2 kAh", ElectricChargeUnit.KiloampereHour, 4.2)] + [InlineData("en-US", "4.2 kC", ElectricChargeUnit.Kilocoulomb, 4.2)] + [InlineData("en-US", "4.2 MA-h", ElectricChargeUnit.MegaampereHour, 4.2)] + [InlineData("en-US", "4.2 MAh", ElectricChargeUnit.MegaampereHour, 4.2)] + [InlineData("en-US", "4.2 MC", ElectricChargeUnit.Megacoulomb, 4.2)] + [InlineData("en-US", "4.2 µC", ElectricChargeUnit.Microcoulomb, 4.2)] + [InlineData("en-US", "4.2 mA-h", ElectricChargeUnit.MilliampereHour, 4.2)] + [InlineData("en-US", "4.2 mAh", ElectricChargeUnit.MilliampereHour, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = ElectricCharge.Parse("1 A-h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.AmpereHours, AmpereHoursTolerance); - Assert.Equal(ElectricChargeUnit.AmpereHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCharge.Parse("1 Ah", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.AmpereHours, AmpereHoursTolerance); - Assert.Equal(ElectricChargeUnit.AmpereHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCharge.Parse("1 C", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Coulombs, CoulombsTolerance); - Assert.Equal(ElectricChargeUnit.Coulomb, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCharge.Parse("1 kA-h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KiloampereHours, KiloampereHoursTolerance); - Assert.Equal(ElectricChargeUnit.KiloampereHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCharge.Parse("1 kAh", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KiloampereHours, KiloampereHoursTolerance); - Assert.Equal(ElectricChargeUnit.KiloampereHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCharge.Parse("1 kC", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilocoulombs, KilocoulombsTolerance); - Assert.Equal(ElectricChargeUnit.Kilocoulomb, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCharge.Parse("1 MA-h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegaampereHours, MegaampereHoursTolerance); - Assert.Equal(ElectricChargeUnit.MegaampereHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCharge.Parse("1 MAh", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegaampereHours, MegaampereHoursTolerance); - Assert.Equal(ElectricChargeUnit.MegaampereHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCharge.Parse("1 MC", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megacoulombs, MegacoulombsTolerance); - Assert.Equal(ElectricChargeUnit.Megacoulomb, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCharge.Parse("1 µC", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microcoulombs, MicrocoulombsTolerance); - Assert.Equal(ElectricChargeUnit.Microcoulomb, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCharge.Parse("1 mA-h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilliampereHours, MilliampereHoursTolerance); - Assert.Equal(ElectricChargeUnit.MilliampereHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCharge.Parse("1 mAh", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilliampereHours, MilliampereHoursTolerance); - Assert.Equal(ElectricChargeUnit.MilliampereHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCharge.Parse("1 mC", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millicoulombs, MillicoulombsTolerance); - Assert.Equal(ElectricChargeUnit.Millicoulomb, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCharge.Parse("1 nC", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanocoulombs, NanocoulombsTolerance); - Assert.Equal(ElectricChargeUnit.Nanocoulomb, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCharge.Parse("1 pC", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Picocoulombs, PicocoulombsTolerance); - Assert.Equal(ElectricChargeUnit.Picocoulomb, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ElectricCharge.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 A-h", ElectricChargeUnit.AmpereHour, 4.2)] + [InlineData("en-US", "4.2 Ah", ElectricChargeUnit.AmpereHour, 4.2)] + [InlineData("en-US", "4.2 C", ElectricChargeUnit.Coulomb, 4.2)] + [InlineData("en-US", "4.2 kA-h", ElectricChargeUnit.KiloampereHour, 4.2)] + [InlineData("en-US", "4.2 kAh", ElectricChargeUnit.KiloampereHour, 4.2)] + [InlineData("en-US", "4.2 kC", ElectricChargeUnit.Kilocoulomb, 4.2)] + [InlineData("en-US", "4.2 MA-h", ElectricChargeUnit.MegaampereHour, 4.2)] + [InlineData("en-US", "4.2 MAh", ElectricChargeUnit.MegaampereHour, 4.2)] + [InlineData("en-US", "4.2 MC", ElectricChargeUnit.Megacoulomb, 4.2)] + [InlineData("en-US", "4.2 µC", ElectricChargeUnit.Microcoulomb, 4.2)] + [InlineData("en-US", "4.2 mA-h", ElectricChargeUnit.MilliampereHour, 4.2)] + [InlineData("en-US", "4.2 mAh", ElectricChargeUnit.MilliampereHour, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(ElectricCharge.TryParse("1 A-h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.AmpereHours, AmpereHoursTolerance); - Assert.Equal(ElectricChargeUnit.AmpereHour, parsed.Unit); - } - - { - Assert.True(ElectricCharge.TryParse("1 Ah", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.AmpereHours, AmpereHoursTolerance); - Assert.Equal(ElectricChargeUnit.AmpereHour, parsed.Unit); - } - - { - Assert.True(ElectricCharge.TryParse("1 C", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Coulombs, CoulombsTolerance); - Assert.Equal(ElectricChargeUnit.Coulomb, parsed.Unit); - } - - { - Assert.True(ElectricCharge.TryParse("1 kA-h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KiloampereHours, KiloampereHoursTolerance); - Assert.Equal(ElectricChargeUnit.KiloampereHour, parsed.Unit); - } - - { - Assert.True(ElectricCharge.TryParse("1 kAh", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KiloampereHours, KiloampereHoursTolerance); - Assert.Equal(ElectricChargeUnit.KiloampereHour, parsed.Unit); - } - - { - Assert.True(ElectricCharge.TryParse("1 kC", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilocoulombs, KilocoulombsTolerance); - Assert.Equal(ElectricChargeUnit.Kilocoulomb, parsed.Unit); - } - - { - Assert.True(ElectricCharge.TryParse("1 µC", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microcoulombs, MicrocoulombsTolerance); - Assert.Equal(ElectricChargeUnit.Microcoulomb, parsed.Unit); - } - - { - Assert.True(ElectricCharge.TryParse("1 nC", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanocoulombs, NanocoulombsTolerance); - Assert.Equal(ElectricChargeUnit.Nanocoulomb, parsed.Unit); - } - - { - Assert.True(ElectricCharge.TryParse("1 pC", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Picocoulombs, PicocoulombsTolerance); - Assert.Equal(ElectricChargeUnit.Picocoulomb, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ElectricCharge.TryParse(quantityString, out ElectricCharge parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -722,6 +619,37 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Electr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ElectricChargeUnit.AmpereHour, "A-h")] + [InlineData("en-US", ElectricChargeUnit.Coulomb, "C")] + [InlineData("en-US", ElectricChargeUnit.KiloampereHour, "kA-h")] + [InlineData("en-US", ElectricChargeUnit.Kilocoulomb, "kC")] + [InlineData("en-US", ElectricChargeUnit.MegaampereHour, "MA-h")] + [InlineData("en-US", ElectricChargeUnit.Megacoulomb, "MC")] + [InlineData("en-US", ElectricChargeUnit.Microcoulomb, "µC")] + [InlineData("en-US", ElectricChargeUnit.MilliampereHour, "mA-h")] + [InlineData("en-US", ElectricChargeUnit.Millicoulomb, "mC")] + [InlineData("en-US", ElectricChargeUnit.Nanocoulomb, "nC")] + [InlineData("en-US", ElectricChargeUnit.Picocoulomb, "pC")] + public void GetAbbreviationForCulture(string culture, ElectricChargeUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ElectricCharge.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ElectricCharge.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ElectricCharge.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricChargeUnit unit) @@ -752,6 +680,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); }); } @@ -775,42 +704,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] @@ -856,8 +787,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); @@ -895,34 +824,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = ElectricCharge.FromCoulombs(1); - Assert.True(v.Equals(ElectricCharge.FromCoulombs(1), CoulombsTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ElectricCharge.Zero, CoulombsTolerance, ComparisonType.Relative)); - Assert.True(ElectricCharge.FromCoulombs(100).Equals(ElectricCharge.FromCoulombs(120), 0.3, ComparisonType.Relative)); - Assert.False(ElectricCharge.FromCoulombs(100).Equals(ElectricCharge.FromCoulombs(120), 0.1, ComparisonType.Relative)); + ElectricCharge coulomb = ElectricCharge.FromCoulombs(1); + Assert.False(coulomb.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = ElectricCharge.FromCoulombs(1); - Assert.Throws(() => v.Equals(ElectricCharge.FromCoulombs(1), -1, ComparisonType.Relative)); + ElectricCharge coulomb = ElectricCharge.FromCoulombs(1); + Assert.False(coulomb.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - ElectricCharge coulomb = ElectricCharge.FromCoulombs(1); - Assert.False(coulomb.Equals(new object())); + var quantity = ElectricCharge.FromCoulombs(firstValue); + var otherQuantity = ElectricCharge.FromCoulombs(secondValue); + ElectricCharge maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - ElectricCharge coulomb = ElectricCharge.FromCoulombs(1); - Assert.False(coulomb.Equals(null)); + var quantity = ElectricCharge.FromCoulombs(1); + var negativeTolerance = ElectricCharge.FromCoulombs(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -941,6 +879,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() { @@ -1019,158 +969,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ElectricCharge))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricChargeUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal(ElectricCharge.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal(ElectricCharge.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal(new {ElectricCharge.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 74d4dfea63..5887d73cf2 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductanceTestsBase.g.cs @@ -156,7 +156,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ElectricConductance(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -169,15 +169,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ElectricConductance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ElectricConductanceUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ElectricConductance(1, ElectricConductanceUnit.Siemens); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ElectricConductance.Zero, quantityInfo.Zero); Assert.Equal("ElectricConductance", quantityInfo.Name); + Assert.Equal(ElectricConductance.Zero, quantityInfo.Zero); + Assert.Equal(ElectricConductance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ElectricConductance.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -206,67 +224,67 @@ public void SiemensToElectricConductanceUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ElectricConductance.From(1, ElectricConductanceUnit.Gigamho); - AssertEx.EqualTolerance(1, quantity00.Gigamhos, GigamhosTolerance); + Assert.Equal(1, quantity00.Gigamhos); Assert.Equal(ElectricConductanceUnit.Gigamho, quantity00.Unit); var quantity01 = ElectricConductance.From(1, ElectricConductanceUnit.Gigasiemens); - AssertEx.EqualTolerance(1, quantity01.Gigasiemens, GigasiemensTolerance); + Assert.Equal(1, quantity01.Gigasiemens); Assert.Equal(ElectricConductanceUnit.Gigasiemens, quantity01.Unit); var quantity02 = ElectricConductance.From(1, ElectricConductanceUnit.Kilomho); - AssertEx.EqualTolerance(1, quantity02.Kilomhos, KilomhosTolerance); + Assert.Equal(1, quantity02.Kilomhos); Assert.Equal(ElectricConductanceUnit.Kilomho, quantity02.Unit); var quantity03 = ElectricConductance.From(1, ElectricConductanceUnit.Kilosiemens); - AssertEx.EqualTolerance(1, quantity03.Kilosiemens, KilosiemensTolerance); + Assert.Equal(1, quantity03.Kilosiemens); Assert.Equal(ElectricConductanceUnit.Kilosiemens, quantity03.Unit); var quantity04 = ElectricConductance.From(1, ElectricConductanceUnit.Megamho); - AssertEx.EqualTolerance(1, quantity04.Megamhos, MegamhosTolerance); + Assert.Equal(1, quantity04.Megamhos); Assert.Equal(ElectricConductanceUnit.Megamho, quantity04.Unit); var quantity05 = ElectricConductance.From(1, ElectricConductanceUnit.Megasiemens); - AssertEx.EqualTolerance(1, quantity05.Megasiemens, MegasiemensTolerance); + Assert.Equal(1, quantity05.Megasiemens); Assert.Equal(ElectricConductanceUnit.Megasiemens, quantity05.Unit); var quantity06 = ElectricConductance.From(1, ElectricConductanceUnit.Mho); - AssertEx.EqualTolerance(1, quantity06.Mhos, MhosTolerance); + Assert.Equal(1, quantity06.Mhos); Assert.Equal(ElectricConductanceUnit.Mho, quantity06.Unit); var quantity07 = ElectricConductance.From(1, ElectricConductanceUnit.Micromho); - AssertEx.EqualTolerance(1, quantity07.Micromhos, MicromhosTolerance); + Assert.Equal(1, quantity07.Micromhos); Assert.Equal(ElectricConductanceUnit.Micromho, quantity07.Unit); var quantity08 = ElectricConductance.From(1, ElectricConductanceUnit.Microsiemens); - AssertEx.EqualTolerance(1, quantity08.Microsiemens, MicrosiemensTolerance); + Assert.Equal(1, quantity08.Microsiemens); Assert.Equal(ElectricConductanceUnit.Microsiemens, quantity08.Unit); var quantity09 = ElectricConductance.From(1, ElectricConductanceUnit.Millimho); - AssertEx.EqualTolerance(1, quantity09.Millimhos, MillimhosTolerance); + Assert.Equal(1, quantity09.Millimhos); Assert.Equal(ElectricConductanceUnit.Millimho, quantity09.Unit); var quantity10 = ElectricConductance.From(1, ElectricConductanceUnit.Millisiemens); - AssertEx.EqualTolerance(1, quantity10.Millisiemens, MillisiemensTolerance); + Assert.Equal(1, quantity10.Millisiemens); Assert.Equal(ElectricConductanceUnit.Millisiemens, quantity10.Unit); var quantity11 = ElectricConductance.From(1, ElectricConductanceUnit.Nanomho); - AssertEx.EqualTolerance(1, quantity11.Nanomhos, NanomhosTolerance); + Assert.Equal(1, quantity11.Nanomhos); Assert.Equal(ElectricConductanceUnit.Nanomho, quantity11.Unit); var quantity12 = ElectricConductance.From(1, ElectricConductanceUnit.Nanosiemens); - AssertEx.EqualTolerance(1, quantity12.Nanosiemens, NanosiemensTolerance); + Assert.Equal(1, quantity12.Nanosiemens); Assert.Equal(ElectricConductanceUnit.Nanosiemens, quantity12.Unit); var quantity13 = ElectricConductance.From(1, ElectricConductanceUnit.Siemens); - AssertEx.EqualTolerance(1, quantity13.Siemens, SiemensTolerance); + Assert.Equal(1, quantity13.Siemens); Assert.Equal(ElectricConductanceUnit.Siemens, quantity13.Unit); var quantity14 = ElectricConductance.From(1, ElectricConductanceUnit.Teramho); - AssertEx.EqualTolerance(1, quantity14.Teramhos, TeramhosTolerance); + Assert.Equal(1, quantity14.Teramhos); Assert.Equal(ElectricConductanceUnit.Teramho, quantity14.Unit); var quantity15 = ElectricConductance.From(1, ElectricConductanceUnit.Terasiemens); - AssertEx.EqualTolerance(1, quantity15.Terasiemens, TerasiemensTolerance); + Assert.Equal(1, quantity15.Terasiemens); Assert.Equal(ElectricConductanceUnit.Terasiemens, quantity15.Unit); } @@ -417,198 +435,54 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 G℧", ElectricConductanceUnit.Gigamho, 4.2)] + [InlineData("en-US", "4.2 GS", ElectricConductanceUnit.Gigasiemens, 4.2)] + [InlineData("en-US", "4.2 k℧", ElectricConductanceUnit.Kilomho, 4.2)] + [InlineData("en-US", "4.2 kS", ElectricConductanceUnit.Kilosiemens, 4.2)] + [InlineData("en-US", "4.2 M℧", ElectricConductanceUnit.Megamho, 4.2)] + [InlineData("en-US", "4.2 MS", ElectricConductanceUnit.Megasiemens, 4.2)] + [InlineData("en-US", "4.2 ℧", ElectricConductanceUnit.Mho, 4.2)] + [InlineData("en-US", "4.2 µ℧", ElectricConductanceUnit.Micromho, 4.2)] + [InlineData("en-US", "4.2 µS", ElectricConductanceUnit.Microsiemens, 4.2)] + [InlineData("en-US", "4.2 m℧", ElectricConductanceUnit.Millimho, 4.2)] + [InlineData("en-US", "4.2 mS", ElectricConductanceUnit.Millisiemens, 4.2)] + [InlineData("en-US", "4.2 n℧", ElectricConductanceUnit.Nanomho, 4.2)] + [InlineData("en-US", "4.2 nS", ElectricConductanceUnit.Nanosiemens, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = ElectricConductance.Parse("1 G℧", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Gigamhos, GigamhosTolerance); - Assert.Equal(ElectricConductanceUnit.Gigamho, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricConductance.Parse("1 GS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Gigasiemens, GigasiemensTolerance); - Assert.Equal(ElectricConductanceUnit.Gigasiemens, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricConductance.Parse("1 k℧", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilomhos, KilomhosTolerance); - Assert.Equal(ElectricConductanceUnit.Kilomho, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricConductance.Parse("1 kS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilosiemens, KilosiemensTolerance); - Assert.Equal(ElectricConductanceUnit.Kilosiemens, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricConductance.Parse("1 M℧", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megamhos, MegamhosTolerance); - Assert.Equal(ElectricConductanceUnit.Megamho, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricConductance.Parse("1 MS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megasiemens, MegasiemensTolerance); - Assert.Equal(ElectricConductanceUnit.Megasiemens, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricConductance.Parse("1 ℧", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Mhos, MhosTolerance); - Assert.Equal(ElectricConductanceUnit.Mho, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricConductance.Parse("1 µ℧", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Micromhos, MicromhosTolerance); - Assert.Equal(ElectricConductanceUnit.Micromho, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricConductance.Parse("1 µS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microsiemens, MicrosiemensTolerance); - Assert.Equal(ElectricConductanceUnit.Microsiemens, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricConductance.Parse("1 m℧", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millimhos, MillimhosTolerance); - Assert.Equal(ElectricConductanceUnit.Millimho, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricConductance.Parse("1 mS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millisiemens, MillisiemensTolerance); - Assert.Equal(ElectricConductanceUnit.Millisiemens, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricConductance.Parse("1 n℧", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanomhos, NanomhosTolerance); - Assert.Equal(ElectricConductanceUnit.Nanomho, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricConductance.Parse("1 nS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanosiemens, NanosiemensTolerance); - Assert.Equal(ElectricConductanceUnit.Nanosiemens, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricConductance.Parse("1 S", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Siemens, SiemensTolerance); - Assert.Equal(ElectricConductanceUnit.Siemens, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricConductance.Parse("1 T℧", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Teramhos, TeramhosTolerance); - Assert.Equal(ElectricConductanceUnit.Teramho, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricConductance.Parse("1 TS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Terasiemens, TerasiemensTolerance); - Assert.Equal(ElectricConductanceUnit.Terasiemens, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ElectricConductance.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 G℧", ElectricConductanceUnit.Gigamho, 4.2)] + [InlineData("en-US", "4.2 GS", ElectricConductanceUnit.Gigasiemens, 4.2)] + [InlineData("en-US", "4.2 k℧", ElectricConductanceUnit.Kilomho, 4.2)] + [InlineData("en-US", "4.2 kS", ElectricConductanceUnit.Kilosiemens, 4.2)] + [InlineData("en-US", "4.2 M℧", ElectricConductanceUnit.Megamho, 4.2)] + [InlineData("en-US", "4.2 MS", ElectricConductanceUnit.Megasiemens, 4.2)] + [InlineData("en-US", "4.2 ℧", ElectricConductanceUnit.Mho, 4.2)] + [InlineData("en-US", "4.2 µ℧", ElectricConductanceUnit.Micromho, 4.2)] + [InlineData("en-US", "4.2 µS", ElectricConductanceUnit.Microsiemens, 4.2)] + [InlineData("en-US", "4.2 m℧", ElectricConductanceUnit.Millimho, 4.2)] + [InlineData("en-US", "4.2 mS", ElectricConductanceUnit.Millisiemens, 4.2)] + [InlineData("en-US", "4.2 n℧", ElectricConductanceUnit.Nanomho, 4.2)] + [InlineData("en-US", "4.2 nS", ElectricConductanceUnit.Nanosiemens, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(ElectricConductance.TryParse("1 G℧", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gigamhos, GigamhosTolerance); - Assert.Equal(ElectricConductanceUnit.Gigamho, parsed.Unit); - } - - { - Assert.True(ElectricConductance.TryParse("1 GS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gigasiemens, GigasiemensTolerance); - Assert.Equal(ElectricConductanceUnit.Gigasiemens, parsed.Unit); - } - - { - Assert.True(ElectricConductance.TryParse("1 k℧", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilomhos, KilomhosTolerance); - Assert.Equal(ElectricConductanceUnit.Kilomho, parsed.Unit); - } - - { - Assert.True(ElectricConductance.TryParse("1 kS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilosiemens, KilosiemensTolerance); - Assert.Equal(ElectricConductanceUnit.Kilosiemens, parsed.Unit); - } - - { - Assert.True(ElectricConductance.TryParse("1 ℧", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Mhos, MhosTolerance); - Assert.Equal(ElectricConductanceUnit.Mho, parsed.Unit); - } - - { - Assert.True(ElectricConductance.TryParse("1 µ℧", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Micromhos, MicromhosTolerance); - Assert.Equal(ElectricConductanceUnit.Micromho, parsed.Unit); - } - - { - Assert.True(ElectricConductance.TryParse("1 µS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microsiemens, MicrosiemensTolerance); - Assert.Equal(ElectricConductanceUnit.Microsiemens, parsed.Unit); - } - - { - Assert.True(ElectricConductance.TryParse("1 n℧", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanomhos, NanomhosTolerance); - Assert.Equal(ElectricConductanceUnit.Nanomho, parsed.Unit); - } - - { - Assert.True(ElectricConductance.TryParse("1 nS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanosiemens, NanosiemensTolerance); - Assert.Equal(ElectricConductanceUnit.Nanosiemens, parsed.Unit); - } - - { - Assert.True(ElectricConductance.TryParse("1 S", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Siemens, SiemensTolerance); - Assert.Equal(ElectricConductanceUnit.Siemens, parsed.Unit); - } - - { - Assert.True(ElectricConductance.TryParse("1 T℧", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Teramhos, TeramhosTolerance); - Assert.Equal(ElectricConductanceUnit.Teramho, parsed.Unit); - } - - { - Assert.True(ElectricConductance.TryParse("1 TS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Terasiemens, TerasiemensTolerance); - Assert.Equal(ElectricConductanceUnit.Terasiemens, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ElectricConductance.TryParse(quantityString, out ElectricConductance parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -805,6 +679,42 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Electr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ElectricConductanceUnit.Gigamho, "G℧")] + [InlineData("en-US", ElectricConductanceUnit.Gigasiemens, "GS")] + [InlineData("en-US", ElectricConductanceUnit.Kilomho, "k℧")] + [InlineData("en-US", ElectricConductanceUnit.Kilosiemens, "kS")] + [InlineData("en-US", ElectricConductanceUnit.Megamho, "M℧")] + [InlineData("en-US", ElectricConductanceUnit.Megasiemens, "MS")] + [InlineData("en-US", ElectricConductanceUnit.Mho, "℧")] + [InlineData("en-US", ElectricConductanceUnit.Micromho, "µ℧")] + [InlineData("en-US", ElectricConductanceUnit.Microsiemens, "µS")] + [InlineData("en-US", ElectricConductanceUnit.Millimho, "m℧")] + [InlineData("en-US", ElectricConductanceUnit.Millisiemens, "mS")] + [InlineData("en-US", ElectricConductanceUnit.Nanomho, "n℧")] + [InlineData("en-US", ElectricConductanceUnit.Nanosiemens, "nS")] + [InlineData("en-US", ElectricConductanceUnit.Siemens, "S")] + [InlineData("en-US", ElectricConductanceUnit.Teramho, "T℧")] + [InlineData("en-US", ElectricConductanceUnit.Terasiemens, "TS")] + public void GetAbbreviationForCulture(string culture, ElectricConductanceUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ElectricConductance.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ElectricConductance.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ElectricConductance.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricConductanceUnit unit) @@ -835,6 +745,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); }); } @@ -858,47 +769,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] @@ -944,8 +857,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); @@ -982,23 +893,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = ElectricConductance.FromSiemens(1); - Assert.True(v.Equals(ElectricConductance.FromSiemens(1), SiemensTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ElectricConductance.Zero, SiemensTolerance, ComparisonType.Relative)); - Assert.True(ElectricConductance.FromSiemens(100).Equals(ElectricConductance.FromSiemens(120), 0.3, ComparisonType.Relative)); - Assert.False(ElectricConductance.FromSiemens(100).Equals(ElectricConductance.FromSiemens(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = ElectricConductance.FromSiemens(1); - Assert.Throws(() => v.Equals(ElectricConductance.FromSiemens(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1013,6 +907,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(siemens.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = ElectricConductance.FromSiemens(1); + var negativeTolerance = ElectricConductance.FromSiemens(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1029,6 +949,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() { @@ -1117,158 +1049,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ElectricConductance))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricConductanceUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal(ElectricConductance.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal(ElectricConductance.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal(new {ElectricConductance.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 5fc7d0c26c..c50d386acb 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductivityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductivityTestsBase.g.cs @@ -116,7 +116,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ElectricConductivity(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -129,15 +129,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ElectricConductivity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ElectricConductivityUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ElectricConductivity(1, ElectricConductivityUnit.SiemensPerMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ElectricConductivity.Zero, quantityInfo.Zero); Assert.Equal("ElectricConductivity", quantityInfo.Name); + Assert.Equal(ElectricConductivity.Zero, quantityInfo.Zero); + Assert.Equal(ElectricConductivity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ElectricConductivity.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void ElectricConductivityInfo_CreateWithCustomUnitInfos() + { + ElectricConductivityUnit[] expectedUnits = [ElectricConductivityUnit.SiemensPerMeter]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -156,27 +174,27 @@ public void SiemensPerMeterToElectricConductivityUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ElectricConductivity.From(1, ElectricConductivityUnit.MicrosiemensPerCentimeter); - AssertEx.EqualTolerance(1, quantity00.MicrosiemensPerCentimeter, MicrosiemensPerCentimeterTolerance); + Assert.Equal(1, quantity00.MicrosiemensPerCentimeter); Assert.Equal(ElectricConductivityUnit.MicrosiemensPerCentimeter, quantity00.Unit); var quantity01 = ElectricConductivity.From(1, ElectricConductivityUnit.MillisiemensPerCentimeter); - AssertEx.EqualTolerance(1, quantity01.MillisiemensPerCentimeter, MillisiemensPerCentimeterTolerance); + Assert.Equal(1, quantity01.MillisiemensPerCentimeter); Assert.Equal(ElectricConductivityUnit.MillisiemensPerCentimeter, quantity01.Unit); var quantity02 = ElectricConductivity.From(1, ElectricConductivityUnit.SiemensPerCentimeter); - AssertEx.EqualTolerance(1, quantity02.SiemensPerCentimeter, SiemensPerCentimeterTolerance); + Assert.Equal(1, quantity02.SiemensPerCentimeter); Assert.Equal(ElectricConductivityUnit.SiemensPerCentimeter, quantity02.Unit); var quantity03 = ElectricConductivity.From(1, ElectricConductivityUnit.SiemensPerFoot); - AssertEx.EqualTolerance(1, quantity03.SiemensPerFoot, SiemensPerFootTolerance); + Assert.Equal(1, quantity03.SiemensPerFoot); Assert.Equal(ElectricConductivityUnit.SiemensPerFoot, quantity03.Unit); var quantity04 = ElectricConductivity.From(1, ElectricConductivityUnit.SiemensPerInch); - AssertEx.EqualTolerance(1, quantity04.SiemensPerInch, SiemensPerInchTolerance); + Assert.Equal(1, quantity04.SiemensPerInch); Assert.Equal(ElectricConductivityUnit.SiemensPerInch, quantity04.Unit); var quantity05 = ElectricConductivity.From(1, ElectricConductivityUnit.SiemensPerMeter); - AssertEx.EqualTolerance(1, quantity05.SiemensPerMeter, SiemensPerMeterTolerance); + Assert.Equal(1, quantity05.SiemensPerMeter); Assert.Equal(ElectricConductivityUnit.SiemensPerMeter, quantity05.Unit); } @@ -317,92 +335,34 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 µS/cm", ElectricConductivityUnit.MicrosiemensPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 mS/cm", ElectricConductivityUnit.MillisiemensPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 S/cm", ElectricConductivityUnit.SiemensPerCentimeter, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = ElectricConductivity.Parse("1 µS/cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrosiemensPerCentimeter, MicrosiemensPerCentimeterTolerance); - Assert.Equal(ElectricConductivityUnit.MicrosiemensPerCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricConductivity.Parse("1 mS/cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillisiemensPerCentimeter, MillisiemensPerCentimeterTolerance); - Assert.Equal(ElectricConductivityUnit.MillisiemensPerCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricConductivity.Parse("1 S/cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SiemensPerCentimeter, SiemensPerCentimeterTolerance); - Assert.Equal(ElectricConductivityUnit.SiemensPerCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricConductivity.Parse("1 S/ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SiemensPerFoot, SiemensPerFootTolerance); - Assert.Equal(ElectricConductivityUnit.SiemensPerFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricConductivity.Parse("1 S/in", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SiemensPerInch, SiemensPerInchTolerance); - Assert.Equal(ElectricConductivityUnit.SiemensPerInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricConductivity.Parse("1 S/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SiemensPerMeter, SiemensPerMeterTolerance); - Assert.Equal(ElectricConductivityUnit.SiemensPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ElectricConductivity.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 µS/cm", ElectricConductivityUnit.MicrosiemensPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 mS/cm", ElectricConductivityUnit.MillisiemensPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 S/cm", ElectricConductivityUnit.SiemensPerCentimeter, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(ElectricConductivity.TryParse("1 µS/cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrosiemensPerCentimeter, MicrosiemensPerCentimeterTolerance); - Assert.Equal(ElectricConductivityUnit.MicrosiemensPerCentimeter, parsed.Unit); - } - - { - Assert.True(ElectricConductivity.TryParse("1 mS/cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillisiemensPerCentimeter, MillisiemensPerCentimeterTolerance); - Assert.Equal(ElectricConductivityUnit.MillisiemensPerCentimeter, parsed.Unit); - } - - { - Assert.True(ElectricConductivity.TryParse("1 S/cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SiemensPerCentimeter, SiemensPerCentimeterTolerance); - Assert.Equal(ElectricConductivityUnit.SiemensPerCentimeter, parsed.Unit); - } - - { - Assert.True(ElectricConductivity.TryParse("1 S/ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SiemensPerFoot, SiemensPerFootTolerance); - Assert.Equal(ElectricConductivityUnit.SiemensPerFoot, parsed.Unit); - } - - { - Assert.True(ElectricConductivity.TryParse("1 S/in", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SiemensPerInch, SiemensPerInchTolerance); - Assert.Equal(ElectricConductivityUnit.SiemensPerInch, parsed.Unit); - } - - { - Assert.True(ElectricConductivity.TryParse("1 S/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SiemensPerMeter, SiemensPerMeterTolerance); - Assert.Equal(ElectricConductivityUnit.SiemensPerMeter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ElectricConductivity.TryParse(quantityString, out ElectricConductivity parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -519,6 +479,32 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Electr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ElectricConductivityUnit.MicrosiemensPerCentimeter, "µS/cm")] + [InlineData("en-US", ElectricConductivityUnit.MillisiemensPerCentimeter, "mS/cm")] + [InlineData("en-US", ElectricConductivityUnit.SiemensPerCentimeter, "S/cm")] + [InlineData("en-US", ElectricConductivityUnit.SiemensPerFoot, "S/ft")] + [InlineData("en-US", ElectricConductivityUnit.SiemensPerInch, "S/in")] + [InlineData("en-US", ElectricConductivityUnit.SiemensPerMeter, "S/m")] + public void GetAbbreviationForCulture(string culture, ElectricConductivityUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ElectricConductivity.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ElectricConductivity.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ElectricConductivity.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricConductivityUnit unit) @@ -549,6 +535,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); }); } @@ -572,37 +559,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] @@ -648,8 +637,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); @@ -687,34 +674,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = ElectricConductivity.FromSiemensPerMeter(1); - Assert.True(v.Equals(ElectricConductivity.FromSiemensPerMeter(1), SiemensPerMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ElectricConductivity.Zero, SiemensPerMeterTolerance, ComparisonType.Relative)); - Assert.True(ElectricConductivity.FromSiemensPerMeter(100).Equals(ElectricConductivity.FromSiemensPerMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(ElectricConductivity.FromSiemensPerMeter(100).Equals(ElectricConductivity.FromSiemensPerMeter(120), 0.1, ComparisonType.Relative)); + ElectricConductivity siemenspermeter = ElectricConductivity.FromSiemensPerMeter(1); + Assert.False(siemenspermeter.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = ElectricConductivity.FromSiemensPerMeter(1); - Assert.Throws(() => v.Equals(ElectricConductivity.FromSiemensPerMeter(1), -1, ComparisonType.Relative)); + ElectricConductivity siemenspermeter = ElectricConductivity.FromSiemensPerMeter(1); + Assert.False(siemenspermeter.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - ElectricConductivity siemenspermeter = ElectricConductivity.FromSiemensPerMeter(1); - Assert.False(siemenspermeter.Equals(new object())); + var quantity = ElectricConductivity.FromSiemensPerMeter(firstValue); + var otherQuantity = ElectricConductivity.FromSiemensPerMeter(secondValue); + ElectricConductivity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - ElectricConductivity siemenspermeter = ElectricConductivity.FromSiemensPerMeter(1); - Assert.False(siemenspermeter.Equals(null)); + var quantity = ElectricConductivity.FromSiemensPerMeter(1); + var negativeTolerance = ElectricConductivity.FromSiemensPerMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -733,6 +729,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() { @@ -801,158 +809,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ElectricConductivity))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricConductivityUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal(ElectricConductivity.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal(ElectricConductivity.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal(new {ElectricConductivity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 227eaeeaa4..b411216902 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentDensityTestsBase.g.cs @@ -104,7 +104,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ElectricCurrentDensity(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -117,15 +117,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ElectricCurrentDensity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ElectricCurrentDensityUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ElectricCurrentDensity(1, ElectricCurrentDensityUnit.AmperePerSquareMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ElectricCurrentDensity.Zero, quantityInfo.Zero); Assert.Equal("ElectricCurrentDensity", quantityInfo.Name); + Assert.Equal(ElectricCurrentDensity.Zero, quantityInfo.Zero); + Assert.Equal(ElectricCurrentDensity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ElectricCurrentDensity.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void ElectricCurrentDensityInfo_CreateWithCustomUnitInfos() + { + ElectricCurrentDensityUnit[] expectedUnits = [ElectricCurrentDensityUnit.AmperePerSquareMeter]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -141,15 +159,15 @@ public void AmperePerSquareMeterToElectricCurrentDensityUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ElectricCurrentDensity.From(1, ElectricCurrentDensityUnit.AmperePerSquareFoot); - AssertEx.EqualTolerance(1, quantity00.AmperesPerSquareFoot, AmperesPerSquareFootTolerance); + Assert.Equal(1, quantity00.AmperesPerSquareFoot); Assert.Equal(ElectricCurrentDensityUnit.AmperePerSquareFoot, quantity00.Unit); var quantity01 = ElectricCurrentDensity.From(1, ElectricCurrentDensityUnit.AmperePerSquareInch); - AssertEx.EqualTolerance(1, quantity01.AmperesPerSquareInch, AmperesPerSquareInchTolerance); + Assert.Equal(1, quantity01.AmperesPerSquareInch); Assert.Equal(ElectricCurrentDensityUnit.AmperePerSquareInch, quantity01.Unit); var quantity02 = ElectricCurrentDensity.From(1, ElectricCurrentDensityUnit.AmperePerSquareMeter); - AssertEx.EqualTolerance(1, quantity02.AmperesPerSquareMeter, AmperesPerSquareMeterTolerance); + Assert.Equal(1, quantity02.AmperesPerSquareMeter); Assert.Equal(ElectricCurrentDensityUnit.AmperePerSquareMeter, quantity02.Unit); } @@ -287,53 +305,28 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [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, decimal expectedValue) { - try - { - var parsed = ElectricCurrentDensity.Parse("1 A/ft²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.AmperesPerSquareFoot, AmperesPerSquareFootTolerance); - Assert.Equal(ElectricCurrentDensityUnit.AmperePerSquareFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCurrentDensity.Parse("1 A/in²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.AmperesPerSquareInch, AmperesPerSquareInchTolerance); - Assert.Equal(ElectricCurrentDensityUnit.AmperePerSquareInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCurrentDensity.Parse("1 A/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.AmperesPerSquareMeter, AmperesPerSquareMeterTolerance); - Assert.Equal(ElectricCurrentDensityUnit.AmperePerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ElectricCurrentDensity.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [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, decimal expectedValue) { - { - Assert.True(ElectricCurrentDensity.TryParse("1 A/ft²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.AmperesPerSquareFoot, AmperesPerSquareFootTolerance); - Assert.Equal(ElectricCurrentDensityUnit.AmperePerSquareFoot, parsed.Unit); - } - - { - Assert.True(ElectricCurrentDensity.TryParse("1 A/in²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.AmperesPerSquareInch, AmperesPerSquareInchTolerance); - Assert.Equal(ElectricCurrentDensityUnit.AmperePerSquareInch, parsed.Unit); - } - - { - Assert.True(ElectricCurrentDensity.TryParse("1 A/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.AmperesPerSquareMeter, AmperesPerSquareMeterTolerance); - Assert.Equal(ElectricCurrentDensityUnit.AmperePerSquareMeter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ElectricCurrentDensity.TryParse(quantityString, out ElectricCurrentDensity parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -426,6 +419,29 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Electr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ElectricCurrentDensityUnit.AmperePerSquareFoot, "A/ft²")] + [InlineData("en-US", ElectricCurrentDensityUnit.AmperePerSquareInch, "A/in²")] + [InlineData("en-US", ElectricCurrentDensityUnit.AmperePerSquareMeter, "A/m²")] + public void GetAbbreviationForCulture(string culture, ElectricCurrentDensityUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ElectricCurrentDensity.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ElectricCurrentDensity.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ElectricCurrentDensity.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricCurrentDensityUnit unit) @@ -456,6 +472,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); }); } @@ -479,34 +496,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] @@ -552,8 +571,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); @@ -591,34 +608,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = ElectricCurrentDensity.FromAmperesPerSquareMeter(1); - Assert.True(v.Equals(ElectricCurrentDensity.FromAmperesPerSquareMeter(1), AmperesPerSquareMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ElectricCurrentDensity.Zero, AmperesPerSquareMeterTolerance, ComparisonType.Relative)); - Assert.True(ElectricCurrentDensity.FromAmperesPerSquareMeter(100).Equals(ElectricCurrentDensity.FromAmperesPerSquareMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(ElectricCurrentDensity.FromAmperesPerSquareMeter(100).Equals(ElectricCurrentDensity.FromAmperesPerSquareMeter(120), 0.1, ComparisonType.Relative)); + ElectricCurrentDensity amperepersquaremeter = ElectricCurrentDensity.FromAmperesPerSquareMeter(1); + Assert.False(amperepersquaremeter.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = ElectricCurrentDensity.FromAmperesPerSquareMeter(1); - Assert.Throws(() => v.Equals(ElectricCurrentDensity.FromAmperesPerSquareMeter(1), -1, ComparisonType.Relative)); + ElectricCurrentDensity amperepersquaremeter = ElectricCurrentDensity.FromAmperesPerSquareMeter(1); + Assert.False(amperepersquaremeter.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - ElectricCurrentDensity amperepersquaremeter = ElectricCurrentDensity.FromAmperesPerSquareMeter(1); - Assert.False(amperepersquaremeter.Equals(new object())); + var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(firstValue); + var otherQuantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(secondValue); + ElectricCurrentDensity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - ElectricCurrentDensity amperepersquaremeter = ElectricCurrentDensity.FromAmperesPerSquareMeter(1); - Assert.False(amperepersquaremeter.Equals(null)); + var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1); + var negativeTolerance = ElectricCurrentDensity.FromAmperesPerSquareMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -637,6 +663,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() { @@ -699,158 +737,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ElectricCurrentDensity))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricCurrentDensityUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal(ElectricCurrentDensity.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal(ElectricCurrentDensity.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal(new {ElectricCurrentDensity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 614baf8e71..0ded8ddc58 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentGradientTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentGradientTestsBase.g.cs @@ -120,7 +120,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ElectricCurrentGradient(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -133,15 +133,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ElectricCurrentGradient_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ElectricCurrentGradientUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ElectricCurrentGradient(1, ElectricCurrentGradientUnit.AmperePerSecond); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ElectricCurrentGradient.Zero, quantityInfo.Zero); Assert.Equal("ElectricCurrentGradient", quantityInfo.Name); + Assert.Equal(ElectricCurrentGradient.Zero, quantityInfo.Zero); + Assert.Equal(ElectricCurrentGradient.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ElectricCurrentGradient.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void ElectricCurrentGradientInfo_CreateWithCustomUnitInfos() + { + ElectricCurrentGradientUnit[] expectedUnits = [ElectricCurrentGradientUnit.AmperePerSecond]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -161,31 +179,31 @@ public void AmperePerSecondToElectricCurrentGradientUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ElectricCurrentGradient.From(1, ElectricCurrentGradientUnit.AmperePerMicrosecond); - AssertEx.EqualTolerance(1, quantity00.AmperesPerMicrosecond, AmperesPerMicrosecondTolerance); + Assert.Equal(1, quantity00.AmperesPerMicrosecond); Assert.Equal(ElectricCurrentGradientUnit.AmperePerMicrosecond, quantity00.Unit); var quantity01 = ElectricCurrentGradient.From(1, ElectricCurrentGradientUnit.AmperePerMillisecond); - AssertEx.EqualTolerance(1, quantity01.AmperesPerMillisecond, AmperesPerMillisecondTolerance); + Assert.Equal(1, quantity01.AmperesPerMillisecond); Assert.Equal(ElectricCurrentGradientUnit.AmperePerMillisecond, quantity01.Unit); var quantity02 = ElectricCurrentGradient.From(1, ElectricCurrentGradientUnit.AmperePerMinute); - AssertEx.EqualTolerance(1, quantity02.AmperesPerMinute, AmperesPerMinuteTolerance); + Assert.Equal(1, quantity02.AmperesPerMinute); Assert.Equal(ElectricCurrentGradientUnit.AmperePerMinute, quantity02.Unit); var quantity03 = ElectricCurrentGradient.From(1, ElectricCurrentGradientUnit.AmperePerNanosecond); - AssertEx.EqualTolerance(1, quantity03.AmperesPerNanosecond, AmperesPerNanosecondTolerance); + Assert.Equal(1, quantity03.AmperesPerNanosecond); Assert.Equal(ElectricCurrentGradientUnit.AmperePerNanosecond, quantity03.Unit); var quantity04 = ElectricCurrentGradient.From(1, ElectricCurrentGradientUnit.AmperePerSecond); - AssertEx.EqualTolerance(1, quantity04.AmperesPerSecond, AmperesPerSecondTolerance); + Assert.Equal(1, quantity04.AmperesPerSecond); Assert.Equal(ElectricCurrentGradientUnit.AmperePerSecond, quantity04.Unit); var quantity05 = ElectricCurrentGradient.From(1, ElectricCurrentGradientUnit.MilliamperePerMinute); - AssertEx.EqualTolerance(1, quantity05.MilliamperesPerMinute, MilliamperesPerMinuteTolerance); + Assert.Equal(1, quantity05.MilliamperesPerMinute); Assert.Equal(ElectricCurrentGradientUnit.MilliamperePerMinute, quantity05.Unit); var quantity06 = ElectricCurrentGradient.From(1, ElectricCurrentGradientUnit.MilliamperePerSecond); - AssertEx.EqualTolerance(1, quantity06.MilliamperesPerSecond, MilliamperesPerSecondTolerance); + Assert.Equal(1, quantity06.MilliamperesPerSecond); Assert.Equal(ElectricCurrentGradientUnit.MilliamperePerSecond, quantity06.Unit); } @@ -327,105 +345,36 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 A/μs", ElectricCurrentGradientUnit.AmperePerMicrosecond, 4.2)] + [InlineData("en-US", "4.2 A/ms", ElectricCurrentGradientUnit.AmperePerMillisecond, 4.2)] + [InlineData("en-US", "4.2 A/min", ElectricCurrentGradientUnit.AmperePerMinute, 4.2)] + [InlineData("en-US", "4.2 A/ns", ElectricCurrentGradientUnit.AmperePerNanosecond, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = ElectricCurrentGradient.Parse("1 A/μs", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.AmperesPerMicrosecond, AmperesPerMicrosecondTolerance); - Assert.Equal(ElectricCurrentGradientUnit.AmperePerMicrosecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCurrentGradient.Parse("1 A/ms", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.AmperesPerMillisecond, AmperesPerMillisecondTolerance); - Assert.Equal(ElectricCurrentGradientUnit.AmperePerMillisecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCurrentGradient.Parse("1 A/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.AmperesPerMinute, AmperesPerMinuteTolerance); - Assert.Equal(ElectricCurrentGradientUnit.AmperePerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCurrentGradient.Parse("1 A/ns", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.AmperesPerNanosecond, AmperesPerNanosecondTolerance); - Assert.Equal(ElectricCurrentGradientUnit.AmperePerNanosecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCurrentGradient.Parse("1 A/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.AmperesPerSecond, AmperesPerSecondTolerance); - Assert.Equal(ElectricCurrentGradientUnit.AmperePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCurrentGradient.Parse("1 mA/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilliamperesPerMinute, MilliamperesPerMinuteTolerance); - Assert.Equal(ElectricCurrentGradientUnit.MilliamperePerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCurrentGradient.Parse("1 mA/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilliamperesPerSecond, MilliamperesPerSecondTolerance); - Assert.Equal(ElectricCurrentGradientUnit.MilliamperePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ElectricCurrentGradient.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 A/μs", ElectricCurrentGradientUnit.AmperePerMicrosecond, 4.2)] + [InlineData("en-US", "4.2 A/ms", ElectricCurrentGradientUnit.AmperePerMillisecond, 4.2)] + [InlineData("en-US", "4.2 A/min", ElectricCurrentGradientUnit.AmperePerMinute, 4.2)] + [InlineData("en-US", "4.2 A/ns", ElectricCurrentGradientUnit.AmperePerNanosecond, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(ElectricCurrentGradient.TryParse("1 A/μs", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.AmperesPerMicrosecond, AmperesPerMicrosecondTolerance); - Assert.Equal(ElectricCurrentGradientUnit.AmperePerMicrosecond, parsed.Unit); - } - - { - Assert.True(ElectricCurrentGradient.TryParse("1 A/ms", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.AmperesPerMillisecond, AmperesPerMillisecondTolerance); - Assert.Equal(ElectricCurrentGradientUnit.AmperePerMillisecond, parsed.Unit); - } - - { - Assert.True(ElectricCurrentGradient.TryParse("1 A/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.AmperesPerMinute, AmperesPerMinuteTolerance); - Assert.Equal(ElectricCurrentGradientUnit.AmperePerMinute, parsed.Unit); - } - - { - Assert.True(ElectricCurrentGradient.TryParse("1 A/ns", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.AmperesPerNanosecond, AmperesPerNanosecondTolerance); - Assert.Equal(ElectricCurrentGradientUnit.AmperePerNanosecond, parsed.Unit); - } - - { - Assert.True(ElectricCurrentGradient.TryParse("1 A/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.AmperesPerSecond, AmperesPerSecondTolerance); - Assert.Equal(ElectricCurrentGradientUnit.AmperePerSecond, parsed.Unit); - } - - { - Assert.True(ElectricCurrentGradient.TryParse("1 mA/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilliamperesPerMinute, MilliamperesPerMinuteTolerance); - Assert.Equal(ElectricCurrentGradientUnit.MilliamperePerMinute, parsed.Unit); - } - - { - Assert.True(ElectricCurrentGradient.TryParse("1 mA/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilliamperesPerSecond, MilliamperesPerSecondTolerance); - Assert.Equal(ElectricCurrentGradientUnit.MilliamperePerSecond, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ElectricCurrentGradient.TryParse(quantityString, out ElectricCurrentGradient parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -550,6 +499,33 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Electr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ElectricCurrentGradientUnit.AmperePerMicrosecond, "A/μs")] + [InlineData("en-US", ElectricCurrentGradientUnit.AmperePerMillisecond, "A/ms")] + [InlineData("en-US", ElectricCurrentGradientUnit.AmperePerMinute, "A/min")] + [InlineData("en-US", ElectricCurrentGradientUnit.AmperePerNanosecond, "A/ns")] + [InlineData("en-US", ElectricCurrentGradientUnit.AmperePerSecond, "A/s")] + [InlineData("en-US", ElectricCurrentGradientUnit.MilliamperePerMinute, "mA/min")] + [InlineData("en-US", ElectricCurrentGradientUnit.MilliamperePerSecond, "mA/s")] + public void GetAbbreviationForCulture(string culture, ElectricCurrentGradientUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ElectricCurrentGradient.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ElectricCurrentGradient.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ElectricCurrentGradient.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricCurrentGradientUnit unit) @@ -580,6 +556,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); }); } @@ -603,38 +580,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] @@ -680,8 +659,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); @@ -719,34 +696,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = ElectricCurrentGradient.FromAmperesPerSecond(1); - Assert.True(v.Equals(ElectricCurrentGradient.FromAmperesPerSecond(1), AmperesPerSecondTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ElectricCurrentGradient.Zero, AmperesPerSecondTolerance, ComparisonType.Relative)); - Assert.True(ElectricCurrentGradient.FromAmperesPerSecond(100).Equals(ElectricCurrentGradient.FromAmperesPerSecond(120), 0.3, ComparisonType.Relative)); - Assert.False(ElectricCurrentGradient.FromAmperesPerSecond(100).Equals(ElectricCurrentGradient.FromAmperesPerSecond(120), 0.1, ComparisonType.Relative)); + ElectricCurrentGradient amperepersecond = ElectricCurrentGradient.FromAmperesPerSecond(1); + Assert.False(amperepersecond.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = ElectricCurrentGradient.FromAmperesPerSecond(1); - Assert.Throws(() => v.Equals(ElectricCurrentGradient.FromAmperesPerSecond(1), -1, ComparisonType.Relative)); + ElectricCurrentGradient amperepersecond = ElectricCurrentGradient.FromAmperesPerSecond(1); + Assert.False(amperepersecond.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - ElectricCurrentGradient amperepersecond = ElectricCurrentGradient.FromAmperesPerSecond(1); - Assert.False(amperepersecond.Equals(new object())); + var quantity = ElectricCurrentGradient.FromAmperesPerSecond(firstValue); + var otherQuantity = ElectricCurrentGradient.FromAmperesPerSecond(secondValue); + ElectricCurrentGradient maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - ElectricCurrentGradient amperepersecond = ElectricCurrentGradient.FromAmperesPerSecond(1); - Assert.False(amperepersecond.Equals(null)); + var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1); + var negativeTolerance = ElectricCurrentGradient.FromAmperesPerSecond(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -765,6 +751,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() { @@ -835,158 +833,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ElectricCurrentGradient))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricCurrentGradientUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal(ElectricCurrentGradient.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal(ElectricCurrentGradient.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal(new {ElectricCurrentGradient.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 cb362d8b98..80e7c1fcfa 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentTestsBase.g.cs @@ -128,7 +128,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ElectricCurrent(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -141,15 +141,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ElectricCurrent_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ElectricCurrentUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ElectricCurrent(1, ElectricCurrentUnit.Ampere); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ElectricCurrent.Zero, quantityInfo.Zero); Assert.Equal("ElectricCurrent", quantityInfo.Name); + Assert.Equal(ElectricCurrent.Zero, quantityInfo.Zero); + Assert.Equal(ElectricCurrent.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ElectricCurrent.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -171,39 +189,39 @@ public void AmpereToElectricCurrentUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ElectricCurrent.From(1, ElectricCurrentUnit.Ampere); - AssertEx.EqualTolerance(1, quantity00.Amperes, AmperesTolerance); + Assert.Equal(1, quantity00.Amperes); Assert.Equal(ElectricCurrentUnit.Ampere, quantity00.Unit); var quantity01 = ElectricCurrent.From(1, ElectricCurrentUnit.Centiampere); - AssertEx.EqualTolerance(1, quantity01.Centiamperes, CentiamperesTolerance); + Assert.Equal(1, quantity01.Centiamperes); Assert.Equal(ElectricCurrentUnit.Centiampere, quantity01.Unit); var quantity02 = ElectricCurrent.From(1, ElectricCurrentUnit.Femtoampere); - AssertEx.EqualTolerance(1, quantity02.Femtoamperes, FemtoamperesTolerance); + Assert.Equal(1, quantity02.Femtoamperes); Assert.Equal(ElectricCurrentUnit.Femtoampere, quantity02.Unit); var quantity03 = ElectricCurrent.From(1, ElectricCurrentUnit.Kiloampere); - AssertEx.EqualTolerance(1, quantity03.Kiloamperes, KiloamperesTolerance); + Assert.Equal(1, quantity03.Kiloamperes); Assert.Equal(ElectricCurrentUnit.Kiloampere, quantity03.Unit); var quantity04 = ElectricCurrent.From(1, ElectricCurrentUnit.Megaampere); - AssertEx.EqualTolerance(1, quantity04.Megaamperes, MegaamperesTolerance); + Assert.Equal(1, quantity04.Megaamperes); Assert.Equal(ElectricCurrentUnit.Megaampere, quantity04.Unit); var quantity05 = ElectricCurrent.From(1, ElectricCurrentUnit.Microampere); - AssertEx.EqualTolerance(1, quantity05.Microamperes, MicroamperesTolerance); + Assert.Equal(1, quantity05.Microamperes); Assert.Equal(ElectricCurrentUnit.Microampere, quantity05.Unit); var quantity06 = ElectricCurrent.From(1, ElectricCurrentUnit.Milliampere); - AssertEx.EqualTolerance(1, quantity06.Milliamperes, MilliamperesTolerance); + Assert.Equal(1, quantity06.Milliamperes); Assert.Equal(ElectricCurrentUnit.Milliampere, quantity06.Unit); var quantity07 = ElectricCurrent.From(1, ElectricCurrentUnit.Nanoampere); - AssertEx.EqualTolerance(1, quantity07.Nanoamperes, NanoamperesTolerance); + Assert.Equal(1, quantity07.Nanoamperes); Assert.Equal(ElectricCurrentUnit.Nanoampere, quantity07.Unit); var quantity08 = ElectricCurrent.From(1, ElectricCurrentUnit.Picoampere); - AssertEx.EqualTolerance(1, quantity08.Picoamperes, PicoamperesTolerance); + Assert.Equal(1, quantity08.Picoamperes); Assert.Equal(ElectricCurrentUnit.Picoampere, quantity08.Unit); } @@ -347,119 +365,40 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 A", ElectricCurrentUnit.Ampere, 4.2)] + [InlineData("en-US", "4.2 cA", ElectricCurrentUnit.Centiampere, 4.2)] + [InlineData("en-US", "4.2 fA", ElectricCurrentUnit.Femtoampere, 4.2)] + [InlineData("en-US", "4.2 kA", ElectricCurrentUnit.Kiloampere, 4.2)] + [InlineData("en-US", "4.2 MA", ElectricCurrentUnit.Megaampere, 4.2)] + [InlineData("en-US", "4.2 µA", ElectricCurrentUnit.Microampere, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = ElectricCurrent.Parse("1 A", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Amperes, AmperesTolerance); - Assert.Equal(ElectricCurrentUnit.Ampere, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCurrent.Parse("1 cA", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Centiamperes, CentiamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Centiampere, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCurrent.Parse("1 fA", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Femtoamperes, FemtoamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Femtoampere, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCurrent.Parse("1 kA", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kiloamperes, KiloamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Kiloampere, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCurrent.Parse("1 MA", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megaamperes, MegaamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Megaampere, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCurrent.Parse("1 µA", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microamperes, MicroamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Microampere, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCurrent.Parse("1 mA", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Milliamperes, MilliamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Milliampere, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCurrent.Parse("1 nA", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanoamperes, NanoamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Nanoampere, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricCurrent.Parse("1 pA", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Picoamperes, PicoamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Picoampere, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ElectricCurrent.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 A", ElectricCurrentUnit.Ampere, 4.2)] + [InlineData("en-US", "4.2 cA", ElectricCurrentUnit.Centiampere, 4.2)] + [InlineData("en-US", "4.2 fA", ElectricCurrentUnit.Femtoampere, 4.2)] + [InlineData("en-US", "4.2 kA", ElectricCurrentUnit.Kiloampere, 4.2)] + [InlineData("en-US", "4.2 MA", ElectricCurrentUnit.Megaampere, 4.2)] + [InlineData("en-US", "4.2 µA", ElectricCurrentUnit.Microampere, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(ElectricCurrent.TryParse("1 A", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Amperes, AmperesTolerance); - Assert.Equal(ElectricCurrentUnit.Ampere, parsed.Unit); - } - - { - Assert.True(ElectricCurrent.TryParse("1 cA", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Centiamperes, CentiamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Centiampere, parsed.Unit); - } - - { - Assert.True(ElectricCurrent.TryParse("1 fA", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Femtoamperes, FemtoamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Femtoampere, parsed.Unit); - } - - { - Assert.True(ElectricCurrent.TryParse("1 kA", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kiloamperes, KiloamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Kiloampere, parsed.Unit); - } - - { - Assert.True(ElectricCurrent.TryParse("1 µA", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microamperes, MicroamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Microampere, parsed.Unit); - } - - { - Assert.True(ElectricCurrent.TryParse("1 nA", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanoamperes, NanoamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Nanoampere, parsed.Unit); - } - - { - Assert.True(ElectricCurrent.TryParse("1 pA", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Picoamperes, PicoamperesTolerance); - Assert.Equal(ElectricCurrentUnit.Picoampere, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ElectricCurrent.TryParse(quantityString, out ElectricCurrent parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -600,6 +539,35 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Electr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ElectricCurrentUnit.Ampere, "A")] + [InlineData("en-US", ElectricCurrentUnit.Centiampere, "cA")] + [InlineData("en-US", ElectricCurrentUnit.Femtoampere, "fA")] + [InlineData("en-US", ElectricCurrentUnit.Kiloampere, "kA")] + [InlineData("en-US", ElectricCurrentUnit.Megaampere, "MA")] + [InlineData("en-US", ElectricCurrentUnit.Microampere, "µA")] + [InlineData("en-US", ElectricCurrentUnit.Milliampere, "mA")] + [InlineData("en-US", ElectricCurrentUnit.Nanoampere, "nA")] + [InlineData("en-US", ElectricCurrentUnit.Picoampere, "pA")] + public void GetAbbreviationForCulture(string culture, ElectricCurrentUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ElectricCurrent.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ElectricCurrent.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ElectricCurrent.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricCurrentUnit unit) @@ -630,6 +598,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); }); } @@ -653,40 +622,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] @@ -732,8 +703,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); @@ -771,34 +740,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = ElectricCurrent.FromAmperes(1); - Assert.True(v.Equals(ElectricCurrent.FromAmperes(1), AmperesTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ElectricCurrent.Zero, AmperesTolerance, ComparisonType.Relative)); - Assert.True(ElectricCurrent.FromAmperes(100).Equals(ElectricCurrent.FromAmperes(120), 0.3, ComparisonType.Relative)); - Assert.False(ElectricCurrent.FromAmperes(100).Equals(ElectricCurrent.FromAmperes(120), 0.1, ComparisonType.Relative)); + ElectricCurrent ampere = ElectricCurrent.FromAmperes(1); + Assert.False(ampere.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = ElectricCurrent.FromAmperes(1); - Assert.Throws(() => v.Equals(ElectricCurrent.FromAmperes(1), -1, ComparisonType.Relative)); + ElectricCurrent ampere = ElectricCurrent.FromAmperes(1); + Assert.False(ampere.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - ElectricCurrent ampere = ElectricCurrent.FromAmperes(1); - Assert.False(ampere.Equals(new object())); + var quantity = ElectricCurrent.FromAmperes(firstValue); + var otherQuantity = ElectricCurrent.FromAmperes(secondValue); + ElectricCurrent maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - ElectricCurrent ampere = ElectricCurrent.FromAmperes(1); - Assert.False(ampere.Equals(null)); + var quantity = ElectricCurrent.FromAmperes(1); + var negativeTolerance = ElectricCurrent.FromAmperes(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -817,6 +795,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() { @@ -891,158 +881,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ElectricCurrent))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricCurrentUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal(ElectricCurrent.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal(ElectricCurrent.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal(new {ElectricCurrent.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 dd51cd898f..ade031be3e 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricFieldTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricFieldTestsBase.g.cs @@ -96,7 +96,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ElectricField(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -109,15 +109,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ElectricField_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ElectricFieldUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ElectricField(1, ElectricFieldUnit.VoltPerMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ElectricField.Zero, quantityInfo.Zero); Assert.Equal("ElectricField", quantityInfo.Name); + Assert.Equal(ElectricField.Zero, quantityInfo.Zero); + Assert.Equal(ElectricField.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ElectricField.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -131,7 +149,7 @@ public void VoltPerMeterToElectricFieldUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ElectricField.From(1, ElectricFieldUnit.VoltPerMeter); - AssertEx.EqualTolerance(1, quantity00.VoltsPerMeter, VoltsPerMeterTolerance); + Assert.Equal(1, quantity00.VoltsPerMeter); Assert.Equal(ElectricFieldUnit.VoltPerMeter, quantity00.Unit); } @@ -267,27 +285,24 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 V/m", ElectricFieldUnit.VoltPerMeter, 4.2)] + public void Parse(string culture, string quantityString, ElectricFieldUnit expectedUnit, decimal expectedValue) { - try - { - var parsed = ElectricField.Parse("1 V/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.VoltsPerMeter, VoltsPerMeterTolerance); - Assert.Equal(ElectricFieldUnit.VoltPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ElectricField.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 V/m", ElectricFieldUnit.VoltPerMeter, 4.2)] + public void TryParse(string culture, string quantityString, ElectricFieldUnit expectedUnit, decimal expectedValue) { - { - Assert.True(ElectricField.TryParse("1 V/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.VoltsPerMeter, VoltsPerMeterTolerance); - Assert.Equal(ElectricFieldUnit.VoltPerMeter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ElectricField.TryParse(quantityString, out ElectricField parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -364,6 +379,27 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Electr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ElectricFieldUnit.VoltPerMeter, "V/m")] + public void GetAbbreviationForCulture(string culture, ElectricFieldUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ElectricField.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ElectricField.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ElectricField.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricFieldUnit unit) @@ -394,6 +430,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); }); } @@ -417,32 +454,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] @@ -488,7 +527,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); @@ -526,34 +564,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = ElectricField.FromVoltsPerMeter(1); - Assert.True(v.Equals(ElectricField.FromVoltsPerMeter(1), VoltsPerMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ElectricField.Zero, VoltsPerMeterTolerance, ComparisonType.Relative)); - Assert.True(ElectricField.FromVoltsPerMeter(100).Equals(ElectricField.FromVoltsPerMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(ElectricField.FromVoltsPerMeter(100).Equals(ElectricField.FromVoltsPerMeter(120), 0.1, ComparisonType.Relative)); + ElectricField voltpermeter = ElectricField.FromVoltsPerMeter(1); + Assert.False(voltpermeter.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = ElectricField.FromVoltsPerMeter(1); - Assert.Throws(() => v.Equals(ElectricField.FromVoltsPerMeter(1), -1, ComparisonType.Relative)); + ElectricField voltpermeter = ElectricField.FromVoltsPerMeter(1); + Assert.False(voltpermeter.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - ElectricField voltpermeter = ElectricField.FromVoltsPerMeter(1); - Assert.False(voltpermeter.Equals(new object())); + var quantity = ElectricField.FromVoltsPerMeter(firstValue); + var otherQuantity = ElectricField.FromVoltsPerMeter(secondValue); + ElectricField maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - ElectricField voltpermeter = ElectricField.FromVoltsPerMeter(1); - Assert.False(voltpermeter.Equals(null)); + var quantity = ElectricField.FromVoltsPerMeter(1); + var negativeTolerance = ElectricField.FromVoltsPerMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -572,6 +619,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() { @@ -630,158 +689,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ElectricField))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricFieldUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal(ElectricField.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal(ElectricField.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal(new {ElectricField.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 a8f3c8e805..d93532fddb 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricImpedanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricImpedanceTestsBase.g.cs @@ -124,7 +124,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ElectricImpedance(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -137,15 +137,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ElectricImpedance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ElectricImpedanceUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ElectricImpedance(1, ElectricImpedanceUnit.Ohm); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ElectricImpedance.Zero, quantityInfo.Zero); Assert.Equal("ElectricImpedance", quantityInfo.Name); + Assert.Equal(ElectricImpedance.Zero, quantityInfo.Zero); + Assert.Equal(ElectricImpedance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ElectricImpedance.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void ElectricImpedanceInfo_CreateWithCustomUnitInfos() + { + ElectricImpedanceUnit[] expectedUnits = [ElectricImpedanceUnit.Ohm]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -166,35 +184,35 @@ public void OhmToElectricImpedanceUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ElectricImpedance.From(1, ElectricImpedanceUnit.Gigaohm); - AssertEx.EqualTolerance(1, quantity00.Gigaohms, GigaohmsTolerance); + Assert.Equal(1, quantity00.Gigaohms); Assert.Equal(ElectricImpedanceUnit.Gigaohm, quantity00.Unit); var quantity01 = ElectricImpedance.From(1, ElectricImpedanceUnit.Kiloohm); - AssertEx.EqualTolerance(1, quantity01.Kiloohms, KiloohmsTolerance); + Assert.Equal(1, quantity01.Kiloohms); Assert.Equal(ElectricImpedanceUnit.Kiloohm, quantity01.Unit); var quantity02 = ElectricImpedance.From(1, ElectricImpedanceUnit.Megaohm); - AssertEx.EqualTolerance(1, quantity02.Megaohms, MegaohmsTolerance); + Assert.Equal(1, quantity02.Megaohms); Assert.Equal(ElectricImpedanceUnit.Megaohm, quantity02.Unit); var quantity03 = ElectricImpedance.From(1, ElectricImpedanceUnit.Microohm); - AssertEx.EqualTolerance(1, quantity03.Microohms, MicroohmsTolerance); + Assert.Equal(1, quantity03.Microohms); Assert.Equal(ElectricImpedanceUnit.Microohm, quantity03.Unit); var quantity04 = ElectricImpedance.From(1, ElectricImpedanceUnit.Milliohm); - AssertEx.EqualTolerance(1, quantity04.Milliohms, MilliohmsTolerance); + Assert.Equal(1, quantity04.Milliohms); Assert.Equal(ElectricImpedanceUnit.Milliohm, quantity04.Unit); var quantity05 = ElectricImpedance.From(1, ElectricImpedanceUnit.Nanoohm); - AssertEx.EqualTolerance(1, quantity05.Nanoohms, NanoohmsTolerance); + Assert.Equal(1, quantity05.Nanoohms); Assert.Equal(ElectricImpedanceUnit.Nanoohm, quantity05.Unit); var quantity06 = ElectricImpedance.From(1, ElectricImpedanceUnit.Ohm); - AssertEx.EqualTolerance(1, quantity06.Ohms, OhmsTolerance); + Assert.Equal(1, quantity06.Ohms); Assert.Equal(ElectricImpedanceUnit.Ohm, quantity06.Unit); var quantity07 = ElectricImpedance.From(1, ElectricImpedanceUnit.Teraohm); - AssertEx.EqualTolerance(1, quantity07.Teraohms, TeraohmsTolerance); + Assert.Equal(1, quantity07.Teraohms); Assert.Equal(ElectricImpedanceUnit.Teraohm, quantity07.Unit); } @@ -337,106 +355,38 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 GΩ", ElectricImpedanceUnit.Gigaohm, 4.2)] + [InlineData("en-US", "4.2 kΩ", ElectricImpedanceUnit.Kiloohm, 4.2)] + [InlineData("en-US", "4.2 MΩ", ElectricImpedanceUnit.Megaohm, 4.2)] + [InlineData("en-US", "4.2 µΩ", ElectricImpedanceUnit.Microohm, 4.2)] + [InlineData("en-US", "4.2 mΩ", ElectricImpedanceUnit.Milliohm, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = ElectricImpedance.Parse("1 GΩ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Gigaohms, GigaohmsTolerance); - Assert.Equal(ElectricImpedanceUnit.Gigaohm, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricImpedance.Parse("1 kΩ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kiloohms, KiloohmsTolerance); - Assert.Equal(ElectricImpedanceUnit.Kiloohm, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricImpedance.Parse("1 MΩ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megaohms, MegaohmsTolerance); - Assert.Equal(ElectricImpedanceUnit.Megaohm, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricImpedance.Parse("1 µΩ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microohms, MicroohmsTolerance); - Assert.Equal(ElectricImpedanceUnit.Microohm, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricImpedance.Parse("1 mΩ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Milliohms, MilliohmsTolerance); - Assert.Equal(ElectricImpedanceUnit.Milliohm, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricImpedance.Parse("1 nΩ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanoohms, NanoohmsTolerance); - Assert.Equal(ElectricImpedanceUnit.Nanoohm, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricImpedance.Parse("1 Ω", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Ohms, OhmsTolerance); - Assert.Equal(ElectricImpedanceUnit.Ohm, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricImpedance.Parse("1 TΩ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Teraohms, TeraohmsTolerance); - Assert.Equal(ElectricImpedanceUnit.Teraohm, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ElectricImpedance.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 GΩ", ElectricImpedanceUnit.Gigaohm, 4.2)] + [InlineData("en-US", "4.2 kΩ", ElectricImpedanceUnit.Kiloohm, 4.2)] + [InlineData("en-US", "4.2 MΩ", ElectricImpedanceUnit.Megaohm, 4.2)] + [InlineData("en-US", "4.2 µΩ", ElectricImpedanceUnit.Microohm, 4.2)] + [InlineData("en-US", "4.2 mΩ", ElectricImpedanceUnit.Milliohm, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(ElectricImpedance.TryParse("1 GΩ", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gigaohms, GigaohmsTolerance); - Assert.Equal(ElectricImpedanceUnit.Gigaohm, parsed.Unit); - } - - { - Assert.True(ElectricImpedance.TryParse("1 kΩ", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kiloohms, KiloohmsTolerance); - Assert.Equal(ElectricImpedanceUnit.Kiloohm, parsed.Unit); - } - - { - Assert.True(ElectricImpedance.TryParse("1 µΩ", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microohms, MicroohmsTolerance); - Assert.Equal(ElectricImpedanceUnit.Microohm, parsed.Unit); - } - - { - Assert.True(ElectricImpedance.TryParse("1 nΩ", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanoohms, NanoohmsTolerance); - Assert.Equal(ElectricImpedanceUnit.Nanoohm, parsed.Unit); - } - - { - Assert.True(ElectricImpedance.TryParse("1 Ω", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Ohms, OhmsTolerance); - Assert.Equal(ElectricImpedanceUnit.Ohm, parsed.Unit); - } - - { - Assert.True(ElectricImpedance.TryParse("1 TΩ", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Teraohms, TeraohmsTolerance); - Assert.Equal(ElectricImpedanceUnit.Teraohm, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ElectricImpedance.TryParse(quantityString, out ElectricImpedance parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -569,6 +519,34 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Electr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ElectricImpedanceUnit.Gigaohm, "GΩ")] + [InlineData("en-US", ElectricImpedanceUnit.Kiloohm, "kΩ")] + [InlineData("en-US", ElectricImpedanceUnit.Megaohm, "MΩ")] + [InlineData("en-US", ElectricImpedanceUnit.Microohm, "µΩ")] + [InlineData("en-US", ElectricImpedanceUnit.Milliohm, "mΩ")] + [InlineData("en-US", ElectricImpedanceUnit.Nanoohm, "nΩ")] + [InlineData("en-US", ElectricImpedanceUnit.Ohm, "Ω")] + [InlineData("en-US", ElectricImpedanceUnit.Teraohm, "TΩ")] + public void GetAbbreviationForCulture(string culture, ElectricImpedanceUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ElectricImpedance.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ElectricImpedance.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ElectricImpedance.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricImpedanceUnit unit) @@ -599,6 +577,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); }); } @@ -622,39 +601,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] @@ -700,8 +681,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); @@ -739,34 +718,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = ElectricImpedance.FromOhms(1); - Assert.True(v.Equals(ElectricImpedance.FromOhms(1), OhmsTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ElectricImpedance.Zero, OhmsTolerance, ComparisonType.Relative)); - Assert.True(ElectricImpedance.FromOhms(100).Equals(ElectricImpedance.FromOhms(120), 0.3, ComparisonType.Relative)); - Assert.False(ElectricImpedance.FromOhms(100).Equals(ElectricImpedance.FromOhms(120), 0.1, ComparisonType.Relative)); + ElectricImpedance ohm = ElectricImpedance.FromOhms(1); + Assert.False(ohm.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = ElectricImpedance.FromOhms(1); - Assert.Throws(() => v.Equals(ElectricImpedance.FromOhms(1), -1, ComparisonType.Relative)); + ElectricImpedance ohm = ElectricImpedance.FromOhms(1); + Assert.False(ohm.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - ElectricImpedance ohm = ElectricImpedance.FromOhms(1); - Assert.False(ohm.Equals(new object())); + var quantity = ElectricImpedance.FromOhms(firstValue); + var otherQuantity = ElectricImpedance.FromOhms(secondValue); + ElectricImpedance maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - ElectricImpedance ohm = ElectricImpedance.FromOhms(1); - Assert.False(ohm.Equals(null)); + var quantity = ElectricImpedance.FromOhms(1); + var negativeTolerance = ElectricImpedance.FromOhms(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -785,6 +773,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() { @@ -857,158 +857,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ElectricImpedance.FromOhms(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ElectricImpedance.FromOhms(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ElectricImpedance.FromOhms(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ElectricImpedance.FromOhms(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ElectricImpedance.FromOhms(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ElectricImpedance.FromOhms(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ElectricImpedance.FromOhms(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ElectricImpedance.FromOhms(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ElectricImpedance.FromOhms(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ElectricImpedance.FromOhms(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ElectricImpedance.FromOhms(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ElectricImpedance.FromOhms(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ElectricImpedance.FromOhms(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ElectricImpedance.FromOhms(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ElectricImpedance.FromOhms(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ElectricImpedance.FromOhms(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ElectricImpedance))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ElectricImpedance.FromOhms(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricImpedanceUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ElectricImpedance.FromOhms(1.0); - Assert.Equal(ElectricImpedance.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ElectricImpedance.FromOhms(1.0); - Assert.Equal(ElectricImpedance.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ElectricImpedance.FromOhms(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ElectricImpedance.FromOhms(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ElectricImpedance.FromOhms(1.0); - Assert.Equal(new {ElectricImpedance.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 60b7a20853..b343f8a219 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricInductanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricInductanceTestsBase.g.cs @@ -112,7 +112,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ElectricInductance(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -125,15 +125,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ElectricInductance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ElectricInductanceUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ElectricInductance(1, ElectricInductanceUnit.Henry); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ElectricInductance.Zero, quantityInfo.Zero); Assert.Equal("ElectricInductance", quantityInfo.Name); + Assert.Equal(ElectricInductance.Zero, quantityInfo.Zero); + Assert.Equal(ElectricInductance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ElectricInductance.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void ElectricInductanceInfo_CreateWithCustomUnitInfos() + { + ElectricInductanceUnit[] expectedUnits = [ElectricInductanceUnit.Henry]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -151,23 +169,23 @@ public void HenryToElectricInductanceUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ElectricInductance.From(1, ElectricInductanceUnit.Henry); - AssertEx.EqualTolerance(1, quantity00.Henries, HenriesTolerance); + Assert.Equal(1, quantity00.Henries); Assert.Equal(ElectricInductanceUnit.Henry, quantity00.Unit); var quantity01 = ElectricInductance.From(1, ElectricInductanceUnit.Microhenry); - AssertEx.EqualTolerance(1, quantity01.Microhenries, MicrohenriesTolerance); + Assert.Equal(1, quantity01.Microhenries); Assert.Equal(ElectricInductanceUnit.Microhenry, quantity01.Unit); var quantity02 = ElectricInductance.From(1, ElectricInductanceUnit.Millihenry); - AssertEx.EqualTolerance(1, quantity02.Millihenries, MillihenriesTolerance); + Assert.Equal(1, quantity02.Millihenries); Assert.Equal(ElectricInductanceUnit.Millihenry, quantity02.Unit); var quantity03 = ElectricInductance.From(1, ElectricInductanceUnit.Nanohenry); - AssertEx.EqualTolerance(1, quantity03.Nanohenries, NanohenriesTolerance); + Assert.Equal(1, quantity03.Nanohenries); Assert.Equal(ElectricInductanceUnit.Nanohenry, quantity03.Unit); var quantity04 = ElectricInductance.From(1, ElectricInductanceUnit.Picohenry); - AssertEx.EqualTolerance(1, quantity04.Picohenries, PicohenriesTolerance); + Assert.Equal(1, quantity04.Picohenries); Assert.Equal(ElectricInductanceUnit.Picohenry, quantity04.Unit); } @@ -307,79 +325,32 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 H", ElectricInductanceUnit.Henry, 4.2)] + [InlineData("en-US", "4.2 µH", ElectricInductanceUnit.Microhenry, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = ElectricInductance.Parse("1 H", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Henries, HenriesTolerance); - Assert.Equal(ElectricInductanceUnit.Henry, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricInductance.Parse("1 µH", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microhenries, MicrohenriesTolerance); - Assert.Equal(ElectricInductanceUnit.Microhenry, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricInductance.Parse("1 mH", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millihenries, MillihenriesTolerance); - Assert.Equal(ElectricInductanceUnit.Millihenry, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricInductance.Parse("1 nH", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanohenries, NanohenriesTolerance); - Assert.Equal(ElectricInductanceUnit.Nanohenry, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricInductance.Parse("1 pH", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Picohenries, PicohenriesTolerance); - Assert.Equal(ElectricInductanceUnit.Picohenry, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ElectricInductance.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 H", ElectricInductanceUnit.Henry, 4.2)] + [InlineData("en-US", "4.2 µH", ElectricInductanceUnit.Microhenry, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(ElectricInductance.TryParse("1 H", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Henries, HenriesTolerance); - Assert.Equal(ElectricInductanceUnit.Henry, parsed.Unit); - } - - { - Assert.True(ElectricInductance.TryParse("1 µH", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microhenries, MicrohenriesTolerance); - Assert.Equal(ElectricInductanceUnit.Microhenry, parsed.Unit); - } - - { - Assert.True(ElectricInductance.TryParse("1 mH", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Millihenries, MillihenriesTolerance); - Assert.Equal(ElectricInductanceUnit.Millihenry, parsed.Unit); - } - - { - Assert.True(ElectricInductance.TryParse("1 nH", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanohenries, NanohenriesTolerance); - Assert.Equal(ElectricInductanceUnit.Nanohenry, parsed.Unit); - } - - { - Assert.True(ElectricInductance.TryParse("1 pH", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Picohenries, PicohenriesTolerance); - Assert.Equal(ElectricInductanceUnit.Picohenry, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ElectricInductance.TryParse(quantityString, out ElectricInductance parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -488,6 +459,31 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Electr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ElectricInductanceUnit.Henry, "H")] + [InlineData("en-US", ElectricInductanceUnit.Microhenry, "µH")] + [InlineData("en-US", ElectricInductanceUnit.Millihenry, "mH")] + [InlineData("en-US", ElectricInductanceUnit.Nanohenry, "nH")] + [InlineData("en-US", ElectricInductanceUnit.Picohenry, "pH")] + public void GetAbbreviationForCulture(string culture, ElectricInductanceUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ElectricInductance.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ElectricInductance.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ElectricInductance.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricInductanceUnit unit) @@ -518,6 +514,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); }); } @@ -541,36 +538,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] @@ -616,8 +615,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); @@ -655,34 +652,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = ElectricInductance.FromHenries(1); - Assert.True(v.Equals(ElectricInductance.FromHenries(1), HenriesTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ElectricInductance.Zero, HenriesTolerance, ComparisonType.Relative)); - Assert.True(ElectricInductance.FromHenries(100).Equals(ElectricInductance.FromHenries(120), 0.3, ComparisonType.Relative)); - Assert.False(ElectricInductance.FromHenries(100).Equals(ElectricInductance.FromHenries(120), 0.1, ComparisonType.Relative)); + ElectricInductance henry = ElectricInductance.FromHenries(1); + Assert.False(henry.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = ElectricInductance.FromHenries(1); - Assert.Throws(() => v.Equals(ElectricInductance.FromHenries(1), -1, ComparisonType.Relative)); + ElectricInductance henry = ElectricInductance.FromHenries(1); + Assert.False(henry.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - ElectricInductance henry = ElectricInductance.FromHenries(1); - Assert.False(henry.Equals(new object())); + var quantity = ElectricInductance.FromHenries(firstValue); + var otherQuantity = ElectricInductance.FromHenries(secondValue); + ElectricInductance maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - ElectricInductance henry = ElectricInductance.FromHenries(1); - Assert.False(henry.Equals(null)); + var quantity = ElectricInductance.FromHenries(1); + var negativeTolerance = ElectricInductance.FromHenries(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -701,6 +707,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() { @@ -767,158 +785,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ElectricInductance))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricInductanceUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal(ElectricInductance.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal(ElectricInductance.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal(new {ElectricInductance.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 38a8cc7ae5..99127a2bdd 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialChangeRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialChangeRateTestsBase.g.cs @@ -172,7 +172,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ElectricPotentialChangeRate(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -185,15 +185,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ElectricPotentialChangeRate_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ElectricPotentialChangeRateUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ElectricPotentialChangeRate(1, ElectricPotentialChangeRateUnit.VoltPerSecond); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ElectricPotentialChangeRate.Zero, quantityInfo.Zero); Assert.Equal("ElectricPotentialChangeRate", quantityInfo.Name); + Assert.Equal(ElectricPotentialChangeRate.Zero, quantityInfo.Zero); + Assert.Equal(ElectricPotentialChangeRate.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ElectricPotentialChangeRate.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void ElectricPotentialChangeRateInfo_CreateWithCustomUnitInfos() + { + ElectricPotentialChangeRateUnit[] expectedUnits = [ElectricPotentialChangeRateUnit.VoltPerSecond]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -226,83 +244,83 @@ public void VoltPerSecondToElectricPotentialChangeRateUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ElectricPotentialChangeRate.From(1, ElectricPotentialChangeRateUnit.KilovoltPerHour); - AssertEx.EqualTolerance(1, quantity00.KilovoltsPerHour, KilovoltsPerHourTolerance); + Assert.Equal(1, quantity00.KilovoltsPerHour); Assert.Equal(ElectricPotentialChangeRateUnit.KilovoltPerHour, quantity00.Unit); var quantity01 = ElectricPotentialChangeRate.From(1, ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond); - AssertEx.EqualTolerance(1, quantity01.KilovoltsPerMicrosecond, KilovoltsPerMicrosecondTolerance); + Assert.Equal(1, quantity01.KilovoltsPerMicrosecond); Assert.Equal(ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond, quantity01.Unit); var quantity02 = ElectricPotentialChangeRate.From(1, ElectricPotentialChangeRateUnit.KilovoltPerMinute); - AssertEx.EqualTolerance(1, quantity02.KilovoltsPerMinute, KilovoltsPerMinuteTolerance); + Assert.Equal(1, quantity02.KilovoltsPerMinute); Assert.Equal(ElectricPotentialChangeRateUnit.KilovoltPerMinute, quantity02.Unit); var quantity03 = ElectricPotentialChangeRate.From(1, ElectricPotentialChangeRateUnit.KilovoltPerSecond); - AssertEx.EqualTolerance(1, quantity03.KilovoltsPerSecond, KilovoltsPerSecondTolerance); + Assert.Equal(1, quantity03.KilovoltsPerSecond); Assert.Equal(ElectricPotentialChangeRateUnit.KilovoltPerSecond, quantity03.Unit); var quantity04 = ElectricPotentialChangeRate.From(1, ElectricPotentialChangeRateUnit.MegavoltPerHour); - AssertEx.EqualTolerance(1, quantity04.MegavoltsPerHour, MegavoltsPerHourTolerance); + Assert.Equal(1, quantity04.MegavoltsPerHour); Assert.Equal(ElectricPotentialChangeRateUnit.MegavoltPerHour, quantity04.Unit); var quantity05 = ElectricPotentialChangeRate.From(1, ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond); - AssertEx.EqualTolerance(1, quantity05.MegavoltsPerMicrosecond, MegavoltsPerMicrosecondTolerance); + Assert.Equal(1, quantity05.MegavoltsPerMicrosecond); Assert.Equal(ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond, quantity05.Unit); var quantity06 = ElectricPotentialChangeRate.From(1, ElectricPotentialChangeRateUnit.MegavoltPerMinute); - AssertEx.EqualTolerance(1, quantity06.MegavoltsPerMinute, MegavoltsPerMinuteTolerance); + Assert.Equal(1, quantity06.MegavoltsPerMinute); Assert.Equal(ElectricPotentialChangeRateUnit.MegavoltPerMinute, quantity06.Unit); var quantity07 = ElectricPotentialChangeRate.From(1, ElectricPotentialChangeRateUnit.MegavoltPerSecond); - AssertEx.EqualTolerance(1, quantity07.MegavoltsPerSecond, MegavoltsPerSecondTolerance); + Assert.Equal(1, quantity07.MegavoltsPerSecond); Assert.Equal(ElectricPotentialChangeRateUnit.MegavoltPerSecond, quantity07.Unit); var quantity08 = ElectricPotentialChangeRate.From(1, ElectricPotentialChangeRateUnit.MicrovoltPerHour); - AssertEx.EqualTolerance(1, quantity08.MicrovoltsPerHour, MicrovoltsPerHourTolerance); + Assert.Equal(1, quantity08.MicrovoltsPerHour); Assert.Equal(ElectricPotentialChangeRateUnit.MicrovoltPerHour, quantity08.Unit); var quantity09 = ElectricPotentialChangeRate.From(1, ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond); - AssertEx.EqualTolerance(1, quantity09.MicrovoltsPerMicrosecond, MicrovoltsPerMicrosecondTolerance); + Assert.Equal(1, quantity09.MicrovoltsPerMicrosecond); Assert.Equal(ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond, quantity09.Unit); var quantity10 = ElectricPotentialChangeRate.From(1, ElectricPotentialChangeRateUnit.MicrovoltPerMinute); - AssertEx.EqualTolerance(1, quantity10.MicrovoltsPerMinute, MicrovoltsPerMinuteTolerance); + Assert.Equal(1, quantity10.MicrovoltsPerMinute); Assert.Equal(ElectricPotentialChangeRateUnit.MicrovoltPerMinute, quantity10.Unit); var quantity11 = ElectricPotentialChangeRate.From(1, ElectricPotentialChangeRateUnit.MicrovoltPerSecond); - AssertEx.EqualTolerance(1, quantity11.MicrovoltsPerSecond, MicrovoltsPerSecondTolerance); + Assert.Equal(1, quantity11.MicrovoltsPerSecond); Assert.Equal(ElectricPotentialChangeRateUnit.MicrovoltPerSecond, quantity11.Unit); var quantity12 = ElectricPotentialChangeRate.From(1, ElectricPotentialChangeRateUnit.MillivoltPerHour); - AssertEx.EqualTolerance(1, quantity12.MillivoltsPerHour, MillivoltsPerHourTolerance); + Assert.Equal(1, quantity12.MillivoltsPerHour); Assert.Equal(ElectricPotentialChangeRateUnit.MillivoltPerHour, quantity12.Unit); var quantity13 = ElectricPotentialChangeRate.From(1, ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond); - AssertEx.EqualTolerance(1, quantity13.MillivoltsPerMicrosecond, MillivoltsPerMicrosecondTolerance); + Assert.Equal(1, quantity13.MillivoltsPerMicrosecond); Assert.Equal(ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond, quantity13.Unit); var quantity14 = ElectricPotentialChangeRate.From(1, ElectricPotentialChangeRateUnit.MillivoltPerMinute); - AssertEx.EqualTolerance(1, quantity14.MillivoltsPerMinute, MillivoltsPerMinuteTolerance); + Assert.Equal(1, quantity14.MillivoltsPerMinute); Assert.Equal(ElectricPotentialChangeRateUnit.MillivoltPerMinute, quantity14.Unit); var quantity15 = ElectricPotentialChangeRate.From(1, ElectricPotentialChangeRateUnit.MillivoltPerSecond); - AssertEx.EqualTolerance(1, quantity15.MillivoltsPerSecond, MillivoltsPerSecondTolerance); + Assert.Equal(1, quantity15.MillivoltsPerSecond); Assert.Equal(ElectricPotentialChangeRateUnit.MillivoltPerSecond, quantity15.Unit); var quantity16 = ElectricPotentialChangeRate.From(1, ElectricPotentialChangeRateUnit.VoltPerHour); - AssertEx.EqualTolerance(1, quantity16.VoltsPerHour, VoltsPerHourTolerance); + Assert.Equal(1, quantity16.VoltsPerHour); Assert.Equal(ElectricPotentialChangeRateUnit.VoltPerHour, quantity16.Unit); var quantity17 = ElectricPotentialChangeRate.From(1, ElectricPotentialChangeRateUnit.VoltPerMicrosecond); - AssertEx.EqualTolerance(1, quantity17.VoltsPerMicrosecond, VoltsPerMicrosecondTolerance); + Assert.Equal(1, quantity17.VoltsPerMicrosecond); Assert.Equal(ElectricPotentialChangeRateUnit.VoltPerMicrosecond, quantity17.Unit); var quantity18 = ElectricPotentialChangeRate.From(1, ElectricPotentialChangeRateUnit.VoltPerMinute); - AssertEx.EqualTolerance(1, quantity18.VoltsPerMinute, VoltsPerMinuteTolerance); + Assert.Equal(1, quantity18.VoltsPerMinute); Assert.Equal(ElectricPotentialChangeRateUnit.VoltPerMinute, quantity18.Unit); var quantity19 = ElectricPotentialChangeRate.From(1, ElectricPotentialChangeRateUnit.VoltPerSecond); - AssertEx.EqualTolerance(1, quantity19.VoltsPerSecond, VoltsPerSecondTolerance); + Assert.Equal(1, quantity19.VoltsPerSecond); Assert.Equal(ElectricPotentialChangeRateUnit.VoltPerSecond, quantity19.Unit); } @@ -457,226 +475,62 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 kV/h", ElectricPotentialChangeRateUnit.KilovoltPerHour, 4.2)] + [InlineData("en-US", "4.2 kV/μs", ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond, 4.2)] + [InlineData("en-US", "4.2 kV/min", ElectricPotentialChangeRateUnit.KilovoltPerMinute, 4.2)] + [InlineData("en-US", "4.2 kV/s", ElectricPotentialChangeRateUnit.KilovoltPerSecond, 4.2)] + [InlineData("en-US", "4.2 MV/h", ElectricPotentialChangeRateUnit.MegavoltPerHour, 4.2)] + [InlineData("en-US", "4.2 MV/μs", ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond, 4.2)] + [InlineData("en-US", "4.2 MV/min", ElectricPotentialChangeRateUnit.MegavoltPerMinute, 4.2)] + [InlineData("en-US", "4.2 MV/s", ElectricPotentialChangeRateUnit.MegavoltPerSecond, 4.2)] + [InlineData("en-US", "4.2 µV/h", ElectricPotentialChangeRateUnit.MicrovoltPerHour, 4.2)] + [InlineData("en-US", "4.2 µV/μs", ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond, 4.2)] + [InlineData("en-US", "4.2 µV/min", ElectricPotentialChangeRateUnit.MicrovoltPerMinute, 4.2)] + [InlineData("en-US", "4.2 µV/s", ElectricPotentialChangeRateUnit.MicrovoltPerSecond, 4.2)] + [InlineData("en-US", "4.2 mV/h", ElectricPotentialChangeRateUnit.MillivoltPerHour, 4.2)] + [InlineData("en-US", "4.2 mV/μs", ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond, 4.2)] + [InlineData("en-US", "4.2 mV/min", ElectricPotentialChangeRateUnit.MillivoltPerMinute, 4.2)] + [InlineData("en-US", "4.2 mV/s", ElectricPotentialChangeRateUnit.MillivoltPerSecond, 4.2)] + [InlineData("en-US", "4.2 V/h", ElectricPotentialChangeRateUnit.VoltPerHour, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = ElectricPotentialChangeRate.Parse("1 kV/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilovoltsPerHour, KilovoltsPerHourTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.KilovoltPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotentialChangeRate.Parse("1 kV/μs", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilovoltsPerMicrosecond, KilovoltsPerMicrosecondTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotentialChangeRate.Parse("1 kV/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilovoltsPerMinute, KilovoltsPerMinuteTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.KilovoltPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotentialChangeRate.Parse("1 kV/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilovoltsPerSecond, KilovoltsPerSecondTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.KilovoltPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotentialChangeRate.Parse("1 MV/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegavoltsPerHour, MegavoltsPerHourTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MegavoltPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotentialChangeRate.Parse("1 MV/μs", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegavoltsPerMicrosecond, MegavoltsPerMicrosecondTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotentialChangeRate.Parse("1 MV/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegavoltsPerMinute, MegavoltsPerMinuteTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MegavoltPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotentialChangeRate.Parse("1 MV/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegavoltsPerSecond, MegavoltsPerSecondTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MegavoltPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotentialChangeRate.Parse("1 µV/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrovoltsPerHour, MicrovoltsPerHourTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MicrovoltPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotentialChangeRate.Parse("1 µV/μs", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrovoltsPerMicrosecond, MicrovoltsPerMicrosecondTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotentialChangeRate.Parse("1 µV/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrovoltsPerMinute, MicrovoltsPerMinuteTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MicrovoltPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotentialChangeRate.Parse("1 µV/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrovoltsPerSecond, MicrovoltsPerSecondTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MicrovoltPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotentialChangeRate.Parse("1 mV/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillivoltsPerHour, MillivoltsPerHourTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MillivoltPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotentialChangeRate.Parse("1 mV/μs", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillivoltsPerMicrosecond, MillivoltsPerMicrosecondTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotentialChangeRate.Parse("1 mV/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillivoltsPerMinute, MillivoltsPerMinuteTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MillivoltPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotentialChangeRate.Parse("1 mV/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillivoltsPerSecond, MillivoltsPerSecondTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MillivoltPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotentialChangeRate.Parse("1 V/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.VoltsPerHour, VoltsPerHourTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.VoltPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotentialChangeRate.Parse("1 V/μs", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.VoltsPerMicrosecond, VoltsPerMicrosecondTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.VoltPerMicrosecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotentialChangeRate.Parse("1 V/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.VoltsPerMinute, VoltsPerMinuteTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.VoltPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotentialChangeRate.Parse("1 V/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.VoltsPerSecond, VoltsPerSecondTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.VoltPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ElectricPotentialChangeRate.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 kV/h", ElectricPotentialChangeRateUnit.KilovoltPerHour, 4.2)] + [InlineData("en-US", "4.2 kV/μs", ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond, 4.2)] + [InlineData("en-US", "4.2 kV/min", ElectricPotentialChangeRateUnit.KilovoltPerMinute, 4.2)] + [InlineData("en-US", "4.2 kV/s", ElectricPotentialChangeRateUnit.KilovoltPerSecond, 4.2)] + [InlineData("en-US", "4.2 MV/h", ElectricPotentialChangeRateUnit.MegavoltPerHour, 4.2)] + [InlineData("en-US", "4.2 MV/μs", ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond, 4.2)] + [InlineData("en-US", "4.2 MV/min", ElectricPotentialChangeRateUnit.MegavoltPerMinute, 4.2)] + [InlineData("en-US", "4.2 MV/s", ElectricPotentialChangeRateUnit.MegavoltPerSecond, 4.2)] + [InlineData("en-US", "4.2 µV/h", ElectricPotentialChangeRateUnit.MicrovoltPerHour, 4.2)] + [InlineData("en-US", "4.2 µV/μs", ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond, 4.2)] + [InlineData("en-US", "4.2 µV/min", ElectricPotentialChangeRateUnit.MicrovoltPerMinute, 4.2)] + [InlineData("en-US", "4.2 µV/s", ElectricPotentialChangeRateUnit.MicrovoltPerSecond, 4.2)] + [InlineData("en-US", "4.2 mV/h", ElectricPotentialChangeRateUnit.MillivoltPerHour, 4.2)] + [InlineData("en-US", "4.2 mV/μs", ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond, 4.2)] + [InlineData("en-US", "4.2 mV/min", ElectricPotentialChangeRateUnit.MillivoltPerMinute, 4.2)] + [InlineData("en-US", "4.2 mV/s", ElectricPotentialChangeRateUnit.MillivoltPerSecond, 4.2)] + [InlineData("en-US", "4.2 V/h", ElectricPotentialChangeRateUnit.VoltPerHour, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(ElectricPotentialChangeRate.TryParse("1 kV/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilovoltsPerHour, KilovoltsPerHourTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.KilovoltPerHour, parsed.Unit); - } - - { - Assert.True(ElectricPotentialChangeRate.TryParse("1 kV/μs", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilovoltsPerMicrosecond, KilovoltsPerMicrosecondTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond, parsed.Unit); - } - - { - Assert.True(ElectricPotentialChangeRate.TryParse("1 kV/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilovoltsPerMinute, KilovoltsPerMinuteTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.KilovoltPerMinute, parsed.Unit); - } - - { - Assert.True(ElectricPotentialChangeRate.TryParse("1 kV/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilovoltsPerSecond, KilovoltsPerSecondTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.KilovoltPerSecond, parsed.Unit); - } - - { - Assert.True(ElectricPotentialChangeRate.TryParse("1 µV/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrovoltsPerHour, MicrovoltsPerHourTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MicrovoltPerHour, parsed.Unit); - } - - { - Assert.True(ElectricPotentialChangeRate.TryParse("1 µV/μs", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrovoltsPerMicrosecond, MicrovoltsPerMicrosecondTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond, parsed.Unit); - } - - { - Assert.True(ElectricPotentialChangeRate.TryParse("1 µV/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrovoltsPerMinute, MicrovoltsPerMinuteTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MicrovoltPerMinute, parsed.Unit); - } - - { - Assert.True(ElectricPotentialChangeRate.TryParse("1 µV/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrovoltsPerSecond, MicrovoltsPerSecondTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.MicrovoltPerSecond, parsed.Unit); - } - - { - Assert.True(ElectricPotentialChangeRate.TryParse("1 V/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.VoltsPerHour, VoltsPerHourTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.VoltPerHour, parsed.Unit); - } - - { - Assert.True(ElectricPotentialChangeRate.TryParse("1 V/μs", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.VoltsPerMicrosecond, VoltsPerMicrosecondTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.VoltPerMicrosecond, parsed.Unit); - } - - { - Assert.True(ElectricPotentialChangeRate.TryParse("1 V/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.VoltsPerMinute, VoltsPerMinuteTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.VoltPerMinute, parsed.Unit); - } - - { - Assert.True(ElectricPotentialChangeRate.TryParse("1 V/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.VoltsPerSecond, VoltsPerSecondTolerance); - Assert.Equal(ElectricPotentialChangeRateUnit.VoltPerSecond, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ElectricPotentialChangeRate.TryParse(quantityString, out ElectricPotentialChangeRate parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -905,6 +759,46 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Electr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ElectricPotentialChangeRateUnit.KilovoltPerHour, "kV/h")] + [InlineData("en-US", ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond, "kV/μs")] + [InlineData("en-US", ElectricPotentialChangeRateUnit.KilovoltPerMinute, "kV/min")] + [InlineData("en-US", ElectricPotentialChangeRateUnit.KilovoltPerSecond, "kV/s")] + [InlineData("en-US", ElectricPotentialChangeRateUnit.MegavoltPerHour, "MV/h")] + [InlineData("en-US", ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond, "MV/μs")] + [InlineData("en-US", ElectricPotentialChangeRateUnit.MegavoltPerMinute, "MV/min")] + [InlineData("en-US", ElectricPotentialChangeRateUnit.MegavoltPerSecond, "MV/s")] + [InlineData("en-US", ElectricPotentialChangeRateUnit.MicrovoltPerHour, "µV/h")] + [InlineData("en-US", ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond, "µV/μs")] + [InlineData("en-US", ElectricPotentialChangeRateUnit.MicrovoltPerMinute, "µV/min")] + [InlineData("en-US", ElectricPotentialChangeRateUnit.MicrovoltPerSecond, "µV/s")] + [InlineData("en-US", ElectricPotentialChangeRateUnit.MillivoltPerHour, "mV/h")] + [InlineData("en-US", ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond, "mV/μs")] + [InlineData("en-US", ElectricPotentialChangeRateUnit.MillivoltPerMinute, "mV/min")] + [InlineData("en-US", ElectricPotentialChangeRateUnit.MillivoltPerSecond, "mV/s")] + [InlineData("en-US", ElectricPotentialChangeRateUnit.VoltPerHour, "V/h")] + [InlineData("en-US", ElectricPotentialChangeRateUnit.VoltPerMicrosecond, "V/μs")] + [InlineData("en-US", ElectricPotentialChangeRateUnit.VoltPerMinute, "V/min")] + [InlineData("en-US", ElectricPotentialChangeRateUnit.VoltPerSecond, "V/s")] + public void GetAbbreviationForCulture(string culture, ElectricPotentialChangeRateUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ElectricPotentialChangeRate.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ElectricPotentialChangeRate.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ElectricPotentialChangeRate.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricPotentialChangeRateUnit unit) @@ -935,6 +829,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); }); } @@ -958,51 +853,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] @@ -1048,8 +945,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); @@ -1086,23 +981,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = ElectricPotentialChangeRate.FromVoltsPerSecond(1); - Assert.True(v.Equals(ElectricPotentialChangeRate.FromVoltsPerSecond(1), VoltsPerSecondTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ElectricPotentialChangeRate.Zero, VoltsPerSecondTolerance, ComparisonType.Relative)); - Assert.True(ElectricPotentialChangeRate.FromVoltsPerSecond(100).Equals(ElectricPotentialChangeRate.FromVoltsPerSecond(120), 0.3, ComparisonType.Relative)); - Assert.False(ElectricPotentialChangeRate.FromVoltsPerSecond(100).Equals(ElectricPotentialChangeRate.FromVoltsPerSecond(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = ElectricPotentialChangeRate.FromVoltsPerSecond(1); - Assert.Throws(() => v.Equals(ElectricPotentialChangeRate.FromVoltsPerSecond(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1117,6 +995,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(voltpersecond.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = ElectricPotentialChangeRate.FromVoltsPerSecond(1); + var negativeTolerance = ElectricPotentialChangeRate.FromVoltsPerSecond(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1133,6 +1037,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() { @@ -1229,158 +1145,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSecond(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSecond(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSecond(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSecond(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSecond(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSecond(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSecond(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ElectricPotentialChangeRate))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSecond(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricPotentialChangeRateUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSecond(1.0); - Assert.Equal(ElectricPotentialChangeRate.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSecond(1.0); - Assert.Equal(ElectricPotentialChangeRate.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSecond(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ElectricPotentialChangeRate.FromVoltsPerSecond(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ElectricPotentialChangeRate.FromVoltsPerSecond(1.0); - Assert.Equal(new {ElectricPotentialChangeRate.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 55f70751f1..4440d5cdcb 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialTestsBase.g.cs @@ -116,7 +116,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ElectricPotential(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -129,15 +129,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ElectricPotential_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ElectricPotentialUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ElectricPotential(1, ElectricPotentialUnit.Volt); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ElectricPotential.Zero, quantityInfo.Zero); Assert.Equal("ElectricPotential", quantityInfo.Name); + Assert.Equal(ElectricPotential.Zero, quantityInfo.Zero); + Assert.Equal(ElectricPotential.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ElectricPotential.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -156,27 +174,27 @@ public void VoltToElectricPotentialUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ElectricPotential.From(1, ElectricPotentialUnit.Kilovolt); - AssertEx.EqualTolerance(1, quantity00.Kilovolts, KilovoltsTolerance); + Assert.Equal(1, quantity00.Kilovolts); Assert.Equal(ElectricPotentialUnit.Kilovolt, quantity00.Unit); var quantity01 = ElectricPotential.From(1, ElectricPotentialUnit.Megavolt); - AssertEx.EqualTolerance(1, quantity01.Megavolts, MegavoltsTolerance); + Assert.Equal(1, quantity01.Megavolts); Assert.Equal(ElectricPotentialUnit.Megavolt, quantity01.Unit); var quantity02 = ElectricPotential.From(1, ElectricPotentialUnit.Microvolt); - AssertEx.EqualTolerance(1, quantity02.Microvolts, MicrovoltsTolerance); + Assert.Equal(1, quantity02.Microvolts); Assert.Equal(ElectricPotentialUnit.Microvolt, quantity02.Unit); var quantity03 = ElectricPotential.From(1, ElectricPotentialUnit.Millivolt); - AssertEx.EqualTolerance(1, quantity03.Millivolts, MillivoltsTolerance); + Assert.Equal(1, quantity03.Millivolts); Assert.Equal(ElectricPotentialUnit.Millivolt, quantity03.Unit); var quantity04 = ElectricPotential.From(1, ElectricPotentialUnit.Nanovolt); - AssertEx.EqualTolerance(1, quantity04.Nanovolts, NanovoltsTolerance); + Assert.Equal(1, quantity04.Nanovolts); Assert.Equal(ElectricPotentialUnit.Nanovolt, quantity04.Unit); var quantity05 = ElectricPotential.From(1, ElectricPotentialUnit.Volt); - AssertEx.EqualTolerance(1, quantity05.Volts, VoltsTolerance); + Assert.Equal(1, quantity05.Volts); Assert.Equal(ElectricPotentialUnit.Volt, quantity05.Unit); } @@ -317,146 +335,46 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 kV", ElectricPotentialUnit.Kilovolt, 4.2)] + [InlineData("en-US", "4.2 MV", ElectricPotentialUnit.Megavolt, 4.2)] + [InlineData("en-US", "4.2 µV", ElectricPotentialUnit.Microvolt, 4.2)] + [InlineData("en-US", "4.2 mV", ElectricPotentialUnit.Millivolt, 4.2)] + [InlineData("en-US", "4.2 nV", ElectricPotentialUnit.Nanovolt, 4.2)] + [InlineData("en-US", "4.2 V", ElectricPotentialUnit.Volt, 4.2)] + [InlineData("ru-RU", "4,2 кВ", ElectricPotentialUnit.Kilovolt, 4.2)] + [InlineData("ru-RU", "4,2 МВ", ElectricPotentialUnit.Megavolt, 4.2)] + [InlineData("ru-RU", "4,2 мкВ", ElectricPotentialUnit.Microvolt, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = ElectricPotential.Parse("1 kV", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilovolts, KilovoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Kilovolt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotential.Parse("1 кВ", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Kilovolts, KilovoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Kilovolt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotential.Parse("1 MV", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megavolts, MegavoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Megavolt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotential.Parse("1 МВ", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Megavolts, MegavoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Megavolt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotential.Parse("1 µV", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microvolts, MicrovoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Microvolt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotential.Parse("1 мкВ", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Microvolts, MicrovoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Microvolt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotential.Parse("1 mV", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millivolts, MillivoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Millivolt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotential.Parse("1 мВ", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Millivolts, MillivoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Millivolt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotential.Parse("1 nV", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanovolts, NanovoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Nanovolt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotential.Parse("1 нВ", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Nanovolts, NanovoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Nanovolt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotential.Parse("1 V", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Volts, VoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Volt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricPotential.Parse("1 В", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Volts, VoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Volt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ElectricPotential.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 kV", ElectricPotentialUnit.Kilovolt, 4.2)] + [InlineData("en-US", "4.2 MV", ElectricPotentialUnit.Megavolt, 4.2)] + [InlineData("en-US", "4.2 µV", ElectricPotentialUnit.Microvolt, 4.2)] + [InlineData("en-US", "4.2 mV", ElectricPotentialUnit.Millivolt, 4.2)] + [InlineData("en-US", "4.2 nV", ElectricPotentialUnit.Nanovolt, 4.2)] + [InlineData("en-US", "4.2 V", ElectricPotentialUnit.Volt, 4.2)] + [InlineData("ru-RU", "4,2 кВ", ElectricPotentialUnit.Kilovolt, 4.2)] + [InlineData("ru-RU", "4,2 МВ", ElectricPotentialUnit.Megavolt, 4.2)] + [InlineData("ru-RU", "4,2 мкВ", ElectricPotentialUnit.Microvolt, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(ElectricPotential.TryParse("1 kV", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilovolts, KilovoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Kilovolt, parsed.Unit); - } - - { - Assert.True(ElectricPotential.TryParse("1 кВ", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilovolts, KilovoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Kilovolt, parsed.Unit); - } - - { - Assert.True(ElectricPotential.TryParse("1 µV", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microvolts, MicrovoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Microvolt, parsed.Unit); - } - - { - Assert.True(ElectricPotential.TryParse("1 мкВ", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microvolts, MicrovoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Microvolt, parsed.Unit); - } - - { - Assert.True(ElectricPotential.TryParse("1 nV", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanovolts, NanovoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Nanovolt, parsed.Unit); - } - - { - Assert.True(ElectricPotential.TryParse("1 нВ", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanovolts, NanovoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Nanovolt, parsed.Unit); - } - - { - Assert.True(ElectricPotential.TryParse("1 V", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Volts, VoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Volt, parsed.Unit); - } - - { - Assert.True(ElectricPotential.TryParse("1 В", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Volts, VoltsTolerance); - Assert.Equal(ElectricPotentialUnit.Volt, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ElectricPotential.TryParse(quantityString, out ElectricPotential parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -597,6 +515,38 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Electr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ElectricPotentialUnit.Kilovolt, "kV")] + [InlineData("en-US", ElectricPotentialUnit.Megavolt, "MV")] + [InlineData("en-US", ElectricPotentialUnit.Microvolt, "µV")] + [InlineData("en-US", ElectricPotentialUnit.Millivolt, "mV")] + [InlineData("en-US", ElectricPotentialUnit.Nanovolt, "nV")] + [InlineData("en-US", ElectricPotentialUnit.Volt, "V")] + [InlineData("ru-RU", ElectricPotentialUnit.Kilovolt, "кВ")] + [InlineData("ru-RU", ElectricPotentialUnit.Megavolt, "МВ")] + [InlineData("ru-RU", ElectricPotentialUnit.Microvolt, "мкВ")] + [InlineData("ru-RU", ElectricPotentialUnit.Millivolt, "мВ")] + [InlineData("ru-RU", ElectricPotentialUnit.Nanovolt, "нВ")] + [InlineData("ru-RU", ElectricPotentialUnit.Volt, "В")] + public void GetAbbreviationForCulture(string culture, ElectricPotentialUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ElectricPotential.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ElectricPotential.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ElectricPotential.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricPotentialUnit unit) @@ -627,6 +577,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); }); } @@ -650,37 +601,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] @@ -726,8 +679,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); @@ -765,34 +716,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = ElectricPotential.FromVolts(1); - Assert.True(v.Equals(ElectricPotential.FromVolts(1), VoltsTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ElectricPotential.Zero, VoltsTolerance, ComparisonType.Relative)); - Assert.True(ElectricPotential.FromVolts(100).Equals(ElectricPotential.FromVolts(120), 0.3, ComparisonType.Relative)); - Assert.False(ElectricPotential.FromVolts(100).Equals(ElectricPotential.FromVolts(120), 0.1, ComparisonType.Relative)); + ElectricPotential volt = ElectricPotential.FromVolts(1); + Assert.False(volt.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = ElectricPotential.FromVolts(1); - Assert.Throws(() => v.Equals(ElectricPotential.FromVolts(1), -1, ComparisonType.Relative)); + ElectricPotential volt = ElectricPotential.FromVolts(1); + Assert.False(volt.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - ElectricPotential volt = ElectricPotential.FromVolts(1); - Assert.False(volt.Equals(new object())); + var quantity = ElectricPotential.FromVolts(firstValue); + var otherQuantity = ElectricPotential.FromVolts(secondValue); + ElectricPotential maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - ElectricPotential volt = ElectricPotential.FromVolts(1); - Assert.False(volt.Equals(null)); + var quantity = ElectricPotential.FromVolts(1); + var negativeTolerance = ElectricPotential.FromVolts(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -811,6 +771,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() { @@ -879,158 +851,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ElectricPotential))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricPotentialUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal(ElectricPotential.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal(ElectricPotential.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal(new {ElectricPotential.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 b2dd71648e..e7767adc39 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricReactanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricReactanceTestsBase.g.cs @@ -124,7 +124,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ElectricReactance(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -137,15 +137,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ElectricReactance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ElectricReactanceUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ElectricReactance(1, ElectricReactanceUnit.Ohm); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ElectricReactance.Zero, quantityInfo.Zero); Assert.Equal("ElectricReactance", quantityInfo.Name); + Assert.Equal(ElectricReactance.Zero, quantityInfo.Zero); + Assert.Equal(ElectricReactance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ElectricReactance.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void ElectricReactanceInfo_CreateWithCustomUnitInfos() + { + ElectricReactanceUnit[] expectedUnits = [ElectricReactanceUnit.Ohm]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -166,35 +184,35 @@ public void OhmToElectricReactanceUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ElectricReactance.From(1, ElectricReactanceUnit.Gigaohm); - AssertEx.EqualTolerance(1, quantity00.Gigaohms, GigaohmsTolerance); + Assert.Equal(1, quantity00.Gigaohms); Assert.Equal(ElectricReactanceUnit.Gigaohm, quantity00.Unit); var quantity01 = ElectricReactance.From(1, ElectricReactanceUnit.Kiloohm); - AssertEx.EqualTolerance(1, quantity01.Kiloohms, KiloohmsTolerance); + Assert.Equal(1, quantity01.Kiloohms); Assert.Equal(ElectricReactanceUnit.Kiloohm, quantity01.Unit); var quantity02 = ElectricReactance.From(1, ElectricReactanceUnit.Megaohm); - AssertEx.EqualTolerance(1, quantity02.Megaohms, MegaohmsTolerance); + Assert.Equal(1, quantity02.Megaohms); Assert.Equal(ElectricReactanceUnit.Megaohm, quantity02.Unit); var quantity03 = ElectricReactance.From(1, ElectricReactanceUnit.Microohm); - AssertEx.EqualTolerance(1, quantity03.Microohms, MicroohmsTolerance); + Assert.Equal(1, quantity03.Microohms); Assert.Equal(ElectricReactanceUnit.Microohm, quantity03.Unit); var quantity04 = ElectricReactance.From(1, ElectricReactanceUnit.Milliohm); - AssertEx.EqualTolerance(1, quantity04.Milliohms, MilliohmsTolerance); + Assert.Equal(1, quantity04.Milliohms); Assert.Equal(ElectricReactanceUnit.Milliohm, quantity04.Unit); var quantity05 = ElectricReactance.From(1, ElectricReactanceUnit.Nanoohm); - AssertEx.EqualTolerance(1, quantity05.Nanoohms, NanoohmsTolerance); + Assert.Equal(1, quantity05.Nanoohms); Assert.Equal(ElectricReactanceUnit.Nanoohm, quantity05.Unit); var quantity06 = ElectricReactance.From(1, ElectricReactanceUnit.Ohm); - AssertEx.EqualTolerance(1, quantity06.Ohms, OhmsTolerance); + Assert.Equal(1, quantity06.Ohms); Assert.Equal(ElectricReactanceUnit.Ohm, quantity06.Unit); var quantity07 = ElectricReactance.From(1, ElectricReactanceUnit.Teraohm); - AssertEx.EqualTolerance(1, quantity07.Teraohms, TeraohmsTolerance); + Assert.Equal(1, quantity07.Teraohms); Assert.Equal(ElectricReactanceUnit.Teraohm, quantity07.Unit); } @@ -337,106 +355,38 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 GΩ", ElectricReactanceUnit.Gigaohm, 4.2)] + [InlineData("en-US", "4.2 kΩ", ElectricReactanceUnit.Kiloohm, 4.2)] + [InlineData("en-US", "4.2 MΩ", ElectricReactanceUnit.Megaohm, 4.2)] + [InlineData("en-US", "4.2 µΩ", ElectricReactanceUnit.Microohm, 4.2)] + [InlineData("en-US", "4.2 mΩ", ElectricReactanceUnit.Milliohm, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = ElectricReactance.Parse("1 GΩ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Gigaohms, GigaohmsTolerance); - Assert.Equal(ElectricReactanceUnit.Gigaohm, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricReactance.Parse("1 kΩ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kiloohms, KiloohmsTolerance); - Assert.Equal(ElectricReactanceUnit.Kiloohm, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricReactance.Parse("1 MΩ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megaohms, MegaohmsTolerance); - Assert.Equal(ElectricReactanceUnit.Megaohm, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricReactance.Parse("1 µΩ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microohms, MicroohmsTolerance); - Assert.Equal(ElectricReactanceUnit.Microohm, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricReactance.Parse("1 mΩ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Milliohms, MilliohmsTolerance); - Assert.Equal(ElectricReactanceUnit.Milliohm, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricReactance.Parse("1 nΩ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanoohms, NanoohmsTolerance); - Assert.Equal(ElectricReactanceUnit.Nanoohm, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricReactance.Parse("1 Ω", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Ohms, OhmsTolerance); - Assert.Equal(ElectricReactanceUnit.Ohm, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricReactance.Parse("1 TΩ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Teraohms, TeraohmsTolerance); - Assert.Equal(ElectricReactanceUnit.Teraohm, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ElectricReactance.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 GΩ", ElectricReactanceUnit.Gigaohm, 4.2)] + [InlineData("en-US", "4.2 kΩ", ElectricReactanceUnit.Kiloohm, 4.2)] + [InlineData("en-US", "4.2 MΩ", ElectricReactanceUnit.Megaohm, 4.2)] + [InlineData("en-US", "4.2 µΩ", ElectricReactanceUnit.Microohm, 4.2)] + [InlineData("en-US", "4.2 mΩ", ElectricReactanceUnit.Milliohm, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(ElectricReactance.TryParse("1 GΩ", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gigaohms, GigaohmsTolerance); - Assert.Equal(ElectricReactanceUnit.Gigaohm, parsed.Unit); - } - - { - Assert.True(ElectricReactance.TryParse("1 kΩ", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kiloohms, KiloohmsTolerance); - Assert.Equal(ElectricReactanceUnit.Kiloohm, parsed.Unit); - } - - { - Assert.True(ElectricReactance.TryParse("1 µΩ", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microohms, MicroohmsTolerance); - Assert.Equal(ElectricReactanceUnit.Microohm, parsed.Unit); - } - - { - Assert.True(ElectricReactance.TryParse("1 nΩ", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanoohms, NanoohmsTolerance); - Assert.Equal(ElectricReactanceUnit.Nanoohm, parsed.Unit); - } - - { - Assert.True(ElectricReactance.TryParse("1 Ω", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Ohms, OhmsTolerance); - Assert.Equal(ElectricReactanceUnit.Ohm, parsed.Unit); - } - - { - Assert.True(ElectricReactance.TryParse("1 TΩ", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Teraohms, TeraohmsTolerance); - Assert.Equal(ElectricReactanceUnit.Teraohm, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ElectricReactance.TryParse(quantityString, out ElectricReactance parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -569,6 +519,34 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Electr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ElectricReactanceUnit.Gigaohm, "GΩ")] + [InlineData("en-US", ElectricReactanceUnit.Kiloohm, "kΩ")] + [InlineData("en-US", ElectricReactanceUnit.Megaohm, "MΩ")] + [InlineData("en-US", ElectricReactanceUnit.Microohm, "µΩ")] + [InlineData("en-US", ElectricReactanceUnit.Milliohm, "mΩ")] + [InlineData("en-US", ElectricReactanceUnit.Nanoohm, "nΩ")] + [InlineData("en-US", ElectricReactanceUnit.Ohm, "Ω")] + [InlineData("en-US", ElectricReactanceUnit.Teraohm, "TΩ")] + public void GetAbbreviationForCulture(string culture, ElectricReactanceUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ElectricReactance.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ElectricReactance.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ElectricReactance.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricReactanceUnit unit) @@ -599,6 +577,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); }); } @@ -622,39 +601,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] @@ -700,8 +681,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); @@ -739,34 +718,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = ElectricReactance.FromOhms(1); - Assert.True(v.Equals(ElectricReactance.FromOhms(1), OhmsTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ElectricReactance.Zero, OhmsTolerance, ComparisonType.Relative)); - Assert.True(ElectricReactance.FromOhms(100).Equals(ElectricReactance.FromOhms(120), 0.3, ComparisonType.Relative)); - Assert.False(ElectricReactance.FromOhms(100).Equals(ElectricReactance.FromOhms(120), 0.1, ComparisonType.Relative)); + ElectricReactance ohm = ElectricReactance.FromOhms(1); + Assert.False(ohm.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = ElectricReactance.FromOhms(1); - Assert.Throws(() => v.Equals(ElectricReactance.FromOhms(1), -1, ComparisonType.Relative)); + ElectricReactance ohm = ElectricReactance.FromOhms(1); + Assert.False(ohm.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - ElectricReactance ohm = ElectricReactance.FromOhms(1); - Assert.False(ohm.Equals(new object())); + var quantity = ElectricReactance.FromOhms(firstValue); + var otherQuantity = ElectricReactance.FromOhms(secondValue); + ElectricReactance maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - ElectricReactance ohm = ElectricReactance.FromOhms(1); - Assert.False(ohm.Equals(null)); + var quantity = ElectricReactance.FromOhms(1); + var negativeTolerance = ElectricReactance.FromOhms(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -785,6 +773,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() { @@ -857,158 +857,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ElectricReactance.FromOhms(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ElectricReactance.FromOhms(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ElectricReactance.FromOhms(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ElectricReactance.FromOhms(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ElectricReactance.FromOhms(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ElectricReactance.FromOhms(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ElectricReactance.FromOhms(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ElectricReactance.FromOhms(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ElectricReactance.FromOhms(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ElectricReactance.FromOhms(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ElectricReactance.FromOhms(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ElectricReactance.FromOhms(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ElectricReactance.FromOhms(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ElectricReactance.FromOhms(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ElectricReactance.FromOhms(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ElectricReactance.FromOhms(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ElectricReactance))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ElectricReactance.FromOhms(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricReactanceUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ElectricReactance.FromOhms(1.0); - Assert.Equal(ElectricReactance.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ElectricReactance.FromOhms(1.0); - Assert.Equal(ElectricReactance.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ElectricReactance.FromOhms(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ElectricReactance.FromOhms(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ElectricReactance.FromOhms(1.0); - Assert.Equal(new {ElectricReactance.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 556f310dca..781d304b03 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricReactiveEnergyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricReactiveEnergyTestsBase.g.cs @@ -104,7 +104,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ElectricReactiveEnergy(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -117,15 +117,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ElectricReactiveEnergy_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ElectricReactiveEnergyUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ElectricReactiveEnergy(1, ElectricReactiveEnergyUnit.VoltampereReactiveHour); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ElectricReactiveEnergy.Zero, quantityInfo.Zero); Assert.Equal("ElectricReactiveEnergy", quantityInfo.Name); + Assert.Equal(ElectricReactiveEnergy.Zero, quantityInfo.Zero); + Assert.Equal(ElectricReactiveEnergy.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ElectricReactiveEnergy.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void ElectricReactiveEnergyInfo_CreateWithCustomUnitInfos() + { + ElectricReactiveEnergyUnit[] expectedUnits = [ElectricReactiveEnergyUnit.VoltampereReactiveHour]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -141,15 +159,15 @@ public void VoltampereReactiveHourToElectricReactiveEnergyUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ElectricReactiveEnergy.From(1, ElectricReactiveEnergyUnit.KilovoltampereReactiveHour); - AssertEx.EqualTolerance(1, quantity00.KilovoltampereReactiveHours, KilovoltampereReactiveHoursTolerance); + Assert.Equal(1, quantity00.KilovoltampereReactiveHours); Assert.Equal(ElectricReactiveEnergyUnit.KilovoltampereReactiveHour, quantity00.Unit); var quantity01 = ElectricReactiveEnergy.From(1, ElectricReactiveEnergyUnit.MegavoltampereReactiveHour); - AssertEx.EqualTolerance(1, quantity01.MegavoltampereReactiveHours, MegavoltampereReactiveHoursTolerance); + Assert.Equal(1, quantity01.MegavoltampereReactiveHours); Assert.Equal(ElectricReactiveEnergyUnit.MegavoltampereReactiveHour, quantity01.Unit); var quantity02 = ElectricReactiveEnergy.From(1, ElectricReactiveEnergyUnit.VoltampereReactiveHour); - AssertEx.EqualTolerance(1, quantity02.VoltampereReactiveHours, VoltampereReactiveHoursTolerance); + Assert.Equal(1, quantity02.VoltampereReactiveHours); Assert.Equal(ElectricReactiveEnergyUnit.VoltampereReactiveHour, quantity02.Unit); } @@ -287,53 +305,28 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [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, decimal expectedValue) { - try - { - var parsed = ElectricReactiveEnergy.Parse("1 kvarh", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilovoltampereReactiveHours, KilovoltampereReactiveHoursTolerance); - Assert.Equal(ElectricReactiveEnergyUnit.KilovoltampereReactiveHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricReactiveEnergy.Parse("1 Mvarh", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegavoltampereReactiveHours, MegavoltampereReactiveHoursTolerance); - Assert.Equal(ElectricReactiveEnergyUnit.MegavoltampereReactiveHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricReactiveEnergy.Parse("1 varh", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.VoltampereReactiveHours, VoltampereReactiveHoursTolerance); - Assert.Equal(ElectricReactiveEnergyUnit.VoltampereReactiveHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ElectricReactiveEnergy.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [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, decimal expectedValue) { - { - Assert.True(ElectricReactiveEnergy.TryParse("1 kvarh", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilovoltampereReactiveHours, KilovoltampereReactiveHoursTolerance); - Assert.Equal(ElectricReactiveEnergyUnit.KilovoltampereReactiveHour, parsed.Unit); - } - - { - Assert.True(ElectricReactiveEnergy.TryParse("1 Mvarh", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegavoltampereReactiveHours, MegavoltampereReactiveHoursTolerance); - Assert.Equal(ElectricReactiveEnergyUnit.MegavoltampereReactiveHour, parsed.Unit); - } - - { - Assert.True(ElectricReactiveEnergy.TryParse("1 varh", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.VoltampereReactiveHours, VoltampereReactiveHoursTolerance); - Assert.Equal(ElectricReactiveEnergyUnit.VoltampereReactiveHour, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ElectricReactiveEnergy.TryParse(quantityString, out ElectricReactiveEnergy parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -426,6 +419,29 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Electr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ElectricReactiveEnergyUnit.KilovoltampereReactiveHour, "kvarh")] + [InlineData("en-US", ElectricReactiveEnergyUnit.MegavoltampereReactiveHour, "Mvarh")] + [InlineData("en-US", ElectricReactiveEnergyUnit.VoltampereReactiveHour, "varh")] + public void GetAbbreviationForCulture(string culture, ElectricReactiveEnergyUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ElectricReactiveEnergy.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ElectricReactiveEnergy.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ElectricReactiveEnergy.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricReactiveEnergyUnit unit) @@ -456,6 +472,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); }); } @@ -479,34 +496,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] @@ -552,8 +571,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); @@ -591,34 +608,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = ElectricReactiveEnergy.FromVoltampereReactiveHours(1); - Assert.True(v.Equals(ElectricReactiveEnergy.FromVoltampereReactiveHours(1), VoltampereReactiveHoursTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ElectricReactiveEnergy.Zero, VoltampereReactiveHoursTolerance, ComparisonType.Relative)); - Assert.True(ElectricReactiveEnergy.FromVoltampereReactiveHours(100).Equals(ElectricReactiveEnergy.FromVoltampereReactiveHours(120), 0.3, ComparisonType.Relative)); - Assert.False(ElectricReactiveEnergy.FromVoltampereReactiveHours(100).Equals(ElectricReactiveEnergy.FromVoltampereReactiveHours(120), 0.1, ComparisonType.Relative)); + ElectricReactiveEnergy voltamperereactivehour = ElectricReactiveEnergy.FromVoltampereReactiveHours(1); + Assert.False(voltamperereactivehour.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = ElectricReactiveEnergy.FromVoltampereReactiveHours(1); - Assert.Throws(() => v.Equals(ElectricReactiveEnergy.FromVoltampereReactiveHours(1), -1, ComparisonType.Relative)); + ElectricReactiveEnergy voltamperereactivehour = ElectricReactiveEnergy.FromVoltampereReactiveHours(1); + Assert.False(voltamperereactivehour.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - ElectricReactiveEnergy voltamperereactivehour = ElectricReactiveEnergy.FromVoltampereReactiveHours(1); - Assert.False(voltamperereactivehour.Equals(new object())); + var quantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(firstValue); + var otherQuantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(secondValue); + ElectricReactiveEnergy maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - ElectricReactiveEnergy voltamperereactivehour = ElectricReactiveEnergy.FromVoltampereReactiveHours(1); - Assert.False(voltamperereactivehour.Equals(null)); + var quantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(1); + var negativeTolerance = ElectricReactiveEnergy.FromVoltampereReactiveHours(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -637,6 +663,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() { @@ -699,158 +737,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ElectricReactiveEnergy))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricReactiveEnergyUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal(ElectricReactiveEnergy.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal(ElectricReactiveEnergy.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal(new {ElectricReactiveEnergy.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 72beb0eccf..2262bea66c 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricReactivePowerTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricReactivePowerTestsBase.g.cs @@ -108,7 +108,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ElectricReactivePower(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -121,15 +121,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ElectricReactivePower_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ElectricReactivePowerUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ElectricReactivePower(1, ElectricReactivePowerUnit.VoltampereReactive); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ElectricReactivePower.Zero, quantityInfo.Zero); Assert.Equal("ElectricReactivePower", quantityInfo.Name); + Assert.Equal(ElectricReactivePower.Zero, quantityInfo.Zero); + Assert.Equal(ElectricReactivePower.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ElectricReactivePower.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void ElectricReactivePowerInfo_CreateWithCustomUnitInfos() + { + ElectricReactivePowerUnit[] expectedUnits = [ElectricReactivePowerUnit.VoltampereReactive]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -146,19 +164,19 @@ public void VoltampereReactiveToElectricReactivePowerUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ElectricReactivePower.From(1, ElectricReactivePowerUnit.GigavoltampereReactive); - AssertEx.EqualTolerance(1, quantity00.GigavoltamperesReactive, GigavoltamperesReactiveTolerance); + Assert.Equal(1, quantity00.GigavoltamperesReactive); Assert.Equal(ElectricReactivePowerUnit.GigavoltampereReactive, quantity00.Unit); var quantity01 = ElectricReactivePower.From(1, ElectricReactivePowerUnit.KilovoltampereReactive); - AssertEx.EqualTolerance(1, quantity01.KilovoltamperesReactive, KilovoltamperesReactiveTolerance); + Assert.Equal(1, quantity01.KilovoltamperesReactive); Assert.Equal(ElectricReactivePowerUnit.KilovoltampereReactive, quantity01.Unit); var quantity02 = ElectricReactivePower.From(1, ElectricReactivePowerUnit.MegavoltampereReactive); - AssertEx.EqualTolerance(1, quantity02.MegavoltamperesReactive, MegavoltamperesReactiveTolerance); + Assert.Equal(1, quantity02.MegavoltamperesReactive); Assert.Equal(ElectricReactivePowerUnit.MegavoltampereReactive, quantity02.Unit); var quantity03 = ElectricReactivePower.From(1, ElectricReactivePowerUnit.VoltampereReactive); - AssertEx.EqualTolerance(1, quantity03.VoltamperesReactive, VoltamperesReactiveTolerance); + Assert.Equal(1, quantity03.VoltamperesReactive); Assert.Equal(ElectricReactivePowerUnit.VoltampereReactive, quantity03.Unit); } @@ -297,66 +315,30 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 Gvar", ElectricReactivePowerUnit.GigavoltampereReactive, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = ElectricReactivePower.Parse("1 Gvar", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GigavoltamperesReactive, GigavoltamperesReactiveTolerance); - Assert.Equal(ElectricReactivePowerUnit.GigavoltampereReactive, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricReactivePower.Parse("1 kvar", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilovoltamperesReactive, KilovoltamperesReactiveTolerance); - Assert.Equal(ElectricReactivePowerUnit.KilovoltampereReactive, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricReactivePower.Parse("1 Mvar", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegavoltamperesReactive, MegavoltamperesReactiveTolerance); - Assert.Equal(ElectricReactivePowerUnit.MegavoltampereReactive, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricReactivePower.Parse("1 var", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.VoltamperesReactive, VoltamperesReactiveTolerance); - Assert.Equal(ElectricReactivePowerUnit.VoltampereReactive, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ElectricReactivePower.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 Gvar", ElectricReactivePowerUnit.GigavoltampereReactive, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(ElectricReactivePower.TryParse("1 Gvar", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigavoltamperesReactive, GigavoltamperesReactiveTolerance); - Assert.Equal(ElectricReactivePowerUnit.GigavoltampereReactive, parsed.Unit); - } - - { - Assert.True(ElectricReactivePower.TryParse("1 kvar", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilovoltamperesReactive, KilovoltamperesReactiveTolerance); - Assert.Equal(ElectricReactivePowerUnit.KilovoltampereReactive, parsed.Unit); - } - - { - Assert.True(ElectricReactivePower.TryParse("1 Mvar", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegavoltamperesReactive, MegavoltamperesReactiveTolerance); - Assert.Equal(ElectricReactivePowerUnit.MegavoltampereReactive, parsed.Unit); - } - - { - Assert.True(ElectricReactivePower.TryParse("1 var", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.VoltamperesReactive, VoltamperesReactiveTolerance); - Assert.Equal(ElectricReactivePowerUnit.VoltampereReactive, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ElectricReactivePower.TryParse(quantityString, out ElectricReactivePower parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -457,6 +439,30 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Electr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ElectricReactivePowerUnit.GigavoltampereReactive, "Gvar")] + [InlineData("en-US", ElectricReactivePowerUnit.KilovoltampereReactive, "kvar")] + [InlineData("en-US", ElectricReactivePowerUnit.MegavoltampereReactive, "Mvar")] + [InlineData("en-US", ElectricReactivePowerUnit.VoltampereReactive, "var")] + public void GetAbbreviationForCulture(string culture, ElectricReactivePowerUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ElectricReactivePower.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ElectricReactivePower.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ElectricReactivePower.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricReactivePowerUnit unit) @@ -487,6 +493,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); }); } @@ -510,35 +517,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] @@ -584,8 +593,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); @@ -623,34 +630,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = ElectricReactivePower.FromVoltamperesReactive(1); - Assert.True(v.Equals(ElectricReactivePower.FromVoltamperesReactive(1), VoltamperesReactiveTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ElectricReactivePower.Zero, VoltamperesReactiveTolerance, ComparisonType.Relative)); - Assert.True(ElectricReactivePower.FromVoltamperesReactive(100).Equals(ElectricReactivePower.FromVoltamperesReactive(120), 0.3, ComparisonType.Relative)); - Assert.False(ElectricReactivePower.FromVoltamperesReactive(100).Equals(ElectricReactivePower.FromVoltamperesReactive(120), 0.1, ComparisonType.Relative)); + ElectricReactivePower voltamperereactive = ElectricReactivePower.FromVoltamperesReactive(1); + Assert.False(voltamperereactive.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = ElectricReactivePower.FromVoltamperesReactive(1); - Assert.Throws(() => v.Equals(ElectricReactivePower.FromVoltamperesReactive(1), -1, ComparisonType.Relative)); + ElectricReactivePower voltamperereactive = ElectricReactivePower.FromVoltamperesReactive(1); + Assert.False(voltamperereactive.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - ElectricReactivePower voltamperereactive = ElectricReactivePower.FromVoltamperesReactive(1); - Assert.False(voltamperereactive.Equals(new object())); + var quantity = ElectricReactivePower.FromVoltamperesReactive(firstValue); + var otherQuantity = ElectricReactivePower.FromVoltamperesReactive(secondValue); + ElectricReactivePower maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - ElectricReactivePower voltamperereactive = ElectricReactivePower.FromVoltamperesReactive(1); - Assert.False(voltamperereactive.Equals(null)); + var quantity = ElectricReactivePower.FromVoltamperesReactive(1); + var negativeTolerance = ElectricReactivePower.FromVoltamperesReactive(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -669,6 +685,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() { @@ -733,158 +761,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ElectricReactivePower.FromVoltamperesReactive(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ElectricReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ElectricReactivePower.FromVoltamperesReactive(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ElectricReactivePower.FromVoltamperesReactive(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ElectricReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ElectricReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ElectricReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ElectricReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ElectricReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ElectricReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ElectricReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ElectricReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ElectricReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ElectricReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ElectricReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ElectricReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ElectricReactivePower))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ElectricReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricReactivePowerUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ElectricReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal(ElectricReactivePower.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ElectricReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal(ElectricReactivePower.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ElectricReactivePower.FromVoltamperesReactive(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ElectricReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ElectricReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal(new {ElectricReactivePower.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 07272d603e..1cc1965ca0 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistanceTestsBase.g.cs @@ -124,7 +124,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ElectricResistance(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -137,15 +137,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ElectricResistance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ElectricResistanceUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ElectricResistance(1, ElectricResistanceUnit.Ohm); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ElectricResistance.Zero, quantityInfo.Zero); Assert.Equal("ElectricResistance", quantityInfo.Name); + Assert.Equal(ElectricResistance.Zero, quantityInfo.Zero); + Assert.Equal(ElectricResistance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ElectricResistance.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void ElectricResistanceInfo_CreateWithCustomUnitInfos() + { + ElectricResistanceUnit[] expectedUnits = [ElectricResistanceUnit.Ohm]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -166,35 +184,35 @@ public void OhmToElectricResistanceUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ElectricResistance.From(1, ElectricResistanceUnit.Gigaohm); - AssertEx.EqualTolerance(1, quantity00.Gigaohms, GigaohmsTolerance); + Assert.Equal(1, quantity00.Gigaohms); Assert.Equal(ElectricResistanceUnit.Gigaohm, quantity00.Unit); var quantity01 = ElectricResistance.From(1, ElectricResistanceUnit.Kiloohm); - AssertEx.EqualTolerance(1, quantity01.Kiloohms, KiloohmsTolerance); + Assert.Equal(1, quantity01.Kiloohms); Assert.Equal(ElectricResistanceUnit.Kiloohm, quantity01.Unit); var quantity02 = ElectricResistance.From(1, ElectricResistanceUnit.Megaohm); - AssertEx.EqualTolerance(1, quantity02.Megaohms, MegaohmsTolerance); + Assert.Equal(1, quantity02.Megaohms); Assert.Equal(ElectricResistanceUnit.Megaohm, quantity02.Unit); var quantity03 = ElectricResistance.From(1, ElectricResistanceUnit.Microohm); - AssertEx.EqualTolerance(1, quantity03.Microohms, MicroohmsTolerance); + Assert.Equal(1, quantity03.Microohms); Assert.Equal(ElectricResistanceUnit.Microohm, quantity03.Unit); var quantity04 = ElectricResistance.From(1, ElectricResistanceUnit.Milliohm); - AssertEx.EqualTolerance(1, quantity04.Milliohms, MilliohmsTolerance); + Assert.Equal(1, quantity04.Milliohms); Assert.Equal(ElectricResistanceUnit.Milliohm, quantity04.Unit); var quantity05 = ElectricResistance.From(1, ElectricResistanceUnit.Nanoohm); - AssertEx.EqualTolerance(1, quantity05.Nanoohms, NanoohmsTolerance); + Assert.Equal(1, quantity05.Nanoohms); Assert.Equal(ElectricResistanceUnit.Nanoohm, quantity05.Unit); var quantity06 = ElectricResistance.From(1, ElectricResistanceUnit.Ohm); - AssertEx.EqualTolerance(1, quantity06.Ohms, OhmsTolerance); + Assert.Equal(1, quantity06.Ohms); Assert.Equal(ElectricResistanceUnit.Ohm, quantity06.Unit); var quantity07 = ElectricResistance.From(1, ElectricResistanceUnit.Teraohm); - AssertEx.EqualTolerance(1, quantity07.Teraohms, TeraohmsTolerance); + Assert.Equal(1, quantity07.Teraohms); Assert.Equal(ElectricResistanceUnit.Teraohm, quantity07.Unit); } @@ -337,106 +355,38 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 GΩ", ElectricResistanceUnit.Gigaohm, 4.2)] + [InlineData("en-US", "4.2 kΩ", ElectricResistanceUnit.Kiloohm, 4.2)] + [InlineData("en-US", "4.2 MΩ", ElectricResistanceUnit.Megaohm, 4.2)] + [InlineData("en-US", "4.2 µΩ", ElectricResistanceUnit.Microohm, 4.2)] + [InlineData("en-US", "4.2 mΩ", ElectricResistanceUnit.Milliohm, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = ElectricResistance.Parse("1 GΩ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Gigaohms, GigaohmsTolerance); - Assert.Equal(ElectricResistanceUnit.Gigaohm, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricResistance.Parse("1 kΩ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kiloohms, KiloohmsTolerance); - Assert.Equal(ElectricResistanceUnit.Kiloohm, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricResistance.Parse("1 MΩ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megaohms, MegaohmsTolerance); - Assert.Equal(ElectricResistanceUnit.Megaohm, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricResistance.Parse("1 µΩ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microohms, MicroohmsTolerance); - Assert.Equal(ElectricResistanceUnit.Microohm, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricResistance.Parse("1 mΩ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Milliohms, MilliohmsTolerance); - Assert.Equal(ElectricResistanceUnit.Milliohm, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricResistance.Parse("1 nΩ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanoohms, NanoohmsTolerance); - Assert.Equal(ElectricResistanceUnit.Nanoohm, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricResistance.Parse("1 Ω", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Ohms, OhmsTolerance); - Assert.Equal(ElectricResistanceUnit.Ohm, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricResistance.Parse("1 TΩ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Teraohms, TeraohmsTolerance); - Assert.Equal(ElectricResistanceUnit.Teraohm, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ElectricResistance.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 GΩ", ElectricResistanceUnit.Gigaohm, 4.2)] + [InlineData("en-US", "4.2 kΩ", ElectricResistanceUnit.Kiloohm, 4.2)] + [InlineData("en-US", "4.2 MΩ", ElectricResistanceUnit.Megaohm, 4.2)] + [InlineData("en-US", "4.2 µΩ", ElectricResistanceUnit.Microohm, 4.2)] + [InlineData("en-US", "4.2 mΩ", ElectricResistanceUnit.Milliohm, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(ElectricResistance.TryParse("1 GΩ", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gigaohms, GigaohmsTolerance); - Assert.Equal(ElectricResistanceUnit.Gigaohm, parsed.Unit); - } - - { - Assert.True(ElectricResistance.TryParse("1 kΩ", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kiloohms, KiloohmsTolerance); - Assert.Equal(ElectricResistanceUnit.Kiloohm, parsed.Unit); - } - - { - Assert.True(ElectricResistance.TryParse("1 µΩ", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microohms, MicroohmsTolerance); - Assert.Equal(ElectricResistanceUnit.Microohm, parsed.Unit); - } - - { - Assert.True(ElectricResistance.TryParse("1 nΩ", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanoohms, NanoohmsTolerance); - Assert.Equal(ElectricResistanceUnit.Nanoohm, parsed.Unit); - } - - { - Assert.True(ElectricResistance.TryParse("1 Ω", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Ohms, OhmsTolerance); - Assert.Equal(ElectricResistanceUnit.Ohm, parsed.Unit); - } - - { - Assert.True(ElectricResistance.TryParse("1 TΩ", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Teraohms, TeraohmsTolerance); - Assert.Equal(ElectricResistanceUnit.Teraohm, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ElectricResistance.TryParse(quantityString, out ElectricResistance parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -569,6 +519,34 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Electr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ElectricResistanceUnit.Gigaohm, "GΩ")] + [InlineData("en-US", ElectricResistanceUnit.Kiloohm, "kΩ")] + [InlineData("en-US", ElectricResistanceUnit.Megaohm, "MΩ")] + [InlineData("en-US", ElectricResistanceUnit.Microohm, "µΩ")] + [InlineData("en-US", ElectricResistanceUnit.Milliohm, "mΩ")] + [InlineData("en-US", ElectricResistanceUnit.Nanoohm, "nΩ")] + [InlineData("en-US", ElectricResistanceUnit.Ohm, "Ω")] + [InlineData("en-US", ElectricResistanceUnit.Teraohm, "TΩ")] + public void GetAbbreviationForCulture(string culture, ElectricResistanceUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ElectricResistance.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ElectricResistance.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ElectricResistance.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricResistanceUnit unit) @@ -599,6 +577,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); }); } @@ -622,39 +601,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] @@ -700,8 +681,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); @@ -739,34 +718,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = ElectricResistance.FromOhms(1); - Assert.True(v.Equals(ElectricResistance.FromOhms(1), OhmsTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ElectricResistance.Zero, OhmsTolerance, ComparisonType.Relative)); - Assert.True(ElectricResistance.FromOhms(100).Equals(ElectricResistance.FromOhms(120), 0.3, ComparisonType.Relative)); - Assert.False(ElectricResistance.FromOhms(100).Equals(ElectricResistance.FromOhms(120), 0.1, ComparisonType.Relative)); + ElectricResistance ohm = ElectricResistance.FromOhms(1); + Assert.False(ohm.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = ElectricResistance.FromOhms(1); - Assert.Throws(() => v.Equals(ElectricResistance.FromOhms(1), -1, ComparisonType.Relative)); + ElectricResistance ohm = ElectricResistance.FromOhms(1); + Assert.False(ohm.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - ElectricResistance ohm = ElectricResistance.FromOhms(1); - Assert.False(ohm.Equals(new object())); + var quantity = ElectricResistance.FromOhms(firstValue); + var otherQuantity = ElectricResistance.FromOhms(secondValue); + ElectricResistance maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - ElectricResistance ohm = ElectricResistance.FromOhms(1); - Assert.False(ohm.Equals(null)); + var quantity = ElectricResistance.FromOhms(1); + var negativeTolerance = ElectricResistance.FromOhms(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -785,6 +773,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() { @@ -857,158 +857,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ElectricResistance))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricResistanceUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal(ElectricResistance.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal(ElectricResistance.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal(new {ElectricResistance.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 bfd4b2e4ac..0d2eeb16c1 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistivityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistivityTestsBase.g.cs @@ -148,7 +148,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ElectricResistivity(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -161,15 +161,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ElectricResistivity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ElectricResistivityUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ElectricResistivity(1, ElectricResistivityUnit.OhmMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ElectricResistivity.Zero, quantityInfo.Zero); Assert.Equal("ElectricResistivity", quantityInfo.Name); + Assert.Equal(ElectricResistivity.Zero, quantityInfo.Zero); + Assert.Equal(ElectricResistivity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ElectricResistivity.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -196,59 +214,59 @@ public void OhmMeterToElectricResistivityUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ElectricResistivity.From(1, ElectricResistivityUnit.KiloohmCentimeter); - AssertEx.EqualTolerance(1, quantity00.KiloohmsCentimeter, KiloohmsCentimeterTolerance); + Assert.Equal(1, quantity00.KiloohmsCentimeter); Assert.Equal(ElectricResistivityUnit.KiloohmCentimeter, quantity00.Unit); var quantity01 = ElectricResistivity.From(1, ElectricResistivityUnit.KiloohmMeter); - AssertEx.EqualTolerance(1, quantity01.KiloohmMeters, KiloohmMetersTolerance); + Assert.Equal(1, quantity01.KiloohmMeters); Assert.Equal(ElectricResistivityUnit.KiloohmMeter, quantity01.Unit); var quantity02 = ElectricResistivity.From(1, ElectricResistivityUnit.MegaohmCentimeter); - AssertEx.EqualTolerance(1, quantity02.MegaohmsCentimeter, MegaohmsCentimeterTolerance); + Assert.Equal(1, quantity02.MegaohmsCentimeter); Assert.Equal(ElectricResistivityUnit.MegaohmCentimeter, quantity02.Unit); var quantity03 = ElectricResistivity.From(1, ElectricResistivityUnit.MegaohmMeter); - AssertEx.EqualTolerance(1, quantity03.MegaohmMeters, MegaohmMetersTolerance); + Assert.Equal(1, quantity03.MegaohmMeters); Assert.Equal(ElectricResistivityUnit.MegaohmMeter, quantity03.Unit); var quantity04 = ElectricResistivity.From(1, ElectricResistivityUnit.MicroohmCentimeter); - AssertEx.EqualTolerance(1, quantity04.MicroohmsCentimeter, MicroohmsCentimeterTolerance); + Assert.Equal(1, quantity04.MicroohmsCentimeter); Assert.Equal(ElectricResistivityUnit.MicroohmCentimeter, quantity04.Unit); var quantity05 = ElectricResistivity.From(1, ElectricResistivityUnit.MicroohmMeter); - AssertEx.EqualTolerance(1, quantity05.MicroohmMeters, MicroohmMetersTolerance); + Assert.Equal(1, quantity05.MicroohmMeters); Assert.Equal(ElectricResistivityUnit.MicroohmMeter, quantity05.Unit); var quantity06 = ElectricResistivity.From(1, ElectricResistivityUnit.MilliohmCentimeter); - AssertEx.EqualTolerance(1, quantity06.MilliohmsCentimeter, MilliohmsCentimeterTolerance); + Assert.Equal(1, quantity06.MilliohmsCentimeter); Assert.Equal(ElectricResistivityUnit.MilliohmCentimeter, quantity06.Unit); var quantity07 = ElectricResistivity.From(1, ElectricResistivityUnit.MilliohmMeter); - AssertEx.EqualTolerance(1, quantity07.MilliohmMeters, MilliohmMetersTolerance); + Assert.Equal(1, quantity07.MilliohmMeters); Assert.Equal(ElectricResistivityUnit.MilliohmMeter, quantity07.Unit); var quantity08 = ElectricResistivity.From(1, ElectricResistivityUnit.NanoohmCentimeter); - AssertEx.EqualTolerance(1, quantity08.NanoohmsCentimeter, NanoohmsCentimeterTolerance); + Assert.Equal(1, quantity08.NanoohmsCentimeter); Assert.Equal(ElectricResistivityUnit.NanoohmCentimeter, quantity08.Unit); var quantity09 = ElectricResistivity.From(1, ElectricResistivityUnit.NanoohmMeter); - AssertEx.EqualTolerance(1, quantity09.NanoohmMeters, NanoohmMetersTolerance); + Assert.Equal(1, quantity09.NanoohmMeters); Assert.Equal(ElectricResistivityUnit.NanoohmMeter, quantity09.Unit); var quantity10 = ElectricResistivity.From(1, ElectricResistivityUnit.OhmCentimeter); - AssertEx.EqualTolerance(1, quantity10.OhmsCentimeter, OhmsCentimeterTolerance); + Assert.Equal(1, quantity10.OhmsCentimeter); Assert.Equal(ElectricResistivityUnit.OhmCentimeter, quantity10.Unit); var quantity11 = ElectricResistivity.From(1, ElectricResistivityUnit.OhmMeter); - AssertEx.EqualTolerance(1, quantity11.OhmMeters, OhmMetersTolerance); + Assert.Equal(1, quantity11.OhmMeters); Assert.Equal(ElectricResistivityUnit.OhmMeter, quantity11.Unit); var quantity12 = ElectricResistivity.From(1, ElectricResistivityUnit.PicoohmCentimeter); - AssertEx.EqualTolerance(1, quantity12.PicoohmsCentimeter, PicoohmsCentimeterTolerance); + Assert.Equal(1, quantity12.PicoohmsCentimeter); Assert.Equal(ElectricResistivityUnit.PicoohmCentimeter, quantity12.Unit); var quantity13 = ElectricResistivity.From(1, ElectricResistivityUnit.PicoohmMeter); - AssertEx.EqualTolerance(1, quantity13.PicoohmMeters, PicoohmMetersTolerance); + Assert.Equal(1, quantity13.PicoohmMeters); Assert.Equal(ElectricResistivityUnit.PicoohmMeter, quantity13.Unit); } @@ -397,172 +415,50 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 kΩ·cm", ElectricResistivityUnit.KiloohmCentimeter, 4.2)] + [InlineData("en-US", "4.2 kΩ·m", ElectricResistivityUnit.KiloohmMeter, 4.2)] + [InlineData("en-US", "4.2 MΩ·cm", ElectricResistivityUnit.MegaohmCentimeter, 4.2)] + [InlineData("en-US", "4.2 MΩ·m", ElectricResistivityUnit.MegaohmMeter, 4.2)] + [InlineData("en-US", "4.2 µΩ·cm", ElectricResistivityUnit.MicroohmCentimeter, 4.2)] + [InlineData("en-US", "4.2 µΩ·m", ElectricResistivityUnit.MicroohmMeter, 4.2)] + [InlineData("en-US", "4.2 mΩ·cm", ElectricResistivityUnit.MilliohmCentimeter, 4.2)] + [InlineData("en-US", "4.2 mΩ·m", ElectricResistivityUnit.MilliohmMeter, 4.2)] + [InlineData("en-US", "4.2 nΩ·cm", ElectricResistivityUnit.NanoohmCentimeter, 4.2)] + [InlineData("en-US", "4.2 nΩ·m", ElectricResistivityUnit.NanoohmMeter, 4.2)] + [InlineData("en-US", "4.2 Ω·cm", ElectricResistivityUnit.OhmCentimeter, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = ElectricResistivity.Parse("1 kΩ·cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KiloohmsCentimeter, KiloohmsCentimeterTolerance); - Assert.Equal(ElectricResistivityUnit.KiloohmCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricResistivity.Parse("1 kΩ·m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KiloohmMeters, KiloohmMetersTolerance); - Assert.Equal(ElectricResistivityUnit.KiloohmMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricResistivity.Parse("1 MΩ·cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegaohmsCentimeter, MegaohmsCentimeterTolerance); - Assert.Equal(ElectricResistivityUnit.MegaohmCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricResistivity.Parse("1 MΩ·m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegaohmMeters, MegaohmMetersTolerance); - Assert.Equal(ElectricResistivityUnit.MegaohmMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricResistivity.Parse("1 µΩ·cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicroohmsCentimeter, MicroohmsCentimeterTolerance); - Assert.Equal(ElectricResistivityUnit.MicroohmCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricResistivity.Parse("1 µΩ·m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicroohmMeters, MicroohmMetersTolerance); - Assert.Equal(ElectricResistivityUnit.MicroohmMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricResistivity.Parse("1 mΩ·cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilliohmsCentimeter, MilliohmsCentimeterTolerance); - Assert.Equal(ElectricResistivityUnit.MilliohmCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricResistivity.Parse("1 mΩ·m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilliohmMeters, MilliohmMetersTolerance); - Assert.Equal(ElectricResistivityUnit.MilliohmMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricResistivity.Parse("1 nΩ·cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanoohmsCentimeter, NanoohmsCentimeterTolerance); - Assert.Equal(ElectricResistivityUnit.NanoohmCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricResistivity.Parse("1 nΩ·m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanoohmMeters, NanoohmMetersTolerance); - Assert.Equal(ElectricResistivityUnit.NanoohmMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricResistivity.Parse("1 Ω·cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.OhmsCentimeter, OhmsCentimeterTolerance); - Assert.Equal(ElectricResistivityUnit.OhmCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricResistivity.Parse("1 Ω·m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.OhmMeters, OhmMetersTolerance); - Assert.Equal(ElectricResistivityUnit.OhmMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricResistivity.Parse("1 pΩ·cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PicoohmsCentimeter, PicoohmsCentimeterTolerance); - Assert.Equal(ElectricResistivityUnit.PicoohmCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricResistivity.Parse("1 pΩ·m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PicoohmMeters, PicoohmMetersTolerance); - Assert.Equal(ElectricResistivityUnit.PicoohmMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ElectricResistivity.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 kΩ·cm", ElectricResistivityUnit.KiloohmCentimeter, 4.2)] + [InlineData("en-US", "4.2 kΩ·m", ElectricResistivityUnit.KiloohmMeter, 4.2)] + [InlineData("en-US", "4.2 MΩ·cm", ElectricResistivityUnit.MegaohmCentimeter, 4.2)] + [InlineData("en-US", "4.2 MΩ·m", ElectricResistivityUnit.MegaohmMeter, 4.2)] + [InlineData("en-US", "4.2 µΩ·cm", ElectricResistivityUnit.MicroohmCentimeter, 4.2)] + [InlineData("en-US", "4.2 µΩ·m", ElectricResistivityUnit.MicroohmMeter, 4.2)] + [InlineData("en-US", "4.2 mΩ·cm", ElectricResistivityUnit.MilliohmCentimeter, 4.2)] + [InlineData("en-US", "4.2 mΩ·m", ElectricResistivityUnit.MilliohmMeter, 4.2)] + [InlineData("en-US", "4.2 nΩ·cm", ElectricResistivityUnit.NanoohmCentimeter, 4.2)] + [InlineData("en-US", "4.2 nΩ·m", ElectricResistivityUnit.NanoohmMeter, 4.2)] + [InlineData("en-US", "4.2 Ω·cm", ElectricResistivityUnit.OhmCentimeter, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(ElectricResistivity.TryParse("1 kΩ·cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KiloohmsCentimeter, KiloohmsCentimeterTolerance); - Assert.Equal(ElectricResistivityUnit.KiloohmCentimeter, parsed.Unit); - } - - { - Assert.True(ElectricResistivity.TryParse("1 kΩ·m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KiloohmMeters, KiloohmMetersTolerance); - Assert.Equal(ElectricResistivityUnit.KiloohmMeter, parsed.Unit); - } - - { - Assert.True(ElectricResistivity.TryParse("1 µΩ·cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicroohmsCentimeter, MicroohmsCentimeterTolerance); - Assert.Equal(ElectricResistivityUnit.MicroohmCentimeter, parsed.Unit); - } - - { - Assert.True(ElectricResistivity.TryParse("1 µΩ·m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicroohmMeters, MicroohmMetersTolerance); - Assert.Equal(ElectricResistivityUnit.MicroohmMeter, parsed.Unit); - } - - { - Assert.True(ElectricResistivity.TryParse("1 nΩ·cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanoohmsCentimeter, NanoohmsCentimeterTolerance); - Assert.Equal(ElectricResistivityUnit.NanoohmCentimeter, parsed.Unit); - } - - { - Assert.True(ElectricResistivity.TryParse("1 nΩ·m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanoohmMeters, NanoohmMetersTolerance); - Assert.Equal(ElectricResistivityUnit.NanoohmMeter, parsed.Unit); - } - - { - Assert.True(ElectricResistivity.TryParse("1 Ω·cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.OhmsCentimeter, OhmsCentimeterTolerance); - Assert.Equal(ElectricResistivityUnit.OhmCentimeter, parsed.Unit); - } - - { - Assert.True(ElectricResistivity.TryParse("1 Ω·m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.OhmMeters, OhmMetersTolerance); - Assert.Equal(ElectricResistivityUnit.OhmMeter, parsed.Unit); - } - - { - Assert.True(ElectricResistivity.TryParse("1 pΩ·cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PicoohmsCentimeter, PicoohmsCentimeterTolerance); - Assert.Equal(ElectricResistivityUnit.PicoohmCentimeter, parsed.Unit); - } - - { - Assert.True(ElectricResistivity.TryParse("1 pΩ·m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PicoohmMeters, PicoohmMetersTolerance); - Assert.Equal(ElectricResistivityUnit.PicoohmMeter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ElectricResistivity.TryParse(quantityString, out ElectricResistivity parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -743,6 +639,40 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Electr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ElectricResistivityUnit.KiloohmCentimeter, "kΩ·cm")] + [InlineData("en-US", ElectricResistivityUnit.KiloohmMeter, "kΩ·m")] + [InlineData("en-US", ElectricResistivityUnit.MegaohmCentimeter, "MΩ·cm")] + [InlineData("en-US", ElectricResistivityUnit.MegaohmMeter, "MΩ·m")] + [InlineData("en-US", ElectricResistivityUnit.MicroohmCentimeter, "µΩ·cm")] + [InlineData("en-US", ElectricResistivityUnit.MicroohmMeter, "µΩ·m")] + [InlineData("en-US", ElectricResistivityUnit.MilliohmCentimeter, "mΩ·cm")] + [InlineData("en-US", ElectricResistivityUnit.MilliohmMeter, "mΩ·m")] + [InlineData("en-US", ElectricResistivityUnit.NanoohmCentimeter, "nΩ·cm")] + [InlineData("en-US", ElectricResistivityUnit.NanoohmMeter, "nΩ·m")] + [InlineData("en-US", ElectricResistivityUnit.OhmCentimeter, "Ω·cm")] + [InlineData("en-US", ElectricResistivityUnit.OhmMeter, "Ω·m")] + [InlineData("en-US", ElectricResistivityUnit.PicoohmCentimeter, "pΩ·cm")] + [InlineData("en-US", ElectricResistivityUnit.PicoohmMeter, "pΩ·m")] + public void GetAbbreviationForCulture(string culture, ElectricResistivityUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ElectricResistivity.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ElectricResistivity.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ElectricResistivity.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricResistivityUnit unit) @@ -773,6 +703,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); }); } @@ -796,45 +727,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] @@ -880,8 +813,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); @@ -919,34 +850,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = ElectricResistivity.FromOhmMeters(1); - Assert.True(v.Equals(ElectricResistivity.FromOhmMeters(1), OhmMetersTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ElectricResistivity.Zero, OhmMetersTolerance, ComparisonType.Relative)); - Assert.True(ElectricResistivity.FromOhmMeters(100).Equals(ElectricResistivity.FromOhmMeters(120), 0.3, ComparisonType.Relative)); - Assert.False(ElectricResistivity.FromOhmMeters(100).Equals(ElectricResistivity.FromOhmMeters(120), 0.1, ComparisonType.Relative)); + ElectricResistivity ohmmeter = ElectricResistivity.FromOhmMeters(1); + Assert.False(ohmmeter.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = ElectricResistivity.FromOhmMeters(1); - Assert.Throws(() => v.Equals(ElectricResistivity.FromOhmMeters(1), -1, ComparisonType.Relative)); + ElectricResistivity ohmmeter = ElectricResistivity.FromOhmMeters(1); + Assert.False(ohmmeter.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - ElectricResistivity ohmmeter = ElectricResistivity.FromOhmMeters(1); - Assert.False(ohmmeter.Equals(new object())); + var quantity = ElectricResistivity.FromOhmMeters(firstValue); + var otherQuantity = ElectricResistivity.FromOhmMeters(secondValue); + ElectricResistivity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - ElectricResistivity ohmmeter = ElectricResistivity.FromOhmMeters(1); - Assert.False(ohmmeter.Equals(null)); + var quantity = ElectricResistivity.FromOhmMeters(1); + var negativeTolerance = ElectricResistivity.FromOhmMeters(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -965,6 +905,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() { @@ -1049,158 +1001,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ElectricResistivity))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricResistivityUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal(ElectricResistivity.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal(ElectricResistivity.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal(new {ElectricResistivity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 82be1d1555..d4e306ab2b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricSurfaceChargeDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricSurfaceChargeDensityTestsBase.g.cs @@ -104,7 +104,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ElectricSurfaceChargeDensity(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -117,15 +117,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ElectricSurfaceChargeDensity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ElectricSurfaceChargeDensityUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ElectricSurfaceChargeDensity(1, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ElectricSurfaceChargeDensity.Zero, quantityInfo.Zero); Assert.Equal("ElectricSurfaceChargeDensity", quantityInfo.Name); + Assert.Equal(ElectricSurfaceChargeDensity.Zero, quantityInfo.Zero); + Assert.Equal(ElectricSurfaceChargeDensity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ElectricSurfaceChargeDensity.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void ElectricSurfaceChargeDensityInfo_CreateWithCustomUnitInfos() + { + ElectricSurfaceChargeDensityUnit[] expectedUnits = [ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -141,15 +159,15 @@ public void CoulombPerSquareMeterToElectricSurfaceChargeDensityUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ElectricSurfaceChargeDensity.From(1, ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter); - AssertEx.EqualTolerance(1, quantity00.CoulombsPerSquareCentimeter, CoulombsPerSquareCentimeterTolerance); + Assert.Equal(1, quantity00.CoulombsPerSquareCentimeter); Assert.Equal(ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter, quantity00.Unit); var quantity01 = ElectricSurfaceChargeDensity.From(1, ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch); - AssertEx.EqualTolerance(1, quantity01.CoulombsPerSquareInch, CoulombsPerSquareInchTolerance); + Assert.Equal(1, quantity01.CoulombsPerSquareInch); Assert.Equal(ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch, quantity01.Unit); var quantity02 = ElectricSurfaceChargeDensity.From(1, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter); - AssertEx.EqualTolerance(1, quantity02.CoulombsPerSquareMeter, CoulombsPerSquareMeterTolerance); + Assert.Equal(1, quantity02.CoulombsPerSquareMeter); Assert.Equal(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, quantity02.Unit); } @@ -287,53 +305,28 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [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, decimal expectedValue) { - try - { - var parsed = ElectricSurfaceChargeDensity.Parse("1 C/cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CoulombsPerSquareCentimeter, CoulombsPerSquareCentimeterTolerance); - Assert.Equal(ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricSurfaceChargeDensity.Parse("1 C/in²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CoulombsPerSquareInch, CoulombsPerSquareInchTolerance); - Assert.Equal(ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricSurfaceChargeDensity.Parse("1 C/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CoulombsPerSquareMeter, CoulombsPerSquareMeterTolerance); - Assert.Equal(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ElectricSurfaceChargeDensity.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [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, decimal expectedValue) { - { - Assert.True(ElectricSurfaceChargeDensity.TryParse("1 C/cm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CoulombsPerSquareCentimeter, CoulombsPerSquareCentimeterTolerance); - Assert.Equal(ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter, parsed.Unit); - } - - { - Assert.True(ElectricSurfaceChargeDensity.TryParse("1 C/in²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CoulombsPerSquareInch, CoulombsPerSquareInchTolerance); - Assert.Equal(ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch, parsed.Unit); - } - - { - Assert.True(ElectricSurfaceChargeDensity.TryParse("1 C/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CoulombsPerSquareMeter, CoulombsPerSquareMeterTolerance); - Assert.Equal(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ElectricSurfaceChargeDensity.TryParse(quantityString, out ElectricSurfaceChargeDensity parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -426,6 +419,29 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Electr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter, "C/cm²")] + [InlineData("en-US", ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch, "C/in²")] + [InlineData("en-US", ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, "C/m²")] + public void GetAbbreviationForCulture(string culture, ElectricSurfaceChargeDensityUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ElectricSurfaceChargeDensity.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ElectricSurfaceChargeDensity.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ElectricSurfaceChargeDensity.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricSurfaceChargeDensityUnit unit) @@ -456,6 +472,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); }); } @@ -479,34 +496,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] @@ -552,8 +571,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); @@ -591,34 +608,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1); - Assert.True(v.Equals(ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1), CoulombsPerSquareMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ElectricSurfaceChargeDensity.Zero, CoulombsPerSquareMeterTolerance, ComparisonType.Relative)); - Assert.True(ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(100).Equals(ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(100).Equals(ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(120), 0.1, ComparisonType.Relative)); + ElectricSurfaceChargeDensity coulombpersquaremeter = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1); + Assert.False(coulombpersquaremeter.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1); - Assert.Throws(() => v.Equals(ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1), -1, ComparisonType.Relative)); + ElectricSurfaceChargeDensity coulombpersquaremeter = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1); + Assert.False(coulombpersquaremeter.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - ElectricSurfaceChargeDensity coulombpersquaremeter = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1); - Assert.False(coulombpersquaremeter.Equals(new object())); + var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(firstValue); + var otherQuantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(secondValue); + ElectricSurfaceChargeDensity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - ElectricSurfaceChargeDensity coulombpersquaremeter = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1); - Assert.False(coulombpersquaremeter.Equals(null)); + var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1); + var negativeTolerance = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -637,6 +663,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() { @@ -699,158 +737,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ElectricSurfaceChargeDensity))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricSurfaceChargeDensityUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal(ElectricSurfaceChargeDensity.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal(ElectricSurfaceChargeDensity.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal(new {ElectricSurfaceChargeDensity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 ac2bb67e5a..22ec231489 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricSusceptanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricSusceptanceTestsBase.g.cs @@ -156,7 +156,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ElectricSusceptance(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -169,15 +169,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ElectricSusceptance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ElectricSusceptanceUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ElectricSusceptance(1, ElectricSusceptanceUnit.Siemens); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ElectricSusceptance.Zero, quantityInfo.Zero); Assert.Equal("ElectricSusceptance", quantityInfo.Name); + Assert.Equal(ElectricSusceptance.Zero, quantityInfo.Zero); + Assert.Equal(ElectricSusceptance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ElectricSusceptance.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -206,67 +224,67 @@ public void SiemensToElectricSusceptanceUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ElectricSusceptance.From(1, ElectricSusceptanceUnit.Gigamho); - AssertEx.EqualTolerance(1, quantity00.Gigamhos, GigamhosTolerance); + Assert.Equal(1, quantity00.Gigamhos); Assert.Equal(ElectricSusceptanceUnit.Gigamho, quantity00.Unit); var quantity01 = ElectricSusceptance.From(1, ElectricSusceptanceUnit.Gigasiemens); - AssertEx.EqualTolerance(1, quantity01.Gigasiemens, GigasiemensTolerance); + Assert.Equal(1, quantity01.Gigasiemens); Assert.Equal(ElectricSusceptanceUnit.Gigasiemens, quantity01.Unit); var quantity02 = ElectricSusceptance.From(1, ElectricSusceptanceUnit.Kilomho); - AssertEx.EqualTolerance(1, quantity02.Kilomhos, KilomhosTolerance); + Assert.Equal(1, quantity02.Kilomhos); Assert.Equal(ElectricSusceptanceUnit.Kilomho, quantity02.Unit); var quantity03 = ElectricSusceptance.From(1, ElectricSusceptanceUnit.Kilosiemens); - AssertEx.EqualTolerance(1, quantity03.Kilosiemens, KilosiemensTolerance); + Assert.Equal(1, quantity03.Kilosiemens); Assert.Equal(ElectricSusceptanceUnit.Kilosiemens, quantity03.Unit); var quantity04 = ElectricSusceptance.From(1, ElectricSusceptanceUnit.Megamho); - AssertEx.EqualTolerance(1, quantity04.Megamhos, MegamhosTolerance); + Assert.Equal(1, quantity04.Megamhos); Assert.Equal(ElectricSusceptanceUnit.Megamho, quantity04.Unit); var quantity05 = ElectricSusceptance.From(1, ElectricSusceptanceUnit.Megasiemens); - AssertEx.EqualTolerance(1, quantity05.Megasiemens, MegasiemensTolerance); + Assert.Equal(1, quantity05.Megasiemens); Assert.Equal(ElectricSusceptanceUnit.Megasiemens, quantity05.Unit); var quantity06 = ElectricSusceptance.From(1, ElectricSusceptanceUnit.Mho); - AssertEx.EqualTolerance(1, quantity06.Mhos, MhosTolerance); + Assert.Equal(1, quantity06.Mhos); Assert.Equal(ElectricSusceptanceUnit.Mho, quantity06.Unit); var quantity07 = ElectricSusceptance.From(1, ElectricSusceptanceUnit.Micromho); - AssertEx.EqualTolerance(1, quantity07.Micromhos, MicromhosTolerance); + Assert.Equal(1, quantity07.Micromhos); Assert.Equal(ElectricSusceptanceUnit.Micromho, quantity07.Unit); var quantity08 = ElectricSusceptance.From(1, ElectricSusceptanceUnit.Microsiemens); - AssertEx.EqualTolerance(1, quantity08.Microsiemens, MicrosiemensTolerance); + Assert.Equal(1, quantity08.Microsiemens); Assert.Equal(ElectricSusceptanceUnit.Microsiemens, quantity08.Unit); var quantity09 = ElectricSusceptance.From(1, ElectricSusceptanceUnit.Millimho); - AssertEx.EqualTolerance(1, quantity09.Millimhos, MillimhosTolerance); + Assert.Equal(1, quantity09.Millimhos); Assert.Equal(ElectricSusceptanceUnit.Millimho, quantity09.Unit); var quantity10 = ElectricSusceptance.From(1, ElectricSusceptanceUnit.Millisiemens); - AssertEx.EqualTolerance(1, quantity10.Millisiemens, MillisiemensTolerance); + Assert.Equal(1, quantity10.Millisiemens); Assert.Equal(ElectricSusceptanceUnit.Millisiemens, quantity10.Unit); var quantity11 = ElectricSusceptance.From(1, ElectricSusceptanceUnit.Nanomho); - AssertEx.EqualTolerance(1, quantity11.Nanomhos, NanomhosTolerance); + Assert.Equal(1, quantity11.Nanomhos); Assert.Equal(ElectricSusceptanceUnit.Nanomho, quantity11.Unit); var quantity12 = ElectricSusceptance.From(1, ElectricSusceptanceUnit.Nanosiemens); - AssertEx.EqualTolerance(1, quantity12.Nanosiemens, NanosiemensTolerance); + Assert.Equal(1, quantity12.Nanosiemens); Assert.Equal(ElectricSusceptanceUnit.Nanosiemens, quantity12.Unit); var quantity13 = ElectricSusceptance.From(1, ElectricSusceptanceUnit.Siemens); - AssertEx.EqualTolerance(1, quantity13.Siemens, SiemensTolerance); + Assert.Equal(1, quantity13.Siemens); Assert.Equal(ElectricSusceptanceUnit.Siemens, quantity13.Unit); var quantity14 = ElectricSusceptance.From(1, ElectricSusceptanceUnit.Teramho); - AssertEx.EqualTolerance(1, quantity14.Teramhos, TeramhosTolerance); + Assert.Equal(1, quantity14.Teramhos); Assert.Equal(ElectricSusceptanceUnit.Teramho, quantity14.Unit); var quantity15 = ElectricSusceptance.From(1, ElectricSusceptanceUnit.Terasiemens); - AssertEx.EqualTolerance(1, quantity15.Terasiemens, TerasiemensTolerance); + Assert.Equal(1, quantity15.Terasiemens); Assert.Equal(ElectricSusceptanceUnit.Terasiemens, quantity15.Unit); } @@ -417,198 +435,54 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 G℧", ElectricSusceptanceUnit.Gigamho, 4.2)] + [InlineData("en-US", "4.2 GS", ElectricSusceptanceUnit.Gigasiemens, 4.2)] + [InlineData("en-US", "4.2 k℧", ElectricSusceptanceUnit.Kilomho, 4.2)] + [InlineData("en-US", "4.2 kS", ElectricSusceptanceUnit.Kilosiemens, 4.2)] + [InlineData("en-US", "4.2 M℧", ElectricSusceptanceUnit.Megamho, 4.2)] + [InlineData("en-US", "4.2 MS", ElectricSusceptanceUnit.Megasiemens, 4.2)] + [InlineData("en-US", "4.2 ℧", ElectricSusceptanceUnit.Mho, 4.2)] + [InlineData("en-US", "4.2 µ℧", ElectricSusceptanceUnit.Micromho, 4.2)] + [InlineData("en-US", "4.2 µS", ElectricSusceptanceUnit.Microsiemens, 4.2)] + [InlineData("en-US", "4.2 m℧", ElectricSusceptanceUnit.Millimho, 4.2)] + [InlineData("en-US", "4.2 mS", ElectricSusceptanceUnit.Millisiemens, 4.2)] + [InlineData("en-US", "4.2 n℧", ElectricSusceptanceUnit.Nanomho, 4.2)] + [InlineData("en-US", "4.2 nS", ElectricSusceptanceUnit.Nanosiemens, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = ElectricSusceptance.Parse("1 G℧", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Gigamhos, GigamhosTolerance); - Assert.Equal(ElectricSusceptanceUnit.Gigamho, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricSusceptance.Parse("1 GS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Gigasiemens, GigasiemensTolerance); - Assert.Equal(ElectricSusceptanceUnit.Gigasiemens, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricSusceptance.Parse("1 k℧", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilomhos, KilomhosTolerance); - Assert.Equal(ElectricSusceptanceUnit.Kilomho, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricSusceptance.Parse("1 kS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilosiemens, KilosiemensTolerance); - Assert.Equal(ElectricSusceptanceUnit.Kilosiemens, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricSusceptance.Parse("1 M℧", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megamhos, MegamhosTolerance); - Assert.Equal(ElectricSusceptanceUnit.Megamho, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricSusceptance.Parse("1 MS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megasiemens, MegasiemensTolerance); - Assert.Equal(ElectricSusceptanceUnit.Megasiemens, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricSusceptance.Parse("1 ℧", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Mhos, MhosTolerance); - Assert.Equal(ElectricSusceptanceUnit.Mho, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricSusceptance.Parse("1 µ℧", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Micromhos, MicromhosTolerance); - Assert.Equal(ElectricSusceptanceUnit.Micromho, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricSusceptance.Parse("1 µS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microsiemens, MicrosiemensTolerance); - Assert.Equal(ElectricSusceptanceUnit.Microsiemens, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricSusceptance.Parse("1 m℧", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millimhos, MillimhosTolerance); - Assert.Equal(ElectricSusceptanceUnit.Millimho, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricSusceptance.Parse("1 mS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millisiemens, MillisiemensTolerance); - Assert.Equal(ElectricSusceptanceUnit.Millisiemens, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricSusceptance.Parse("1 n℧", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanomhos, NanomhosTolerance); - Assert.Equal(ElectricSusceptanceUnit.Nanomho, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricSusceptance.Parse("1 nS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanosiemens, NanosiemensTolerance); - Assert.Equal(ElectricSusceptanceUnit.Nanosiemens, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricSusceptance.Parse("1 S", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Siemens, SiemensTolerance); - Assert.Equal(ElectricSusceptanceUnit.Siemens, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricSusceptance.Parse("1 T℧", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Teramhos, TeramhosTolerance); - Assert.Equal(ElectricSusceptanceUnit.Teramho, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ElectricSusceptance.Parse("1 TS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Terasiemens, TerasiemensTolerance); - Assert.Equal(ElectricSusceptanceUnit.Terasiemens, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ElectricSusceptance.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 G℧", ElectricSusceptanceUnit.Gigamho, 4.2)] + [InlineData("en-US", "4.2 GS", ElectricSusceptanceUnit.Gigasiemens, 4.2)] + [InlineData("en-US", "4.2 k℧", ElectricSusceptanceUnit.Kilomho, 4.2)] + [InlineData("en-US", "4.2 kS", ElectricSusceptanceUnit.Kilosiemens, 4.2)] + [InlineData("en-US", "4.2 M℧", ElectricSusceptanceUnit.Megamho, 4.2)] + [InlineData("en-US", "4.2 MS", ElectricSusceptanceUnit.Megasiemens, 4.2)] + [InlineData("en-US", "4.2 ℧", ElectricSusceptanceUnit.Mho, 4.2)] + [InlineData("en-US", "4.2 µ℧", ElectricSusceptanceUnit.Micromho, 4.2)] + [InlineData("en-US", "4.2 µS", ElectricSusceptanceUnit.Microsiemens, 4.2)] + [InlineData("en-US", "4.2 m℧", ElectricSusceptanceUnit.Millimho, 4.2)] + [InlineData("en-US", "4.2 mS", ElectricSusceptanceUnit.Millisiemens, 4.2)] + [InlineData("en-US", "4.2 n℧", ElectricSusceptanceUnit.Nanomho, 4.2)] + [InlineData("en-US", "4.2 nS", ElectricSusceptanceUnit.Nanosiemens, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(ElectricSusceptance.TryParse("1 G℧", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gigamhos, GigamhosTolerance); - Assert.Equal(ElectricSusceptanceUnit.Gigamho, parsed.Unit); - } - - { - Assert.True(ElectricSusceptance.TryParse("1 GS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gigasiemens, GigasiemensTolerance); - Assert.Equal(ElectricSusceptanceUnit.Gigasiemens, parsed.Unit); - } - - { - Assert.True(ElectricSusceptance.TryParse("1 k℧", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilomhos, KilomhosTolerance); - Assert.Equal(ElectricSusceptanceUnit.Kilomho, parsed.Unit); - } - - { - Assert.True(ElectricSusceptance.TryParse("1 kS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilosiemens, KilosiemensTolerance); - Assert.Equal(ElectricSusceptanceUnit.Kilosiemens, parsed.Unit); - } - - { - Assert.True(ElectricSusceptance.TryParse("1 ℧", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Mhos, MhosTolerance); - Assert.Equal(ElectricSusceptanceUnit.Mho, parsed.Unit); - } - - { - Assert.True(ElectricSusceptance.TryParse("1 µ℧", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Micromhos, MicromhosTolerance); - Assert.Equal(ElectricSusceptanceUnit.Micromho, parsed.Unit); - } - - { - Assert.True(ElectricSusceptance.TryParse("1 µS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microsiemens, MicrosiemensTolerance); - Assert.Equal(ElectricSusceptanceUnit.Microsiemens, parsed.Unit); - } - - { - Assert.True(ElectricSusceptance.TryParse("1 n℧", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanomhos, NanomhosTolerance); - Assert.Equal(ElectricSusceptanceUnit.Nanomho, parsed.Unit); - } - - { - Assert.True(ElectricSusceptance.TryParse("1 nS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanosiemens, NanosiemensTolerance); - Assert.Equal(ElectricSusceptanceUnit.Nanosiemens, parsed.Unit); - } - - { - Assert.True(ElectricSusceptance.TryParse("1 S", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Siemens, SiemensTolerance); - Assert.Equal(ElectricSusceptanceUnit.Siemens, parsed.Unit); - } - - { - Assert.True(ElectricSusceptance.TryParse("1 T℧", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Teramhos, TeramhosTolerance); - Assert.Equal(ElectricSusceptanceUnit.Teramho, parsed.Unit); - } - - { - Assert.True(ElectricSusceptance.TryParse("1 TS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Terasiemens, TerasiemensTolerance); - Assert.Equal(ElectricSusceptanceUnit.Terasiemens, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ElectricSusceptance.TryParse(quantityString, out ElectricSusceptance parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -805,6 +679,42 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Electr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ElectricSusceptanceUnit.Gigamho, "G℧")] + [InlineData("en-US", ElectricSusceptanceUnit.Gigasiemens, "GS")] + [InlineData("en-US", ElectricSusceptanceUnit.Kilomho, "k℧")] + [InlineData("en-US", ElectricSusceptanceUnit.Kilosiemens, "kS")] + [InlineData("en-US", ElectricSusceptanceUnit.Megamho, "M℧")] + [InlineData("en-US", ElectricSusceptanceUnit.Megasiemens, "MS")] + [InlineData("en-US", ElectricSusceptanceUnit.Mho, "℧")] + [InlineData("en-US", ElectricSusceptanceUnit.Micromho, "µ℧")] + [InlineData("en-US", ElectricSusceptanceUnit.Microsiemens, "µS")] + [InlineData("en-US", ElectricSusceptanceUnit.Millimho, "m℧")] + [InlineData("en-US", ElectricSusceptanceUnit.Millisiemens, "mS")] + [InlineData("en-US", ElectricSusceptanceUnit.Nanomho, "n℧")] + [InlineData("en-US", ElectricSusceptanceUnit.Nanosiemens, "nS")] + [InlineData("en-US", ElectricSusceptanceUnit.Siemens, "S")] + [InlineData("en-US", ElectricSusceptanceUnit.Teramho, "T℧")] + [InlineData("en-US", ElectricSusceptanceUnit.Terasiemens, "TS")] + public void GetAbbreviationForCulture(string culture, ElectricSusceptanceUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ElectricSusceptance.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ElectricSusceptance.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ElectricSusceptance.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ElectricSusceptanceUnit unit) @@ -835,6 +745,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); }); } @@ -858,47 +769,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] @@ -944,8 +857,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); @@ -982,23 +893,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = ElectricSusceptance.FromSiemens(1); - Assert.True(v.Equals(ElectricSusceptance.FromSiemens(1), SiemensTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ElectricSusceptance.Zero, SiemensTolerance, ComparisonType.Relative)); - Assert.True(ElectricSusceptance.FromSiemens(100).Equals(ElectricSusceptance.FromSiemens(120), 0.3, ComparisonType.Relative)); - Assert.False(ElectricSusceptance.FromSiemens(100).Equals(ElectricSusceptance.FromSiemens(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = ElectricSusceptance.FromSiemens(1); - Assert.Throws(() => v.Equals(ElectricSusceptance.FromSiemens(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1013,6 +907,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(siemens.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = ElectricSusceptance.FromSiemens(1); + var negativeTolerance = ElectricSusceptance.FromSiemens(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1029,6 +949,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() { @@ -1117,158 +1049,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ElectricSusceptance.FromSiemens(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ElectricSusceptance.FromSiemens(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ElectricSusceptance.FromSiemens(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ElectricSusceptance.FromSiemens(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ElectricSusceptance.FromSiemens(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ElectricSusceptance.FromSiemens(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ElectricSusceptance.FromSiemens(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ElectricSusceptance.FromSiemens(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ElectricSusceptance.FromSiemens(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ElectricSusceptance.FromSiemens(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ElectricSusceptance.FromSiemens(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ElectricSusceptance.FromSiemens(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ElectricSusceptance.FromSiemens(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ElectricSusceptance.FromSiemens(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ElectricSusceptance.FromSiemens(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ElectricSusceptance.FromSiemens(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ElectricSusceptance))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ElectricSusceptance.FromSiemens(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ElectricSusceptanceUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ElectricSusceptance.FromSiemens(1.0); - Assert.Equal(ElectricSusceptance.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ElectricSusceptance.FromSiemens(1.0); - Assert.Equal(ElectricSusceptance.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ElectricSusceptance.FromSiemens(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ElectricSusceptance.FromSiemens(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ElectricSusceptance.FromSiemens(1.0); - Assert.Equal(new {ElectricSusceptance.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 13320432d5..f46d21b097 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyDensityTestsBase.g.cs @@ -140,7 +140,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new EnergyDensity(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -153,15 +153,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void EnergyDensity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + EnergyDensityUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new EnergyDensity(1, EnergyDensityUnit.JoulePerCubicMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(EnergyDensity.Zero, quantityInfo.Zero); Assert.Equal("EnergyDensity", quantityInfo.Name); + Assert.Equal(EnergyDensity.Zero, quantityInfo.Zero); + Assert.Equal(EnergyDensity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(EnergyDensity.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -186,51 +204,51 @@ public void JoulePerCubicMeterToEnergyDensityUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = EnergyDensity.From(1, EnergyDensityUnit.GigajoulePerCubicMeter); - AssertEx.EqualTolerance(1, quantity00.GigajoulesPerCubicMeter, GigajoulesPerCubicMeterTolerance); + Assert.Equal(1, quantity00.GigajoulesPerCubicMeter); Assert.Equal(EnergyDensityUnit.GigajoulePerCubicMeter, quantity00.Unit); var quantity01 = EnergyDensity.From(1, EnergyDensityUnit.GigawattHourPerCubicMeter); - AssertEx.EqualTolerance(1, quantity01.GigawattHoursPerCubicMeter, GigawattHoursPerCubicMeterTolerance); + Assert.Equal(1, quantity01.GigawattHoursPerCubicMeter); Assert.Equal(EnergyDensityUnit.GigawattHourPerCubicMeter, quantity01.Unit); var quantity02 = EnergyDensity.From(1, EnergyDensityUnit.JoulePerCubicMeter); - AssertEx.EqualTolerance(1, quantity02.JoulesPerCubicMeter, JoulesPerCubicMeterTolerance); + Assert.Equal(1, quantity02.JoulesPerCubicMeter); Assert.Equal(EnergyDensityUnit.JoulePerCubicMeter, quantity02.Unit); var quantity03 = EnergyDensity.From(1, EnergyDensityUnit.KilojoulePerCubicMeter); - AssertEx.EqualTolerance(1, quantity03.KilojoulesPerCubicMeter, KilojoulesPerCubicMeterTolerance); + Assert.Equal(1, quantity03.KilojoulesPerCubicMeter); Assert.Equal(EnergyDensityUnit.KilojoulePerCubicMeter, quantity03.Unit); var quantity04 = EnergyDensity.From(1, EnergyDensityUnit.KilowattHourPerCubicMeter); - AssertEx.EqualTolerance(1, quantity04.KilowattHoursPerCubicMeter, KilowattHoursPerCubicMeterTolerance); + Assert.Equal(1, quantity04.KilowattHoursPerCubicMeter); Assert.Equal(EnergyDensityUnit.KilowattHourPerCubicMeter, quantity04.Unit); var quantity05 = EnergyDensity.From(1, EnergyDensityUnit.MegajoulePerCubicMeter); - AssertEx.EqualTolerance(1, quantity05.MegajoulesPerCubicMeter, MegajoulesPerCubicMeterTolerance); + Assert.Equal(1, quantity05.MegajoulesPerCubicMeter); Assert.Equal(EnergyDensityUnit.MegajoulePerCubicMeter, quantity05.Unit); var quantity06 = EnergyDensity.From(1, EnergyDensityUnit.MegawattHourPerCubicMeter); - AssertEx.EqualTolerance(1, quantity06.MegawattHoursPerCubicMeter, MegawattHoursPerCubicMeterTolerance); + Assert.Equal(1, quantity06.MegawattHoursPerCubicMeter); Assert.Equal(EnergyDensityUnit.MegawattHourPerCubicMeter, quantity06.Unit); var quantity07 = EnergyDensity.From(1, EnergyDensityUnit.PetajoulePerCubicMeter); - AssertEx.EqualTolerance(1, quantity07.PetajoulesPerCubicMeter, PetajoulesPerCubicMeterTolerance); + Assert.Equal(1, quantity07.PetajoulesPerCubicMeter); Assert.Equal(EnergyDensityUnit.PetajoulePerCubicMeter, quantity07.Unit); var quantity08 = EnergyDensity.From(1, EnergyDensityUnit.PetawattHourPerCubicMeter); - AssertEx.EqualTolerance(1, quantity08.PetawattHoursPerCubicMeter, PetawattHoursPerCubicMeterTolerance); + Assert.Equal(1, quantity08.PetawattHoursPerCubicMeter); Assert.Equal(EnergyDensityUnit.PetawattHourPerCubicMeter, quantity08.Unit); var quantity09 = EnergyDensity.From(1, EnergyDensityUnit.TerajoulePerCubicMeter); - AssertEx.EqualTolerance(1, quantity09.TerajoulesPerCubicMeter, TerajoulesPerCubicMeterTolerance); + Assert.Equal(1, quantity09.TerajoulesPerCubicMeter); Assert.Equal(EnergyDensityUnit.TerajoulePerCubicMeter, quantity09.Unit); var quantity10 = EnergyDensity.From(1, EnergyDensityUnit.TerawattHourPerCubicMeter); - AssertEx.EqualTolerance(1, quantity10.TerawattHoursPerCubicMeter, TerawattHoursPerCubicMeterTolerance); + Assert.Equal(1, quantity10.TerawattHoursPerCubicMeter); Assert.Equal(EnergyDensityUnit.TerawattHourPerCubicMeter, quantity10.Unit); var quantity11 = EnergyDensity.From(1, EnergyDensityUnit.WattHourPerCubicMeter); - AssertEx.EqualTolerance(1, quantity11.WattHoursPerCubicMeter, WattHoursPerCubicMeterTolerance); + Assert.Equal(1, quantity11.WattHoursPerCubicMeter); Assert.Equal(EnergyDensityUnit.WattHourPerCubicMeter, quantity11.Unit); } @@ -377,170 +395,46 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 GJ/m³", EnergyDensityUnit.GigajoulePerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 GWh/m³", EnergyDensityUnit.GigawattHourPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 J/m³", EnergyDensityUnit.JoulePerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 kJ/m³", EnergyDensityUnit.KilojoulePerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 kWh/m³", EnergyDensityUnit.KilowattHourPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 MJ/m³", EnergyDensityUnit.MegajoulePerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 MWh/m³", EnergyDensityUnit.MegawattHourPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 PJ/m³", EnergyDensityUnit.PetajoulePerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 PWh/m³", EnergyDensityUnit.PetawattHourPerCubicMeter, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = EnergyDensity.Parse("1 GJ/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GigajoulesPerCubicMeter, GigajoulesPerCubicMeterTolerance); - Assert.Equal(EnergyDensityUnit.GigajoulePerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = EnergyDensity.Parse("1 GWh/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GigawattHoursPerCubicMeter, GigawattHoursPerCubicMeterTolerance); - Assert.Equal(EnergyDensityUnit.GigawattHourPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = EnergyDensity.Parse("1 J/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.JoulesPerCubicMeter, JoulesPerCubicMeterTolerance); - Assert.Equal(EnergyDensityUnit.JoulePerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = EnergyDensity.Parse("1 kJ/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilojoulesPerCubicMeter, KilojoulesPerCubicMeterTolerance); - Assert.Equal(EnergyDensityUnit.KilojoulePerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = EnergyDensity.Parse("1 kWh/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilowattHoursPerCubicMeter, KilowattHoursPerCubicMeterTolerance); - Assert.Equal(EnergyDensityUnit.KilowattHourPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = EnergyDensity.Parse("1 MJ/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegajoulesPerCubicMeter, MegajoulesPerCubicMeterTolerance); - Assert.Equal(EnergyDensityUnit.MegajoulePerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = EnergyDensity.Parse("1 MWh/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegawattHoursPerCubicMeter, MegawattHoursPerCubicMeterTolerance); - Assert.Equal(EnergyDensityUnit.MegawattHourPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = EnergyDensity.Parse("1 PJ/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PetajoulesPerCubicMeter, PetajoulesPerCubicMeterTolerance); - Assert.Equal(EnergyDensityUnit.PetajoulePerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = EnergyDensity.Parse("1 PWh/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PetawattHoursPerCubicMeter, PetawattHoursPerCubicMeterTolerance); - Assert.Equal(EnergyDensityUnit.PetawattHourPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = EnergyDensity.Parse("1 TJ/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TerajoulesPerCubicMeter, TerajoulesPerCubicMeterTolerance); - Assert.Equal(EnergyDensityUnit.TerajoulePerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = EnergyDensity.Parse("1 TWh/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TerawattHoursPerCubicMeter, TerawattHoursPerCubicMeterTolerance); - Assert.Equal(EnergyDensityUnit.TerawattHourPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = EnergyDensity.Parse("1 Wh/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WattHoursPerCubicMeter, WattHoursPerCubicMeterTolerance); - Assert.Equal(EnergyDensityUnit.WattHourPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = EnergyDensity.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 GJ/m³", EnergyDensityUnit.GigajoulePerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 GWh/m³", EnergyDensityUnit.GigawattHourPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 J/m³", EnergyDensityUnit.JoulePerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 kJ/m³", EnergyDensityUnit.KilojoulePerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 kWh/m³", EnergyDensityUnit.KilowattHourPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 MJ/m³", EnergyDensityUnit.MegajoulePerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 MWh/m³", EnergyDensityUnit.MegawattHourPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 PJ/m³", EnergyDensityUnit.PetajoulePerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 PWh/m³", EnergyDensityUnit.PetawattHourPerCubicMeter, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(EnergyDensity.TryParse("1 GJ/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigajoulesPerCubicMeter, GigajoulesPerCubicMeterTolerance); - Assert.Equal(EnergyDensityUnit.GigajoulePerCubicMeter, parsed.Unit); - } - - { - Assert.True(EnergyDensity.TryParse("1 GWh/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigawattHoursPerCubicMeter, GigawattHoursPerCubicMeterTolerance); - Assert.Equal(EnergyDensityUnit.GigawattHourPerCubicMeter, parsed.Unit); - } - - { - Assert.True(EnergyDensity.TryParse("1 J/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.JoulesPerCubicMeter, JoulesPerCubicMeterTolerance); - Assert.Equal(EnergyDensityUnit.JoulePerCubicMeter, parsed.Unit); - } - - { - Assert.True(EnergyDensity.TryParse("1 kJ/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilojoulesPerCubicMeter, KilojoulesPerCubicMeterTolerance); - Assert.Equal(EnergyDensityUnit.KilojoulePerCubicMeter, parsed.Unit); - } - - { - Assert.True(EnergyDensity.TryParse("1 kWh/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilowattHoursPerCubicMeter, KilowattHoursPerCubicMeterTolerance); - Assert.Equal(EnergyDensityUnit.KilowattHourPerCubicMeter, parsed.Unit); - } - - { - Assert.True(EnergyDensity.TryParse("1 MJ/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegajoulesPerCubicMeter, MegajoulesPerCubicMeterTolerance); - Assert.Equal(EnergyDensityUnit.MegajoulePerCubicMeter, parsed.Unit); - } - - { - Assert.True(EnergyDensity.TryParse("1 MWh/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegawattHoursPerCubicMeter, MegawattHoursPerCubicMeterTolerance); - Assert.Equal(EnergyDensityUnit.MegawattHourPerCubicMeter, parsed.Unit); - } - - { - Assert.True(EnergyDensity.TryParse("1 PJ/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PetajoulesPerCubicMeter, PetajoulesPerCubicMeterTolerance); - Assert.Equal(EnergyDensityUnit.PetajoulePerCubicMeter, parsed.Unit); - } - - { - Assert.True(EnergyDensity.TryParse("1 PWh/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PetawattHoursPerCubicMeter, PetawattHoursPerCubicMeterTolerance); - Assert.Equal(EnergyDensityUnit.PetawattHourPerCubicMeter, parsed.Unit); - } - - { - Assert.True(EnergyDensity.TryParse("1 TJ/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TerajoulesPerCubicMeter, TerajoulesPerCubicMeterTolerance); - Assert.Equal(EnergyDensityUnit.TerajoulePerCubicMeter, parsed.Unit); - } - - { - Assert.True(EnergyDensity.TryParse("1 TWh/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TerawattHoursPerCubicMeter, TerawattHoursPerCubicMeterTolerance); - Assert.Equal(EnergyDensityUnit.TerawattHourPerCubicMeter, parsed.Unit); - } - - { - Assert.True(EnergyDensity.TryParse("1 Wh/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattHoursPerCubicMeter, WattHoursPerCubicMeterTolerance); - Assert.Equal(EnergyDensityUnit.WattHourPerCubicMeter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(EnergyDensity.TryParse(quantityString, out EnergyDensity parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -705,6 +599,38 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Energy Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", EnergyDensityUnit.GigajoulePerCubicMeter, "GJ/m³")] + [InlineData("en-US", EnergyDensityUnit.GigawattHourPerCubicMeter, "GWh/m³")] + [InlineData("en-US", EnergyDensityUnit.JoulePerCubicMeter, "J/m³")] + [InlineData("en-US", EnergyDensityUnit.KilojoulePerCubicMeter, "kJ/m³")] + [InlineData("en-US", EnergyDensityUnit.KilowattHourPerCubicMeter, "kWh/m³")] + [InlineData("en-US", EnergyDensityUnit.MegajoulePerCubicMeter, "MJ/m³")] + [InlineData("en-US", EnergyDensityUnit.MegawattHourPerCubicMeter, "MWh/m³")] + [InlineData("en-US", EnergyDensityUnit.PetajoulePerCubicMeter, "PJ/m³")] + [InlineData("en-US", EnergyDensityUnit.PetawattHourPerCubicMeter, "PWh/m³")] + [InlineData("en-US", EnergyDensityUnit.TerajoulePerCubicMeter, "TJ/m³")] + [InlineData("en-US", EnergyDensityUnit.TerawattHourPerCubicMeter, "TWh/m³")] + [InlineData("en-US", EnergyDensityUnit.WattHourPerCubicMeter, "Wh/m³")] + public void GetAbbreviationForCulture(string culture, EnergyDensityUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = EnergyDensity.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(EnergyDensity.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = EnergyDensity.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(EnergyDensityUnit unit) @@ -735,6 +661,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); }); } @@ -758,43 +685,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] @@ -840,8 +769,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); @@ -879,34 +806,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = EnergyDensity.FromJoulesPerCubicMeter(1); - Assert.True(v.Equals(EnergyDensity.FromJoulesPerCubicMeter(1), JoulesPerCubicMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(EnergyDensity.Zero, JoulesPerCubicMeterTolerance, ComparisonType.Relative)); - Assert.True(EnergyDensity.FromJoulesPerCubicMeter(100).Equals(EnergyDensity.FromJoulesPerCubicMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(EnergyDensity.FromJoulesPerCubicMeter(100).Equals(EnergyDensity.FromJoulesPerCubicMeter(120), 0.1, ComparisonType.Relative)); + EnergyDensity joulepercubicmeter = EnergyDensity.FromJoulesPerCubicMeter(1); + Assert.False(joulepercubicmeter.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = EnergyDensity.FromJoulesPerCubicMeter(1); - Assert.Throws(() => v.Equals(EnergyDensity.FromJoulesPerCubicMeter(1), -1, ComparisonType.Relative)); + EnergyDensity joulepercubicmeter = EnergyDensity.FromJoulesPerCubicMeter(1); + Assert.False(joulepercubicmeter.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - EnergyDensity joulepercubicmeter = EnergyDensity.FromJoulesPerCubicMeter(1); - Assert.False(joulepercubicmeter.Equals(new object())); + var quantity = EnergyDensity.FromJoulesPerCubicMeter(firstValue); + var otherQuantity = EnergyDensity.FromJoulesPerCubicMeter(secondValue); + EnergyDensity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - EnergyDensity joulepercubicmeter = EnergyDensity.FromJoulesPerCubicMeter(1); - Assert.False(joulepercubicmeter.Equals(null)); + var quantity = EnergyDensity.FromJoulesPerCubicMeter(1); + var negativeTolerance = EnergyDensity.FromJoulesPerCubicMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -925,6 +861,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() { @@ -1005,158 +953,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = EnergyDensity.FromJoulesPerCubicMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = EnergyDensity.FromJoulesPerCubicMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = EnergyDensity.FromJoulesPerCubicMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = EnergyDensity.FromJoulesPerCubicMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = EnergyDensity.FromJoulesPerCubicMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = EnergyDensity.FromJoulesPerCubicMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = EnergyDensity.FromJoulesPerCubicMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = EnergyDensity.FromJoulesPerCubicMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = EnergyDensity.FromJoulesPerCubicMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = EnergyDensity.FromJoulesPerCubicMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = EnergyDensity.FromJoulesPerCubicMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = EnergyDensity.FromJoulesPerCubicMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = EnergyDensity.FromJoulesPerCubicMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = EnergyDensity.FromJoulesPerCubicMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = EnergyDensity.FromJoulesPerCubicMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = EnergyDensity.FromJoulesPerCubicMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(EnergyDensity))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = EnergyDensity.FromJoulesPerCubicMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(EnergyDensityUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = EnergyDensity.FromJoulesPerCubicMeter(1.0); - Assert.Equal(EnergyDensity.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = EnergyDensity.FromJoulesPerCubicMeter(1.0); - Assert.Equal(EnergyDensity.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = EnergyDensity.FromJoulesPerCubicMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = EnergyDensity.FromJoulesPerCubicMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = EnergyDensity.FromJoulesPerCubicMeter(1.0); - Assert.Equal(new {EnergyDensity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 99008357b7..63687af5f6 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyTestsBase.g.cs @@ -252,7 +252,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Energy(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -265,15 +265,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Energy_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + EnergyUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Energy(1, EnergyUnit.Joule); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Energy.Zero, quantityInfo.Zero); Assert.Equal("Energy", quantityInfo.Name); + Assert.Equal(Energy.Zero, quantityInfo.Zero); + Assert.Equal(Energy.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Energy.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void EnergyInfo_CreateWithCustomUnitInfos() + { + EnergyUnit[] expectedUnits = [EnergyUnit.Joule]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -326,163 +344,163 @@ public void JouleToEnergyUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Energy.From(1, EnergyUnit.BritishThermalUnit); - AssertEx.EqualTolerance(1, quantity00.BritishThermalUnits, BritishThermalUnitsTolerance); + Assert.Equal(1, quantity00.BritishThermalUnits); Assert.Equal(EnergyUnit.BritishThermalUnit, quantity00.Unit); var quantity01 = Energy.From(1, EnergyUnit.Calorie); - AssertEx.EqualTolerance(1, quantity01.Calories, CaloriesTolerance); + Assert.Equal(1, quantity01.Calories); Assert.Equal(EnergyUnit.Calorie, quantity01.Unit); var quantity02 = Energy.From(1, EnergyUnit.DecathermEc); - AssertEx.EqualTolerance(1, quantity02.DecathermsEc, DecathermsEcTolerance); + Assert.Equal(1, quantity02.DecathermsEc); Assert.Equal(EnergyUnit.DecathermEc, quantity02.Unit); var quantity03 = Energy.From(1, EnergyUnit.DecathermImperial); - AssertEx.EqualTolerance(1, quantity03.DecathermsImperial, DecathermsImperialTolerance); + Assert.Equal(1, quantity03.DecathermsImperial); Assert.Equal(EnergyUnit.DecathermImperial, quantity03.Unit); var quantity04 = Energy.From(1, EnergyUnit.DecathermUs); - AssertEx.EqualTolerance(1, quantity04.DecathermsUs, DecathermsUsTolerance); + Assert.Equal(1, quantity04.DecathermsUs); Assert.Equal(EnergyUnit.DecathermUs, quantity04.Unit); var quantity05 = Energy.From(1, EnergyUnit.ElectronVolt); - AssertEx.EqualTolerance(1, quantity05.ElectronVolts, ElectronVoltsTolerance); + Assert.Equal(1, quantity05.ElectronVolts); Assert.Equal(EnergyUnit.ElectronVolt, quantity05.Unit); var quantity06 = Energy.From(1, EnergyUnit.Erg); - AssertEx.EqualTolerance(1, quantity06.Ergs, ErgsTolerance); + Assert.Equal(1, quantity06.Ergs); Assert.Equal(EnergyUnit.Erg, quantity06.Unit); var quantity07 = Energy.From(1, EnergyUnit.FootPound); - AssertEx.EqualTolerance(1, quantity07.FootPounds, FootPoundsTolerance); + Assert.Equal(1, quantity07.FootPounds); Assert.Equal(EnergyUnit.FootPound, quantity07.Unit); var quantity08 = Energy.From(1, EnergyUnit.GigabritishThermalUnit); - AssertEx.EqualTolerance(1, quantity08.GigabritishThermalUnits, GigabritishThermalUnitsTolerance); + Assert.Equal(1, quantity08.GigabritishThermalUnits); Assert.Equal(EnergyUnit.GigabritishThermalUnit, quantity08.Unit); var quantity09 = Energy.From(1, EnergyUnit.GigaelectronVolt); - AssertEx.EqualTolerance(1, quantity09.GigaelectronVolts, GigaelectronVoltsTolerance); + Assert.Equal(1, quantity09.GigaelectronVolts); Assert.Equal(EnergyUnit.GigaelectronVolt, quantity09.Unit); var quantity10 = Energy.From(1, EnergyUnit.Gigajoule); - AssertEx.EqualTolerance(1, quantity10.Gigajoules, GigajoulesTolerance); + Assert.Equal(1, quantity10.Gigajoules); Assert.Equal(EnergyUnit.Gigajoule, quantity10.Unit); var quantity11 = Energy.From(1, EnergyUnit.GigawattDay); - AssertEx.EqualTolerance(1, quantity11.GigawattDays, GigawattDaysTolerance); + Assert.Equal(1, quantity11.GigawattDays); Assert.Equal(EnergyUnit.GigawattDay, quantity11.Unit); var quantity12 = Energy.From(1, EnergyUnit.GigawattHour); - AssertEx.EqualTolerance(1, quantity12.GigawattHours, GigawattHoursTolerance); + Assert.Equal(1, quantity12.GigawattHours); Assert.Equal(EnergyUnit.GigawattHour, quantity12.Unit); var quantity13 = Energy.From(1, EnergyUnit.HorsepowerHour); - AssertEx.EqualTolerance(1, quantity13.HorsepowerHours, HorsepowerHoursTolerance); + Assert.Equal(1, quantity13.HorsepowerHours); Assert.Equal(EnergyUnit.HorsepowerHour, quantity13.Unit); var quantity14 = Energy.From(1, EnergyUnit.Joule); - AssertEx.EqualTolerance(1, quantity14.Joules, JoulesTolerance); + Assert.Equal(1, quantity14.Joules); Assert.Equal(EnergyUnit.Joule, quantity14.Unit); var quantity15 = Energy.From(1, EnergyUnit.KilobritishThermalUnit); - AssertEx.EqualTolerance(1, quantity15.KilobritishThermalUnits, KilobritishThermalUnitsTolerance); + Assert.Equal(1, quantity15.KilobritishThermalUnits); Assert.Equal(EnergyUnit.KilobritishThermalUnit, quantity15.Unit); var quantity16 = Energy.From(1, EnergyUnit.Kilocalorie); - AssertEx.EqualTolerance(1, quantity16.Kilocalories, KilocaloriesTolerance); + Assert.Equal(1, quantity16.Kilocalories); Assert.Equal(EnergyUnit.Kilocalorie, quantity16.Unit); var quantity17 = Energy.From(1, EnergyUnit.KiloelectronVolt); - AssertEx.EqualTolerance(1, quantity17.KiloelectronVolts, KiloelectronVoltsTolerance); + Assert.Equal(1, quantity17.KiloelectronVolts); Assert.Equal(EnergyUnit.KiloelectronVolt, quantity17.Unit); var quantity18 = Energy.From(1, EnergyUnit.Kilojoule); - AssertEx.EqualTolerance(1, quantity18.Kilojoules, KilojoulesTolerance); + Assert.Equal(1, quantity18.Kilojoules); Assert.Equal(EnergyUnit.Kilojoule, quantity18.Unit); var quantity19 = Energy.From(1, EnergyUnit.KilowattDay); - AssertEx.EqualTolerance(1, quantity19.KilowattDays, KilowattDaysTolerance); + Assert.Equal(1, quantity19.KilowattDays); Assert.Equal(EnergyUnit.KilowattDay, quantity19.Unit); var quantity20 = Energy.From(1, EnergyUnit.KilowattHour); - AssertEx.EqualTolerance(1, quantity20.KilowattHours, KilowattHoursTolerance); + Assert.Equal(1, quantity20.KilowattHours); Assert.Equal(EnergyUnit.KilowattHour, quantity20.Unit); var quantity21 = Energy.From(1, EnergyUnit.MegabritishThermalUnit); - AssertEx.EqualTolerance(1, quantity21.MegabritishThermalUnits, MegabritishThermalUnitsTolerance); + Assert.Equal(1, quantity21.MegabritishThermalUnits); Assert.Equal(EnergyUnit.MegabritishThermalUnit, quantity21.Unit); var quantity22 = Energy.From(1, EnergyUnit.Megacalorie); - AssertEx.EqualTolerance(1, quantity22.Megacalories, MegacaloriesTolerance); + Assert.Equal(1, quantity22.Megacalories); Assert.Equal(EnergyUnit.Megacalorie, quantity22.Unit); var quantity23 = Energy.From(1, EnergyUnit.MegaelectronVolt); - AssertEx.EqualTolerance(1, quantity23.MegaelectronVolts, MegaelectronVoltsTolerance); + Assert.Equal(1, quantity23.MegaelectronVolts); Assert.Equal(EnergyUnit.MegaelectronVolt, quantity23.Unit); var quantity24 = Energy.From(1, EnergyUnit.Megajoule); - AssertEx.EqualTolerance(1, quantity24.Megajoules, MegajoulesTolerance); + Assert.Equal(1, quantity24.Megajoules); Assert.Equal(EnergyUnit.Megajoule, quantity24.Unit); var quantity25 = Energy.From(1, EnergyUnit.MegawattDay); - AssertEx.EqualTolerance(1, quantity25.MegawattDays, MegawattDaysTolerance); + Assert.Equal(1, quantity25.MegawattDays); Assert.Equal(EnergyUnit.MegawattDay, quantity25.Unit); var quantity26 = Energy.From(1, EnergyUnit.MegawattHour); - AssertEx.EqualTolerance(1, quantity26.MegawattHours, MegawattHoursTolerance); + Assert.Equal(1, quantity26.MegawattHours); Assert.Equal(EnergyUnit.MegawattHour, quantity26.Unit); var quantity27 = Energy.From(1, EnergyUnit.Microjoule); - AssertEx.EqualTolerance(1, quantity27.Microjoules, MicrojoulesTolerance); + Assert.Equal(1, quantity27.Microjoules); Assert.Equal(EnergyUnit.Microjoule, quantity27.Unit); var quantity28 = Energy.From(1, EnergyUnit.Millijoule); - AssertEx.EqualTolerance(1, quantity28.Millijoules, MillijoulesTolerance); + Assert.Equal(1, quantity28.Millijoules); Assert.Equal(EnergyUnit.Millijoule, quantity28.Unit); var quantity29 = Energy.From(1, EnergyUnit.Nanojoule); - AssertEx.EqualTolerance(1, quantity29.Nanojoules, NanojoulesTolerance); + Assert.Equal(1, quantity29.Nanojoules); Assert.Equal(EnergyUnit.Nanojoule, quantity29.Unit); var quantity30 = Energy.From(1, EnergyUnit.Petajoule); - AssertEx.EqualTolerance(1, quantity30.Petajoules, PetajoulesTolerance); + Assert.Equal(1, quantity30.Petajoules); Assert.Equal(EnergyUnit.Petajoule, quantity30.Unit); var quantity31 = Energy.From(1, EnergyUnit.TeraelectronVolt); - AssertEx.EqualTolerance(1, quantity31.TeraelectronVolts, TeraelectronVoltsTolerance); + Assert.Equal(1, quantity31.TeraelectronVolts); Assert.Equal(EnergyUnit.TeraelectronVolt, quantity31.Unit); var quantity32 = Energy.From(1, EnergyUnit.Terajoule); - AssertEx.EqualTolerance(1, quantity32.Terajoules, TerajoulesTolerance); + Assert.Equal(1, quantity32.Terajoules); Assert.Equal(EnergyUnit.Terajoule, quantity32.Unit); var quantity33 = Energy.From(1, EnergyUnit.TerawattDay); - AssertEx.EqualTolerance(1, quantity33.TerawattDays, TerawattDaysTolerance); + Assert.Equal(1, quantity33.TerawattDays); Assert.Equal(EnergyUnit.TerawattDay, quantity33.Unit); var quantity34 = Energy.From(1, EnergyUnit.TerawattHour); - AssertEx.EqualTolerance(1, quantity34.TerawattHours, TerawattHoursTolerance); + Assert.Equal(1, quantity34.TerawattHours); Assert.Equal(EnergyUnit.TerawattHour, quantity34.Unit); var quantity35 = Energy.From(1, EnergyUnit.ThermEc); - AssertEx.EqualTolerance(1, quantity35.ThermsEc, ThermsEcTolerance); + Assert.Equal(1, quantity35.ThermsEc); Assert.Equal(EnergyUnit.ThermEc, quantity35.Unit); var quantity36 = Energy.From(1, EnergyUnit.ThermImperial); - AssertEx.EqualTolerance(1, quantity36.ThermsImperial, ThermsImperialTolerance); + Assert.Equal(1, quantity36.ThermsImperial); Assert.Equal(EnergyUnit.ThermImperial, quantity36.Unit); var quantity37 = Energy.From(1, EnergyUnit.ThermUs); - AssertEx.EqualTolerance(1, quantity37.ThermsUs, ThermsUsTolerance); + Assert.Equal(1, quantity37.ThermsUs); Assert.Equal(EnergyUnit.ThermUs, quantity37.Unit); var quantity38 = Energy.From(1, EnergyUnit.WattDay); - AssertEx.EqualTolerance(1, quantity38.WattDays, WattDaysTolerance); + Assert.Equal(1, quantity38.WattDays); Assert.Equal(EnergyUnit.WattDay, quantity38.Unit); var quantity39 = Energy.From(1, EnergyUnit.WattHour); - AssertEx.EqualTolerance(1, quantity39.WattHours, WattHoursTolerance); + Assert.Equal(1, quantity39.WattHours); Assert.Equal(EnergyUnit.WattHour, quantity39.Unit); } @@ -657,795 +675,144 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 BTU", EnergyUnit.BritishThermalUnit, 4.2)] + [InlineData("en-US", "4.2 cal", EnergyUnit.Calorie, 4.2)] + [InlineData("en-US", "4.2 Dth (E.C.)", EnergyUnit.DecathermEc, 4.2)] + [InlineData("en-US", "4.2 Dth (imp.)", EnergyUnit.DecathermImperial, 4.2)] + [InlineData("en-US", "4.2 Dth (U.S.)", EnergyUnit.DecathermUs, 4.2)] + [InlineData("en-US", "4.2 eV", EnergyUnit.ElectronVolt, 4.2)] + [InlineData("en-US", "4.2 erg", EnergyUnit.Erg, 4.2)] + [InlineData("en-US", "4.2 ft·lb", EnergyUnit.FootPound, 4.2)] + [InlineData("en-US", "4.2 GBTU", EnergyUnit.GigabritishThermalUnit, 4.2)] + [InlineData("en-US", "4.2 GeV", EnergyUnit.GigaelectronVolt, 4.2)] + [InlineData("en-US", "4.2 GJ", EnergyUnit.Gigajoule, 4.2)] + [InlineData("en-US", "4.2 GWd", EnergyUnit.GigawattDay, 4.2)] + [InlineData("en-US", "4.2 GWh", EnergyUnit.GigawattHour, 4.2)] + [InlineData("en-US", "4.2 hp·h", EnergyUnit.HorsepowerHour, 4.2)] + [InlineData("en-US", "4.2 J", EnergyUnit.Joule, 4.2)] + [InlineData("en-US", "4.2 kBTU", EnergyUnit.KilobritishThermalUnit, 4.2)] + [InlineData("en-US", "4.2 kcal", EnergyUnit.Kilocalorie, 4.2)] + [InlineData("en-US", "4.2 keV", EnergyUnit.KiloelectronVolt, 4.2)] + [InlineData("en-US", "4.2 kJ", EnergyUnit.Kilojoule, 4.2)] + [InlineData("en-US", "4.2 kWd", EnergyUnit.KilowattDay, 4.2)] + [InlineData("en-US", "4.2 kWh", EnergyUnit.KilowattHour, 4.2)] + [InlineData("en-US", "4.2 MBTU", EnergyUnit.MegabritishThermalUnit, 4.2)] + [InlineData("en-US", "4.2 Mcal", EnergyUnit.Megacalorie, 4.2)] + [InlineData("en-US", "4.2 MeV", EnergyUnit.MegaelectronVolt, 4.2)] + [InlineData("en-US", "4.2 MJ", EnergyUnit.Megajoule, 4.2)] + [InlineData("en-US", "4.2 MWd", EnergyUnit.MegawattDay, 4.2)] + [InlineData("en-US", "4.2 MWh", EnergyUnit.MegawattHour, 4.2)] + [InlineData("en-US", "4.2 µJ", EnergyUnit.Microjoule, 4.2)] + [InlineData("en-US", "4.2 mJ", EnergyUnit.Millijoule, 4.2)] + [InlineData("en-US", "4.2 nJ", EnergyUnit.Nanojoule, 4.2)] + [InlineData("en-US", "4.2 PJ", EnergyUnit.Petajoule, 4.2)] + [InlineData("en-US", "4.2 TeV", EnergyUnit.TeraelectronVolt, 4.2)] + [InlineData("en-US", "4.2 TJ", EnergyUnit.Terajoule, 4.2)] + [InlineData("en-US", "4.2 TWd", EnergyUnit.TerawattDay, 4.2)] + [InlineData("en-US", "4.2 TWh", EnergyUnit.TerawattHour, 4.2)] + [InlineData("en-US", "4.2 th (E.C.)", EnergyUnit.ThermEc, 4.2)] + [InlineData("en-US", "4.2 th (imp.)", EnergyUnit.ThermImperial, 4.2)] + [InlineData("en-US", "4.2 th (U.S.)", EnergyUnit.ThermUs, 4.2)] + [InlineData("en-US", "4.2 Wd", EnergyUnit.WattDay, 4.2)] + [InlineData("en-US", "4.2 Wh", EnergyUnit.WattHour, 4.2)] + [InlineData("ru-RU", "4,2 Европейский декатерм", EnergyUnit.DecathermEc, 4.2)] + [InlineData("ru-RU", "4,2 Английский декатерм", EnergyUnit.DecathermImperial, 4.2)] + [InlineData("ru-RU", "4,2 Американский декатерм", EnergyUnit.DecathermUs, 4.2)] + [InlineData("ru-RU", "4,2 эВ", EnergyUnit.ElectronVolt, 4.2)] + [InlineData("ru-RU", "4,2 ГэВ", EnergyUnit.GigaelectronVolt, 4.2)] + [InlineData("ru-RU", "4,2 ГВт/д", EnergyUnit.GigawattDay, 4.2)] + [InlineData("ru-RU", "4,2 ГВт/ч", EnergyUnit.GigawattHour, 4.2)] + [InlineData("ru-RU", "4,2 кэВ", EnergyUnit.KiloelectronVolt, 4.2)] + [InlineData("ru-RU", "4,2 кВт/д", EnergyUnit.KilowattDay, 4.2)] + [InlineData("ru-RU", "4,2 кВт/ч", EnergyUnit.KilowattHour, 4.2)] + [InlineData("ru-RU", "4,2 МэВ", EnergyUnit.MegaelectronVolt, 4.2)] + [InlineData("ru-RU", "4,2 МВт/д", EnergyUnit.MegawattDay, 4.2)] + [InlineData("ru-RU", "4,2 МВт/ч", EnergyUnit.MegawattHour, 4.2)] + [InlineData("ru-RU", "4,2 ТэВ", EnergyUnit.TeraelectronVolt, 4.2)] + [InlineData("ru-RU", "4,2 ТВт/д", EnergyUnit.TerawattDay, 4.2)] + [InlineData("ru-RU", "4,2 ТВт/ч", EnergyUnit.TerawattHour, 4.2)] + [InlineData("ru-RU", "4,2 Европейский терм", EnergyUnit.ThermEc, 4.2)] + [InlineData("ru-RU", "4,2 Английский терм", EnergyUnit.ThermImperial, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = Energy.Parse("1 BTU", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.BritishThermalUnits, BritishThermalUnitsTolerance); - Assert.Equal(EnergyUnit.BritishThermalUnit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 cal", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Calories, CaloriesTolerance); - Assert.Equal(EnergyUnit.Calorie, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 Dth (E.C.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecathermsEc, DecathermsEcTolerance); - Assert.Equal(EnergyUnit.DecathermEc, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 Европейский декатерм", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.DecathermsEc, DecathermsEcTolerance); - Assert.Equal(EnergyUnit.DecathermEc, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 Dth (imp.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecathermsImperial, DecathermsImperialTolerance); - Assert.Equal(EnergyUnit.DecathermImperial, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 Английский декатерм", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.DecathermsImperial, DecathermsImperialTolerance); - Assert.Equal(EnergyUnit.DecathermImperial, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 Dth (U.S.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecathermsUs, DecathermsUsTolerance); - Assert.Equal(EnergyUnit.DecathermUs, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 Американский декатерм", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.DecathermsUs, DecathermsUsTolerance); - Assert.Equal(EnergyUnit.DecathermUs, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 eV", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ElectronVolts, ElectronVoltsTolerance); - Assert.Equal(EnergyUnit.ElectronVolt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 эВ", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.ElectronVolts, ElectronVoltsTolerance); - Assert.Equal(EnergyUnit.ElectronVolt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 erg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Ergs, ErgsTolerance); - Assert.Equal(EnergyUnit.Erg, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 ft·lb", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.FootPounds, FootPoundsTolerance); - Assert.Equal(EnergyUnit.FootPound, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 GBTU", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GigabritishThermalUnits, GigabritishThermalUnitsTolerance); - Assert.Equal(EnergyUnit.GigabritishThermalUnit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 GeV", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GigaelectronVolts, GigaelectronVoltsTolerance); - Assert.Equal(EnergyUnit.GigaelectronVolt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 ГэВ", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.GigaelectronVolts, GigaelectronVoltsTolerance); - Assert.Equal(EnergyUnit.GigaelectronVolt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 GJ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Gigajoules, GigajoulesTolerance); - Assert.Equal(EnergyUnit.Gigajoule, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 GWd", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GigawattDays, GigawattDaysTolerance); - Assert.Equal(EnergyUnit.GigawattDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 ГВт/д", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.GigawattDays, GigawattDaysTolerance); - Assert.Equal(EnergyUnit.GigawattDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 GWh", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GigawattHours, GigawattHoursTolerance); - Assert.Equal(EnergyUnit.GigawattHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 ГВт/ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.GigawattHours, GigawattHoursTolerance); - Assert.Equal(EnergyUnit.GigawattHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 hp·h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.HorsepowerHours, HorsepowerHoursTolerance); - Assert.Equal(EnergyUnit.HorsepowerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 J", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Joules, JoulesTolerance); - Assert.Equal(EnergyUnit.Joule, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 kBTU", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilobritishThermalUnits, KilobritishThermalUnitsTolerance); - Assert.Equal(EnergyUnit.KilobritishThermalUnit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 kcal", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilocalories, KilocaloriesTolerance); - Assert.Equal(EnergyUnit.Kilocalorie, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 keV", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KiloelectronVolts, KiloelectronVoltsTolerance); - Assert.Equal(EnergyUnit.KiloelectronVolt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 кэВ", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KiloelectronVolts, KiloelectronVoltsTolerance); - Assert.Equal(EnergyUnit.KiloelectronVolt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 kJ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilojoules, KilojoulesTolerance); - Assert.Equal(EnergyUnit.Kilojoule, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 kWd", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilowattDays, KilowattDaysTolerance); - Assert.Equal(EnergyUnit.KilowattDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 кВт/д", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilowattDays, KilowattDaysTolerance); - Assert.Equal(EnergyUnit.KilowattDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 kWh", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilowattHours, KilowattHoursTolerance); - Assert.Equal(EnergyUnit.KilowattHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 кВт/ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilowattHours, KilowattHoursTolerance); - Assert.Equal(EnergyUnit.KilowattHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 MBTU", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegabritishThermalUnits, MegabritishThermalUnitsTolerance); - Assert.Equal(EnergyUnit.MegabritishThermalUnit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 Mcal", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megacalories, MegacaloriesTolerance); - Assert.Equal(EnergyUnit.Megacalorie, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 MeV", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegaelectronVolts, MegaelectronVoltsTolerance); - Assert.Equal(EnergyUnit.MegaelectronVolt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 МэВ", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MegaelectronVolts, MegaelectronVoltsTolerance); - Assert.Equal(EnergyUnit.MegaelectronVolt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 MJ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megajoules, MegajoulesTolerance); - Assert.Equal(EnergyUnit.Megajoule, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 MWd", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegawattDays, MegawattDaysTolerance); - Assert.Equal(EnergyUnit.MegawattDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 МВт/д", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MegawattDays, MegawattDaysTolerance); - Assert.Equal(EnergyUnit.MegawattDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 MWh", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegawattHours, MegawattHoursTolerance); - Assert.Equal(EnergyUnit.MegawattHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 МВт/ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MegawattHours, MegawattHoursTolerance); - Assert.Equal(EnergyUnit.MegawattHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 µJ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microjoules, MicrojoulesTolerance); - Assert.Equal(EnergyUnit.Microjoule, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 mJ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millijoules, MillijoulesTolerance); - Assert.Equal(EnergyUnit.Millijoule, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 nJ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanojoules, NanojoulesTolerance); - Assert.Equal(EnergyUnit.Nanojoule, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 PJ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Petajoules, PetajoulesTolerance); - Assert.Equal(EnergyUnit.Petajoule, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 TeV", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TeraelectronVolts, TeraelectronVoltsTolerance); - Assert.Equal(EnergyUnit.TeraelectronVolt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 ТэВ", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.TeraelectronVolts, TeraelectronVoltsTolerance); - Assert.Equal(EnergyUnit.TeraelectronVolt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 TJ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Terajoules, TerajoulesTolerance); - Assert.Equal(EnergyUnit.Terajoule, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 TWd", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TerawattDays, TerawattDaysTolerance); - Assert.Equal(EnergyUnit.TerawattDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 ТВт/д", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.TerawattDays, TerawattDaysTolerance); - Assert.Equal(EnergyUnit.TerawattDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 TWh", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TerawattHours, TerawattHoursTolerance); - Assert.Equal(EnergyUnit.TerawattHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 ТВт/ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.TerawattHours, TerawattHoursTolerance); - Assert.Equal(EnergyUnit.TerawattHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 th (E.C.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ThermsEc, ThermsEcTolerance); - Assert.Equal(EnergyUnit.ThermEc, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 Европейский терм", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.ThermsEc, ThermsEcTolerance); - Assert.Equal(EnergyUnit.ThermEc, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 th (imp.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ThermsImperial, ThermsImperialTolerance); - Assert.Equal(EnergyUnit.ThermImperial, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 Английский терм", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.ThermsImperial, ThermsImperialTolerance); - Assert.Equal(EnergyUnit.ThermImperial, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 th (U.S.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ThermsUs, ThermsUsTolerance); - Assert.Equal(EnergyUnit.ThermUs, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 Американский терм", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.ThermsUs, ThermsUsTolerance); - Assert.Equal(EnergyUnit.ThermUs, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 Wd", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WattDays, WattDaysTolerance); - Assert.Equal(EnergyUnit.WattDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 Вт/д", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.WattDays, WattDaysTolerance); - Assert.Equal(EnergyUnit.WattDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 Wh", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WattHours, WattHoursTolerance); - Assert.Equal(EnergyUnit.WattHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Energy.Parse("1 Вт/ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.WattHours, WattHoursTolerance); - Assert.Equal(EnergyUnit.WattHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Energy.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 BTU", EnergyUnit.BritishThermalUnit, 4.2)] + [InlineData("en-US", "4.2 cal", EnergyUnit.Calorie, 4.2)] + [InlineData("en-US", "4.2 Dth (E.C.)", EnergyUnit.DecathermEc, 4.2)] + [InlineData("en-US", "4.2 Dth (imp.)", EnergyUnit.DecathermImperial, 4.2)] + [InlineData("en-US", "4.2 Dth (U.S.)", EnergyUnit.DecathermUs, 4.2)] + [InlineData("en-US", "4.2 eV", EnergyUnit.ElectronVolt, 4.2)] + [InlineData("en-US", "4.2 erg", EnergyUnit.Erg, 4.2)] + [InlineData("en-US", "4.2 ft·lb", EnergyUnit.FootPound, 4.2)] + [InlineData("en-US", "4.2 GBTU", EnergyUnit.GigabritishThermalUnit, 4.2)] + [InlineData("en-US", "4.2 GeV", EnergyUnit.GigaelectronVolt, 4.2)] + [InlineData("en-US", "4.2 GJ", EnergyUnit.Gigajoule, 4.2)] + [InlineData("en-US", "4.2 GWd", EnergyUnit.GigawattDay, 4.2)] + [InlineData("en-US", "4.2 GWh", EnergyUnit.GigawattHour, 4.2)] + [InlineData("en-US", "4.2 hp·h", EnergyUnit.HorsepowerHour, 4.2)] + [InlineData("en-US", "4.2 J", EnergyUnit.Joule, 4.2)] + [InlineData("en-US", "4.2 kBTU", EnergyUnit.KilobritishThermalUnit, 4.2)] + [InlineData("en-US", "4.2 kcal", EnergyUnit.Kilocalorie, 4.2)] + [InlineData("en-US", "4.2 keV", EnergyUnit.KiloelectronVolt, 4.2)] + [InlineData("en-US", "4.2 kJ", EnergyUnit.Kilojoule, 4.2)] + [InlineData("en-US", "4.2 kWd", EnergyUnit.KilowattDay, 4.2)] + [InlineData("en-US", "4.2 kWh", EnergyUnit.KilowattHour, 4.2)] + [InlineData("en-US", "4.2 MBTU", EnergyUnit.MegabritishThermalUnit, 4.2)] + [InlineData("en-US", "4.2 Mcal", EnergyUnit.Megacalorie, 4.2)] + [InlineData("en-US", "4.2 MeV", EnergyUnit.MegaelectronVolt, 4.2)] + [InlineData("en-US", "4.2 MJ", EnergyUnit.Megajoule, 4.2)] + [InlineData("en-US", "4.2 MWd", EnergyUnit.MegawattDay, 4.2)] + [InlineData("en-US", "4.2 MWh", EnergyUnit.MegawattHour, 4.2)] + [InlineData("en-US", "4.2 µJ", EnergyUnit.Microjoule, 4.2)] + [InlineData("en-US", "4.2 mJ", EnergyUnit.Millijoule, 4.2)] + [InlineData("en-US", "4.2 nJ", EnergyUnit.Nanojoule, 4.2)] + [InlineData("en-US", "4.2 PJ", EnergyUnit.Petajoule, 4.2)] + [InlineData("en-US", "4.2 TeV", EnergyUnit.TeraelectronVolt, 4.2)] + [InlineData("en-US", "4.2 TJ", EnergyUnit.Terajoule, 4.2)] + [InlineData("en-US", "4.2 TWd", EnergyUnit.TerawattDay, 4.2)] + [InlineData("en-US", "4.2 TWh", EnergyUnit.TerawattHour, 4.2)] + [InlineData("en-US", "4.2 th (E.C.)", EnergyUnit.ThermEc, 4.2)] + [InlineData("en-US", "4.2 th (imp.)", EnergyUnit.ThermImperial, 4.2)] + [InlineData("en-US", "4.2 th (U.S.)", EnergyUnit.ThermUs, 4.2)] + [InlineData("en-US", "4.2 Wd", EnergyUnit.WattDay, 4.2)] + [InlineData("en-US", "4.2 Wh", EnergyUnit.WattHour, 4.2)] + [InlineData("ru-RU", "4,2 Европейский декатерм", EnergyUnit.DecathermEc, 4.2)] + [InlineData("ru-RU", "4,2 Английский декатерм", EnergyUnit.DecathermImperial, 4.2)] + [InlineData("ru-RU", "4,2 Американский декатерм", EnergyUnit.DecathermUs, 4.2)] + [InlineData("ru-RU", "4,2 эВ", EnergyUnit.ElectronVolt, 4.2)] + [InlineData("ru-RU", "4,2 ГэВ", EnergyUnit.GigaelectronVolt, 4.2)] + [InlineData("ru-RU", "4,2 ГВт/д", EnergyUnit.GigawattDay, 4.2)] + [InlineData("ru-RU", "4,2 ГВт/ч", EnergyUnit.GigawattHour, 4.2)] + [InlineData("ru-RU", "4,2 кэВ", EnergyUnit.KiloelectronVolt, 4.2)] + [InlineData("ru-RU", "4,2 кВт/д", EnergyUnit.KilowattDay, 4.2)] + [InlineData("ru-RU", "4,2 кВт/ч", EnergyUnit.KilowattHour, 4.2)] + [InlineData("ru-RU", "4,2 МэВ", EnergyUnit.MegaelectronVolt, 4.2)] + [InlineData("ru-RU", "4,2 МВт/д", EnergyUnit.MegawattDay, 4.2)] + [InlineData("ru-RU", "4,2 МВт/ч", EnergyUnit.MegawattHour, 4.2)] + [InlineData("ru-RU", "4,2 ТэВ", EnergyUnit.TeraelectronVolt, 4.2)] + [InlineData("ru-RU", "4,2 ТВт/д", EnergyUnit.TerawattDay, 4.2)] + [InlineData("ru-RU", "4,2 ТВт/ч", EnergyUnit.TerawattHour, 4.2)] + [InlineData("ru-RU", "4,2 Европейский терм", EnergyUnit.ThermEc, 4.2)] + [InlineData("ru-RU", "4,2 Английский терм", EnergyUnit.ThermImperial, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(Energy.TryParse("1 BTU", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BritishThermalUnits, BritishThermalUnitsTolerance); - Assert.Equal(EnergyUnit.BritishThermalUnit, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 cal", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Calories, CaloriesTolerance); - Assert.Equal(EnergyUnit.Calorie, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 Dth (E.C.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecathermsEc, DecathermsEcTolerance); - Assert.Equal(EnergyUnit.DecathermEc, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 Европейский декатерм", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecathermsEc, DecathermsEcTolerance); - Assert.Equal(EnergyUnit.DecathermEc, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 Dth (imp.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecathermsImperial, DecathermsImperialTolerance); - Assert.Equal(EnergyUnit.DecathermImperial, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 Английский декатерм", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecathermsImperial, DecathermsImperialTolerance); - Assert.Equal(EnergyUnit.DecathermImperial, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 Dth (U.S.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecathermsUs, DecathermsUsTolerance); - Assert.Equal(EnergyUnit.DecathermUs, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 Американский декатерм", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecathermsUs, DecathermsUsTolerance); - Assert.Equal(EnergyUnit.DecathermUs, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 eV", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ElectronVolts, ElectronVoltsTolerance); - Assert.Equal(EnergyUnit.ElectronVolt, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 эВ", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ElectronVolts, ElectronVoltsTolerance); - Assert.Equal(EnergyUnit.ElectronVolt, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 erg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Ergs, ErgsTolerance); - Assert.Equal(EnergyUnit.Erg, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 ft·lb", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.FootPounds, FootPoundsTolerance); - Assert.Equal(EnergyUnit.FootPound, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 GBTU", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigabritishThermalUnits, GigabritishThermalUnitsTolerance); - Assert.Equal(EnergyUnit.GigabritishThermalUnit, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 GeV", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigaelectronVolts, GigaelectronVoltsTolerance); - Assert.Equal(EnergyUnit.GigaelectronVolt, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 ГэВ", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigaelectronVolts, GigaelectronVoltsTolerance); - Assert.Equal(EnergyUnit.GigaelectronVolt, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 GJ", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gigajoules, GigajoulesTolerance); - Assert.Equal(EnergyUnit.Gigajoule, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 GWd", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigawattDays, GigawattDaysTolerance); - Assert.Equal(EnergyUnit.GigawattDay, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 ГВт/д", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigawattDays, GigawattDaysTolerance); - Assert.Equal(EnergyUnit.GigawattDay, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 GWh", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigawattHours, GigawattHoursTolerance); - Assert.Equal(EnergyUnit.GigawattHour, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 ГВт/ч", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigawattHours, GigawattHoursTolerance); - Assert.Equal(EnergyUnit.GigawattHour, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 hp·h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HorsepowerHours, HorsepowerHoursTolerance); - Assert.Equal(EnergyUnit.HorsepowerHour, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 J", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Joules, JoulesTolerance); - Assert.Equal(EnergyUnit.Joule, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 kBTU", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilobritishThermalUnits, KilobritishThermalUnitsTolerance); - Assert.Equal(EnergyUnit.KilobritishThermalUnit, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 kcal", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilocalories, KilocaloriesTolerance); - Assert.Equal(EnergyUnit.Kilocalorie, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 keV", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KiloelectronVolts, KiloelectronVoltsTolerance); - Assert.Equal(EnergyUnit.KiloelectronVolt, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 кэВ", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KiloelectronVolts, KiloelectronVoltsTolerance); - Assert.Equal(EnergyUnit.KiloelectronVolt, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 kJ", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilojoules, KilojoulesTolerance); - Assert.Equal(EnergyUnit.Kilojoule, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 kWd", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilowattDays, KilowattDaysTolerance); - Assert.Equal(EnergyUnit.KilowattDay, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 кВт/д", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilowattDays, KilowattDaysTolerance); - Assert.Equal(EnergyUnit.KilowattDay, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 kWh", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilowattHours, KilowattHoursTolerance); - Assert.Equal(EnergyUnit.KilowattHour, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 кВт/ч", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilowattHours, KilowattHoursTolerance); - Assert.Equal(EnergyUnit.KilowattHour, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 MBTU", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegabritishThermalUnits, MegabritishThermalUnitsTolerance); - Assert.Equal(EnergyUnit.MegabritishThermalUnit, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 Mcal", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Megacalories, MegacaloriesTolerance); - Assert.Equal(EnergyUnit.Megacalorie, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 MeV", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegaelectronVolts, MegaelectronVoltsTolerance); - Assert.Equal(EnergyUnit.MegaelectronVolt, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 МэВ", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegaelectronVolts, MegaelectronVoltsTolerance); - Assert.Equal(EnergyUnit.MegaelectronVolt, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 MWd", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegawattDays, MegawattDaysTolerance); - Assert.Equal(EnergyUnit.MegawattDay, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 МВт/д", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegawattDays, MegawattDaysTolerance); - Assert.Equal(EnergyUnit.MegawattDay, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 MWh", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegawattHours, MegawattHoursTolerance); - Assert.Equal(EnergyUnit.MegawattHour, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 МВт/ч", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegawattHours, MegawattHoursTolerance); - Assert.Equal(EnergyUnit.MegawattHour, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 µJ", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microjoules, MicrojoulesTolerance); - Assert.Equal(EnergyUnit.Microjoule, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 nJ", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanojoules, NanojoulesTolerance); - Assert.Equal(EnergyUnit.Nanojoule, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 PJ", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Petajoules, PetajoulesTolerance); - Assert.Equal(EnergyUnit.Petajoule, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 TeV", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TeraelectronVolts, TeraelectronVoltsTolerance); - Assert.Equal(EnergyUnit.TeraelectronVolt, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 ТэВ", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TeraelectronVolts, TeraelectronVoltsTolerance); - Assert.Equal(EnergyUnit.TeraelectronVolt, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 TJ", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Terajoules, TerajoulesTolerance); - Assert.Equal(EnergyUnit.Terajoule, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 TWd", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TerawattDays, TerawattDaysTolerance); - Assert.Equal(EnergyUnit.TerawattDay, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 ТВт/д", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TerawattDays, TerawattDaysTolerance); - Assert.Equal(EnergyUnit.TerawattDay, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 TWh", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TerawattHours, TerawattHoursTolerance); - Assert.Equal(EnergyUnit.TerawattHour, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 ТВт/ч", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TerawattHours, TerawattHoursTolerance); - Assert.Equal(EnergyUnit.TerawattHour, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 th (E.C.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ThermsEc, ThermsEcTolerance); - Assert.Equal(EnergyUnit.ThermEc, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 Европейский терм", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ThermsEc, ThermsEcTolerance); - Assert.Equal(EnergyUnit.ThermEc, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 th (imp.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ThermsImperial, ThermsImperialTolerance); - Assert.Equal(EnergyUnit.ThermImperial, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 Английский терм", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ThermsImperial, ThermsImperialTolerance); - Assert.Equal(EnergyUnit.ThermImperial, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 th (U.S.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ThermsUs, ThermsUsTolerance); - Assert.Equal(EnergyUnit.ThermUs, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 Американский терм", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ThermsUs, ThermsUsTolerance); - Assert.Equal(EnergyUnit.ThermUs, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 Wd", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattDays, WattDaysTolerance); - Assert.Equal(EnergyUnit.WattDay, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 Вт/д", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattDays, WattDaysTolerance); - Assert.Equal(EnergyUnit.WattDay, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 Wh", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattHours, WattHoursTolerance); - Assert.Equal(EnergyUnit.WattHour, parsed.Unit); - } - - { - Assert.True(Energy.TryParse("1 Вт/ч", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattHours, WattHoursTolerance); - Assert.Equal(EnergyUnit.WattHour, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Energy.TryParse(quantityString, out Energy parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -1918,6 +1285,87 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Energy Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", EnergyUnit.BritishThermalUnit, "BTU")] + [InlineData("en-US", EnergyUnit.Calorie, "cal")] + [InlineData("en-US", EnergyUnit.DecathermEc, "Dth (E.C.)")] + [InlineData("en-US", EnergyUnit.DecathermImperial, "Dth (imp.)")] + [InlineData("en-US", EnergyUnit.DecathermUs, "Dth (U.S.)")] + [InlineData("en-US", EnergyUnit.ElectronVolt, "eV")] + [InlineData("en-US", EnergyUnit.Erg, "erg")] + [InlineData("en-US", EnergyUnit.FootPound, "ft·lb")] + [InlineData("en-US", EnergyUnit.GigabritishThermalUnit, "GBTU")] + [InlineData("en-US", EnergyUnit.GigaelectronVolt, "GeV")] + [InlineData("en-US", EnergyUnit.Gigajoule, "GJ")] + [InlineData("en-US", EnergyUnit.GigawattDay, "GWd")] + [InlineData("en-US", EnergyUnit.GigawattHour, "GWh")] + [InlineData("en-US", EnergyUnit.HorsepowerHour, "hp·h")] + [InlineData("en-US", EnergyUnit.Joule, "J")] + [InlineData("en-US", EnergyUnit.KilobritishThermalUnit, "kBTU")] + [InlineData("en-US", EnergyUnit.Kilocalorie, "kcal")] + [InlineData("en-US", EnergyUnit.KiloelectronVolt, "keV")] + [InlineData("en-US", EnergyUnit.Kilojoule, "kJ")] + [InlineData("en-US", EnergyUnit.KilowattDay, "kWd")] + [InlineData("en-US", EnergyUnit.KilowattHour, "kWh")] + [InlineData("en-US", EnergyUnit.MegabritishThermalUnit, "MBTU")] + [InlineData("en-US", EnergyUnit.Megacalorie, "Mcal")] + [InlineData("en-US", EnergyUnit.MegaelectronVolt, "MeV")] + [InlineData("en-US", EnergyUnit.Megajoule, "MJ")] + [InlineData("en-US", EnergyUnit.MegawattDay, "MWd")] + [InlineData("en-US", EnergyUnit.MegawattHour, "MWh")] + [InlineData("en-US", EnergyUnit.Microjoule, "µJ")] + [InlineData("en-US", EnergyUnit.Millijoule, "mJ")] + [InlineData("en-US", EnergyUnit.Nanojoule, "nJ")] + [InlineData("en-US", EnergyUnit.Petajoule, "PJ")] + [InlineData("en-US", EnergyUnit.TeraelectronVolt, "TeV")] + [InlineData("en-US", EnergyUnit.Terajoule, "TJ")] + [InlineData("en-US", EnergyUnit.TerawattDay, "TWd")] + [InlineData("en-US", EnergyUnit.TerawattHour, "TWh")] + [InlineData("en-US", EnergyUnit.ThermEc, "th (E.C.)")] + [InlineData("en-US", EnergyUnit.ThermImperial, "th (imp.)")] + [InlineData("en-US", EnergyUnit.ThermUs, "th (U.S.)")] + [InlineData("en-US", EnergyUnit.WattDay, "Wd")] + [InlineData("en-US", EnergyUnit.WattHour, "Wh")] + [InlineData("ru-RU", EnergyUnit.DecathermEc, "Европейский декатерм")] + [InlineData("ru-RU", EnergyUnit.DecathermImperial, "Английский декатерм")] + [InlineData("ru-RU", EnergyUnit.DecathermUs, "Американский декатерм")] + [InlineData("ru-RU", EnergyUnit.ElectronVolt, "эВ")] + [InlineData("ru-RU", EnergyUnit.GigaelectronVolt, "ГэВ")] + [InlineData("ru-RU", EnergyUnit.GigawattDay, "ГВт/д")] + [InlineData("ru-RU", EnergyUnit.GigawattHour, "ГВт/ч")] + [InlineData("ru-RU", EnergyUnit.KiloelectronVolt, "кэВ")] + [InlineData("ru-RU", EnergyUnit.KilowattDay, "кВт/д")] + [InlineData("ru-RU", EnergyUnit.KilowattHour, "кВт/ч")] + [InlineData("ru-RU", EnergyUnit.MegaelectronVolt, "МэВ")] + [InlineData("ru-RU", EnergyUnit.MegawattDay, "МВт/д")] + [InlineData("ru-RU", EnergyUnit.MegawattHour, "МВт/ч")] + [InlineData("ru-RU", EnergyUnit.TeraelectronVolt, "ТэВ")] + [InlineData("ru-RU", EnergyUnit.TerawattDay, "ТВт/д")] + [InlineData("ru-RU", EnergyUnit.TerawattHour, "ТВт/ч")] + [InlineData("ru-RU", EnergyUnit.ThermEc, "Европейский терм")] + [InlineData("ru-RU", EnergyUnit.ThermImperial, "Английский терм")] + [InlineData("ru-RU", EnergyUnit.ThermUs, "Американский терм")] + [InlineData("ru-RU", EnergyUnit.WattDay, "Вт/д")] + [InlineData("ru-RU", EnergyUnit.WattHour, "Вт/ч")] + public void GetAbbreviationForCulture(string culture, EnergyUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Energy.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Energy.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Energy.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(EnergyUnit unit) @@ -1948,6 +1396,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); }); } @@ -1971,71 +1420,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] @@ -2081,8 +1532,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); @@ -2119,23 +1568,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = Energy.FromJoules(1); - Assert.True(v.Equals(Energy.FromJoules(1), JoulesTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Energy.Zero, JoulesTolerance, ComparisonType.Relative)); - Assert.True(Energy.FromJoules(100).Equals(Energy.FromJoules(120), 0.3, ComparisonType.Relative)); - Assert.False(Energy.FromJoules(100).Equals(Energy.FromJoules(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = Energy.FromJoules(1); - Assert.Throws(() => v.Equals(Energy.FromJoules(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -2150,6 +1582,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(joule.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = Energy.FromJoules(1); + var negativeTolerance = Energy.FromJoules(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -2166,6 +1624,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() { @@ -2302,158 +1772,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Energy.FromJoules(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Energy.FromJoules(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Energy.FromJoules(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Energy.FromJoules(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Energy.FromJoules(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Energy.FromJoules(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Energy.FromJoules(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Energy.FromJoules(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Energy.FromJoules(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Energy.FromJoules(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Energy.FromJoules(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Energy.FromJoules(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Energy.FromJoules(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Energy.FromJoules(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Energy.FromJoules(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Energy.FromJoules(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Energy))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Energy.FromJoules(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(EnergyUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Energy.FromJoules(1.0); - Assert.Equal(Energy.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Energy.FromJoules(1.0); - Assert.Equal(Energy.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Energy.FromJoules(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Energy.FromJoules(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Energy.FromJoules(1.0); - Assert.Equal(new {Energy.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 1ece792a81..d807864063 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/EntropyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/EntropyTestsBase.g.cs @@ -120,7 +120,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Entropy(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -133,15 +133,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Entropy_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + EntropyUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Entropy(1, EntropyUnit.JoulePerKelvin); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Entropy.Zero, quantityInfo.Zero); Assert.Equal("Entropy", quantityInfo.Name); + Assert.Equal(Entropy.Zero, quantityInfo.Zero); + Assert.Equal(Entropy.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Entropy.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void EntropyInfo_CreateWithCustomUnitInfos() + { + EntropyUnit[] expectedUnits = [EntropyUnit.JoulePerKelvin]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -161,31 +179,31 @@ public void JoulePerKelvinToEntropyUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Entropy.From(1, EntropyUnit.CaloriePerKelvin); - AssertEx.EqualTolerance(1, quantity00.CaloriesPerKelvin, CaloriesPerKelvinTolerance); + Assert.Equal(1, quantity00.CaloriesPerKelvin); Assert.Equal(EntropyUnit.CaloriePerKelvin, quantity00.Unit); var quantity01 = Entropy.From(1, EntropyUnit.JoulePerDegreeCelsius); - AssertEx.EqualTolerance(1, quantity01.JoulesPerDegreeCelsius, JoulesPerDegreeCelsiusTolerance); + Assert.Equal(1, quantity01.JoulesPerDegreeCelsius); Assert.Equal(EntropyUnit.JoulePerDegreeCelsius, quantity01.Unit); var quantity02 = Entropy.From(1, EntropyUnit.JoulePerKelvin); - AssertEx.EqualTolerance(1, quantity02.JoulesPerKelvin, JoulesPerKelvinTolerance); + Assert.Equal(1, quantity02.JoulesPerKelvin); Assert.Equal(EntropyUnit.JoulePerKelvin, quantity02.Unit); var quantity03 = Entropy.From(1, EntropyUnit.KilocaloriePerKelvin); - AssertEx.EqualTolerance(1, quantity03.KilocaloriesPerKelvin, KilocaloriesPerKelvinTolerance); + Assert.Equal(1, quantity03.KilocaloriesPerKelvin); Assert.Equal(EntropyUnit.KilocaloriePerKelvin, quantity03.Unit); var quantity04 = Entropy.From(1, EntropyUnit.KilojoulePerDegreeCelsius); - AssertEx.EqualTolerance(1, quantity04.KilojoulesPerDegreeCelsius, KilojoulesPerDegreeCelsiusTolerance); + Assert.Equal(1, quantity04.KilojoulesPerDegreeCelsius); Assert.Equal(EntropyUnit.KilojoulePerDegreeCelsius, quantity04.Unit); var quantity05 = Entropy.From(1, EntropyUnit.KilojoulePerKelvin); - AssertEx.EqualTolerance(1, quantity05.KilojoulesPerKelvin, KilojoulesPerKelvinTolerance); + Assert.Equal(1, quantity05.KilojoulesPerKelvin); Assert.Equal(EntropyUnit.KilojoulePerKelvin, quantity05.Unit); var quantity06 = Entropy.From(1, EntropyUnit.MegajoulePerKelvin); - AssertEx.EqualTolerance(1, quantity06.MegajoulesPerKelvin, MegajoulesPerKelvinTolerance); + Assert.Equal(1, quantity06.MegajoulesPerKelvin); Assert.Equal(EntropyUnit.MegajoulePerKelvin, quantity06.Unit); } @@ -327,105 +345,36 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 cal/K", EntropyUnit.CaloriePerKelvin, 4.2)] + [InlineData("en-US", "4.2 J/°C", EntropyUnit.JoulePerDegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 J/K", EntropyUnit.JoulePerKelvin, 4.2)] + [InlineData("en-US", "4.2 kcal/K", EntropyUnit.KilocaloriePerKelvin, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = Entropy.Parse("1 cal/K", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CaloriesPerKelvin, CaloriesPerKelvinTolerance); - Assert.Equal(EntropyUnit.CaloriePerKelvin, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Entropy.Parse("1 J/°C", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.JoulesPerDegreeCelsius, JoulesPerDegreeCelsiusTolerance); - Assert.Equal(EntropyUnit.JoulePerDegreeCelsius, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Entropy.Parse("1 J/K", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.JoulesPerKelvin, JoulesPerKelvinTolerance); - Assert.Equal(EntropyUnit.JoulePerKelvin, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Entropy.Parse("1 kcal/K", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilocaloriesPerKelvin, KilocaloriesPerKelvinTolerance); - Assert.Equal(EntropyUnit.KilocaloriePerKelvin, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Entropy.Parse("1 kJ/°C", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilojoulesPerDegreeCelsius, KilojoulesPerDegreeCelsiusTolerance); - Assert.Equal(EntropyUnit.KilojoulePerDegreeCelsius, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Entropy.Parse("1 kJ/K", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilojoulesPerKelvin, KilojoulesPerKelvinTolerance); - Assert.Equal(EntropyUnit.KilojoulePerKelvin, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Entropy.Parse("1 MJ/K", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegajoulesPerKelvin, MegajoulesPerKelvinTolerance); - Assert.Equal(EntropyUnit.MegajoulePerKelvin, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Entropy.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 cal/K", EntropyUnit.CaloriePerKelvin, 4.2)] + [InlineData("en-US", "4.2 J/°C", EntropyUnit.JoulePerDegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 J/K", EntropyUnit.JoulePerKelvin, 4.2)] + [InlineData("en-US", "4.2 kcal/K", EntropyUnit.KilocaloriePerKelvin, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(Entropy.TryParse("1 cal/K", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CaloriesPerKelvin, CaloriesPerKelvinTolerance); - Assert.Equal(EntropyUnit.CaloriePerKelvin, parsed.Unit); - } - - { - Assert.True(Entropy.TryParse("1 J/°C", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.JoulesPerDegreeCelsius, JoulesPerDegreeCelsiusTolerance); - Assert.Equal(EntropyUnit.JoulePerDegreeCelsius, parsed.Unit); - } - - { - Assert.True(Entropy.TryParse("1 J/K", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.JoulesPerKelvin, JoulesPerKelvinTolerance); - Assert.Equal(EntropyUnit.JoulePerKelvin, parsed.Unit); - } - - { - Assert.True(Entropy.TryParse("1 kcal/K", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilocaloriesPerKelvin, KilocaloriesPerKelvinTolerance); - Assert.Equal(EntropyUnit.KilocaloriePerKelvin, parsed.Unit); - } - - { - Assert.True(Entropy.TryParse("1 kJ/°C", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilojoulesPerDegreeCelsius, KilojoulesPerDegreeCelsiusTolerance); - Assert.Equal(EntropyUnit.KilojoulePerDegreeCelsius, parsed.Unit); - } - - { - Assert.True(Entropy.TryParse("1 kJ/K", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilojoulesPerKelvin, KilojoulesPerKelvinTolerance); - Assert.Equal(EntropyUnit.KilojoulePerKelvin, parsed.Unit); - } - - { - Assert.True(Entropy.TryParse("1 MJ/K", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegajoulesPerKelvin, MegajoulesPerKelvinTolerance); - Assert.Equal(EntropyUnit.MegajoulePerKelvin, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Entropy.TryParse(quantityString, out Entropy parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -550,6 +499,33 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Entrop Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", EntropyUnit.CaloriePerKelvin, "cal/K")] + [InlineData("en-US", EntropyUnit.JoulePerDegreeCelsius, "J/°C")] + [InlineData("en-US", EntropyUnit.JoulePerKelvin, "J/K")] + [InlineData("en-US", EntropyUnit.KilocaloriePerKelvin, "kcal/K")] + [InlineData("en-US", EntropyUnit.KilojoulePerDegreeCelsius, "kJ/°C")] + [InlineData("en-US", EntropyUnit.KilojoulePerKelvin, "kJ/K")] + [InlineData("en-US", EntropyUnit.MegajoulePerKelvin, "MJ/K")] + public void GetAbbreviationForCulture(string culture, EntropyUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Entropy.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Entropy.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Entropy.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(EntropyUnit unit) @@ -580,6 +556,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); }); } @@ -603,38 +580,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] @@ -680,8 +659,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); @@ -719,34 +696,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = Entropy.FromJoulesPerKelvin(1); - Assert.True(v.Equals(Entropy.FromJoulesPerKelvin(1), JoulesPerKelvinTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Entropy.Zero, JoulesPerKelvinTolerance, ComparisonType.Relative)); - Assert.True(Entropy.FromJoulesPerKelvin(100).Equals(Entropy.FromJoulesPerKelvin(120), 0.3, ComparisonType.Relative)); - Assert.False(Entropy.FromJoulesPerKelvin(100).Equals(Entropy.FromJoulesPerKelvin(120), 0.1, ComparisonType.Relative)); + Entropy jouleperkelvin = Entropy.FromJoulesPerKelvin(1); + Assert.False(jouleperkelvin.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = Entropy.FromJoulesPerKelvin(1); - Assert.Throws(() => v.Equals(Entropy.FromJoulesPerKelvin(1), -1, ComparisonType.Relative)); + Entropy jouleperkelvin = Entropy.FromJoulesPerKelvin(1); + Assert.False(jouleperkelvin.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - Entropy jouleperkelvin = Entropy.FromJoulesPerKelvin(1); - Assert.False(jouleperkelvin.Equals(new object())); + var quantity = Entropy.FromJoulesPerKelvin(firstValue); + var otherQuantity = Entropy.FromJoulesPerKelvin(secondValue); + Entropy maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - Entropy jouleperkelvin = Entropy.FromJoulesPerKelvin(1); - Assert.False(jouleperkelvin.Equals(null)); + var quantity = Entropy.FromJoulesPerKelvin(1); + var negativeTolerance = Entropy.FromJoulesPerKelvin(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -765,6 +751,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() { @@ -835,158 +833,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Entropy))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(EntropyUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal(Entropy.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal(Entropy.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal(new {Entropy.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 bcd3a0be09..712c1315a6 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/FluidResistanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/FluidResistanceTestsBase.g.cs @@ -168,7 +168,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new FluidResistance(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -181,15 +181,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void FluidResistance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + FluidResistanceUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new FluidResistance(1, FluidResistanceUnit.PascalSecondPerCubicMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(FluidResistance.Zero, quantityInfo.Zero); Assert.Equal("FluidResistance", quantityInfo.Name); + Assert.Equal(FluidResistance.Zero, quantityInfo.Zero); + Assert.Equal(FluidResistance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(FluidResistance.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void FluidResistanceInfo_CreateWithCustomUnitInfos() + { + FluidResistanceUnit[] expectedUnits = [FluidResistanceUnit.PascalSecondPerCubicMeter]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -221,79 +239,79 @@ public void PascalSecondPerCubicMeterToFluidResistanceUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = FluidResistance.From(1, FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth); - AssertEx.EqualTolerance(1, quantity00.DyneSecondsPerCentimeterToTheFifth, DyneSecondsPerCentimeterToTheFifthTolerance); + Assert.Equal(1, quantity00.DyneSecondsPerCentimeterToTheFifth); Assert.Equal(FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth, quantity00.Unit); var quantity01 = FluidResistance.From(1, FluidResistanceUnit.MegapascalSecondPerCubicMeter); - AssertEx.EqualTolerance(1, quantity01.MegapascalSecondsPerCubicMeter, MegapascalSecondsPerCubicMeterTolerance); + Assert.Equal(1, quantity01.MegapascalSecondsPerCubicMeter); Assert.Equal(FluidResistanceUnit.MegapascalSecondPerCubicMeter, quantity01.Unit); var quantity02 = FluidResistance.From(1, FluidResistanceUnit.MillimeterMercuryMinutePerCubicCentimeter); - AssertEx.EqualTolerance(1, quantity02.MillimeterMercuryMinutesPerCubicCentimeter, MillimeterMercuryMinutesPerCubicCentimeterTolerance); + Assert.Equal(1, quantity02.MillimeterMercuryMinutesPerCubicCentimeter); Assert.Equal(FluidResistanceUnit.MillimeterMercuryMinutePerCubicCentimeter, quantity02.Unit); var quantity03 = FluidResistance.From(1, FluidResistanceUnit.MillimeterMercuryMinutePerCubicMeter); - AssertEx.EqualTolerance(1, quantity03.MillimeterMercuryMinutesPerCubicMeter, MillimeterMercuryMinutesPerCubicMeterTolerance); + Assert.Equal(1, quantity03.MillimeterMercuryMinutesPerCubicMeter); Assert.Equal(FluidResistanceUnit.MillimeterMercuryMinutePerCubicMeter, quantity03.Unit); var quantity04 = FluidResistance.From(1, FluidResistanceUnit.MillimeterMercuryMinutePerLiter); - AssertEx.EqualTolerance(1, quantity04.MillimeterMercuryMinutesPerLiter, MillimeterMercuryMinutesPerLiterTolerance); + Assert.Equal(1, quantity04.MillimeterMercuryMinutesPerLiter); Assert.Equal(FluidResistanceUnit.MillimeterMercuryMinutePerLiter, quantity04.Unit); var quantity05 = FluidResistance.From(1, FluidResistanceUnit.MillimeterMercuryMinutePerMilliliter); - AssertEx.EqualTolerance(1, quantity05.MillimeterMercuryMinutesPerMilliliter, MillimeterMercuryMinutesPerMilliliterTolerance); + Assert.Equal(1, quantity05.MillimeterMercuryMinutesPerMilliliter); Assert.Equal(FluidResistanceUnit.MillimeterMercuryMinutePerMilliliter, quantity05.Unit); var quantity06 = FluidResistance.From(1, FluidResistanceUnit.MillimeterMercurySecondPerCubicCentimeter); - AssertEx.EqualTolerance(1, quantity06.MillimeterMercurySecondsPerCubicCentimeter, MillimeterMercurySecondsPerCubicCentimeterTolerance); + Assert.Equal(1, quantity06.MillimeterMercurySecondsPerCubicCentimeter); Assert.Equal(FluidResistanceUnit.MillimeterMercurySecondPerCubicCentimeter, quantity06.Unit); var quantity07 = FluidResistance.From(1, FluidResistanceUnit.MillimeterMercurySecondPerCubicMeter); - AssertEx.EqualTolerance(1, quantity07.MillimeterMercurySecondsPerCubicMeter, MillimeterMercurySecondsPerCubicMeterTolerance); + Assert.Equal(1, quantity07.MillimeterMercurySecondsPerCubicMeter); Assert.Equal(FluidResistanceUnit.MillimeterMercurySecondPerCubicMeter, quantity07.Unit); var quantity08 = FluidResistance.From(1, FluidResistanceUnit.MillimeterMercurySecondPerLiter); - AssertEx.EqualTolerance(1, quantity08.MillimeterMercurySecondsPerLiter, MillimeterMercurySecondsPerLiterTolerance); + Assert.Equal(1, quantity08.MillimeterMercurySecondsPerLiter); Assert.Equal(FluidResistanceUnit.MillimeterMercurySecondPerLiter, quantity08.Unit); var quantity09 = FluidResistance.From(1, FluidResistanceUnit.MillimeterMercurySecondPerMilliliter); - AssertEx.EqualTolerance(1, quantity09.MillimeterMercurySecondsPerMilliliter, MillimeterMercurySecondsPerMilliliterTolerance); + Assert.Equal(1, quantity09.MillimeterMercurySecondsPerMilliliter); Assert.Equal(FluidResistanceUnit.MillimeterMercurySecondPerMilliliter, quantity09.Unit); var quantity10 = FluidResistance.From(1, FluidResistanceUnit.PascalMinutePerCubicCentimeter); - AssertEx.EqualTolerance(1, quantity10.PascalMinutesPerCubicCentimeter, PascalMinutesPerCubicCentimeterTolerance); + Assert.Equal(1, quantity10.PascalMinutesPerCubicCentimeter); Assert.Equal(FluidResistanceUnit.PascalMinutePerCubicCentimeter, quantity10.Unit); var quantity11 = FluidResistance.From(1, FluidResistanceUnit.PascalMinutePerCubicMeter); - AssertEx.EqualTolerance(1, quantity11.PascalMinutesPerCubicMeter, PascalMinutesPerCubicMeterTolerance); + Assert.Equal(1, quantity11.PascalMinutesPerCubicMeter); Assert.Equal(FluidResistanceUnit.PascalMinutePerCubicMeter, quantity11.Unit); var quantity12 = FluidResistance.From(1, FluidResistanceUnit.PascalMinutePerLiter); - AssertEx.EqualTolerance(1, quantity12.PascalMinutesPerLiter, PascalMinutesPerLiterTolerance); + Assert.Equal(1, quantity12.PascalMinutesPerLiter); Assert.Equal(FluidResistanceUnit.PascalMinutePerLiter, quantity12.Unit); var quantity13 = FluidResistance.From(1, FluidResistanceUnit.PascalMinutePerMilliliter); - AssertEx.EqualTolerance(1, quantity13.PascalMinutesPerMilliliter, PascalMinutesPerMilliliterTolerance); + Assert.Equal(1, quantity13.PascalMinutesPerMilliliter); Assert.Equal(FluidResistanceUnit.PascalMinutePerMilliliter, quantity13.Unit); var quantity14 = FluidResistance.From(1, FluidResistanceUnit.PascalSecondPerCubicCentimeter); - AssertEx.EqualTolerance(1, quantity14.PascalSecondsPerCubicCentimeter, PascalSecondsPerCubicCentimeterTolerance); + Assert.Equal(1, quantity14.PascalSecondsPerCubicCentimeter); Assert.Equal(FluidResistanceUnit.PascalSecondPerCubicCentimeter, quantity14.Unit); var quantity15 = FluidResistance.From(1, FluidResistanceUnit.PascalSecondPerCubicMeter); - AssertEx.EqualTolerance(1, quantity15.PascalSecondsPerCubicMeter, PascalSecondsPerCubicMeterTolerance); + Assert.Equal(1, quantity15.PascalSecondsPerCubicMeter); Assert.Equal(FluidResistanceUnit.PascalSecondPerCubicMeter, quantity15.Unit); var quantity16 = FluidResistance.From(1, FluidResistanceUnit.PascalSecondPerLiter); - AssertEx.EqualTolerance(1, quantity16.PascalSecondsPerLiter, PascalSecondsPerLiterTolerance); + Assert.Equal(1, quantity16.PascalSecondsPerLiter); Assert.Equal(FluidResistanceUnit.PascalSecondPerLiter, quantity16.Unit); var quantity17 = FluidResistance.From(1, FluidResistanceUnit.PascalSecondPerMilliliter); - AssertEx.EqualTolerance(1, quantity17.PascalSecondsPerMilliliter, PascalSecondsPerMilliliterTolerance); + Assert.Equal(1, quantity17.PascalSecondsPerMilliliter); Assert.Equal(FluidResistanceUnit.PascalSecondPerMilliliter, quantity17.Unit); var quantity18 = FluidResistance.From(1, FluidResistanceUnit.WoodUnit); - AssertEx.EqualTolerance(1, quantity18.WoodUnits, WoodUnitsTolerance); + Assert.Equal(1, quantity18.WoodUnits); Assert.Equal(FluidResistanceUnit.WoodUnit, quantity18.Unit); } @@ -447,560 +465,106 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 dyn·s/cm⁵", FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth, 4.2)] + [InlineData("en-US", "4.2 dyn·s·cm⁻⁵", FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth, 4.2)] + [InlineData("en-US", "4.2 MPa·s/m³", FluidResistanceUnit.MegapascalSecondPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 mmHg·min/cm³", FluidResistanceUnit.MillimeterMercuryMinutePerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 mmHg·min/m³", FluidResistanceUnit.MillimeterMercuryMinutePerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 mmHg·min/l", FluidResistanceUnit.MillimeterMercuryMinutePerLiter, 4.2)] + [InlineData("en-US", "4.2 mmHg·min/ml", FluidResistanceUnit.MillimeterMercuryMinutePerMilliliter, 4.2)] + [InlineData("en-US", "4.2 mmHg·s/cm³", FluidResistanceUnit.MillimeterMercurySecondPerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 mmHg·s/m³", FluidResistanceUnit.MillimeterMercurySecondPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 mmHg·s/l", FluidResistanceUnit.MillimeterMercurySecondPerLiter, 4.2)] + [InlineData("en-US", "4.2 mmHg·s/ml", FluidResistanceUnit.MillimeterMercurySecondPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 Pa·min/cm³", FluidResistanceUnit.PascalMinutePerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 Pa·min/m³", FluidResistanceUnit.PascalMinutePerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 Pa·min/l", FluidResistanceUnit.PascalMinutePerLiter, 4.2)] + [InlineData("en-US", "4.2 Pa·min/ml", FluidResistanceUnit.PascalMinutePerMilliliter, 4.2)] + [InlineData("en-US", "4.2 Pa·s/cm³", FluidResistanceUnit.PascalSecondPerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 Pa·s/m³", FluidResistanceUnit.PascalSecondPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 Pa·s/l", FluidResistanceUnit.PascalSecondPerLiter, 4.2)] + [InlineData("en-US", "4.2 Pa·s/ml", FluidResistanceUnit.PascalSecondPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 WU", FluidResistanceUnit.WoodUnit, 4.2)] + [InlineData("en-US", "4.2 HRU", FluidResistanceUnit.WoodUnit, 4.2)] + [InlineData("ru-RU", "4,2 дин·с/см⁵", FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth, 4.2)] + [InlineData("ru-RU", "4,2 дин·с·см⁻⁵", FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth, 4.2)] + [InlineData("ru-RU", "4,2 МПа·с/м³", FluidResistanceUnit.MegapascalSecondPerCubicMeter, 4.2)] + [InlineData("ru-RU", "4,2 мм рт.ст·мин/см³", FluidResistanceUnit.MillimeterMercuryMinutePerCubicCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 мм рт.ст·мин/м³", FluidResistanceUnit.MillimeterMercuryMinutePerCubicMeter, 4.2)] + [InlineData("ru-RU", "4,2 мм рт.ст·мин/л", FluidResistanceUnit.MillimeterMercuryMinutePerLiter, 4.2)] + [InlineData("ru-RU", "4,2 мм рт.ст·мин/мл", FluidResistanceUnit.MillimeterMercuryMinutePerMilliliter, 4.2)] + [InlineData("ru-RU", "4,2 мм рт.ст·с/см³", FluidResistanceUnit.MillimeterMercurySecondPerCubicCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 мм рт.ст·с/м³", FluidResistanceUnit.MillimeterMercurySecondPerCubicMeter, 4.2)] + [InlineData("ru-RU", "4,2 мм рт.ст·с/л", FluidResistanceUnit.MillimeterMercurySecondPerLiter, 4.2)] + [InlineData("ru-RU", "4,2 мм рт.ст·с/мл", FluidResistanceUnit.MillimeterMercurySecondPerMilliliter, 4.2)] + [InlineData("ru-RU", "4,2 Па·мин/см³", FluidResistanceUnit.PascalMinutePerCubicCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 Па·мин/м³", FluidResistanceUnit.PascalMinutePerCubicMeter, 4.2)] + [InlineData("ru-RU", "4,2 Па·мин/л", FluidResistanceUnit.PascalMinutePerLiter, 4.2)] + [InlineData("ru-RU", "4,2 Па·мин/мл", FluidResistanceUnit.PascalMinutePerMilliliter, 4.2)] + [InlineData("ru-RU", "4,2 Па·с/см³", FluidResistanceUnit.PascalSecondPerCubicCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 Па·с/м³", FluidResistanceUnit.PascalSecondPerCubicMeter, 4.2)] + [InlineData("ru-RU", "4,2 Па·с/л", FluidResistanceUnit.PascalSecondPerLiter, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = FluidResistance.Parse("1 dyn·s/cm⁵", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DyneSecondsPerCentimeterToTheFifth, DyneSecondsPerCentimeterToTheFifthTolerance); - Assert.Equal(FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 dyn·s·cm⁻⁵", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DyneSecondsPerCentimeterToTheFifth, DyneSecondsPerCentimeterToTheFifthTolerance); - Assert.Equal(FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 дин·с/см⁵", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.DyneSecondsPerCentimeterToTheFifth, DyneSecondsPerCentimeterToTheFifthTolerance); - Assert.Equal(FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 дин·с·см⁻⁵", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.DyneSecondsPerCentimeterToTheFifth, DyneSecondsPerCentimeterToTheFifthTolerance); - Assert.Equal(FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 MPa·s/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegapascalSecondsPerCubicMeter, MegapascalSecondsPerCubicMeterTolerance); - Assert.Equal(FluidResistanceUnit.MegapascalSecondPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 МПа·с/м³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MegapascalSecondsPerCubicMeter, MegapascalSecondsPerCubicMeterTolerance); - Assert.Equal(FluidResistanceUnit.MegapascalSecondPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 mmHg·min/cm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillimeterMercuryMinutesPerCubicCentimeter, MillimeterMercuryMinutesPerCubicCentimeterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercuryMinutePerCubicCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 мм рт.ст·мин/см³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MillimeterMercuryMinutesPerCubicCentimeter, MillimeterMercuryMinutesPerCubicCentimeterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercuryMinutePerCubicCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 mmHg·min/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillimeterMercuryMinutesPerCubicMeter, MillimeterMercuryMinutesPerCubicMeterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercuryMinutePerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 мм рт.ст·мин/м³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MillimeterMercuryMinutesPerCubicMeter, MillimeterMercuryMinutesPerCubicMeterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercuryMinutePerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 mmHg·min/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillimeterMercuryMinutesPerLiter, MillimeterMercuryMinutesPerLiterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercuryMinutePerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 мм рт.ст·мин/л", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MillimeterMercuryMinutesPerLiter, MillimeterMercuryMinutesPerLiterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercuryMinutePerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 mmHg·min/ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillimeterMercuryMinutesPerMilliliter, MillimeterMercuryMinutesPerMilliliterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercuryMinutePerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 мм рт.ст·мин/мл", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MillimeterMercuryMinutesPerMilliliter, MillimeterMercuryMinutesPerMilliliterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercuryMinutePerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 mmHg·s/cm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillimeterMercurySecondsPerCubicCentimeter, MillimeterMercurySecondsPerCubicCentimeterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercurySecondPerCubicCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 мм рт.ст·с/см³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MillimeterMercurySecondsPerCubicCentimeter, MillimeterMercurySecondsPerCubicCentimeterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercurySecondPerCubicCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 mmHg·s/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillimeterMercurySecondsPerCubicMeter, MillimeterMercurySecondsPerCubicMeterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercurySecondPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 мм рт.ст·с/м³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MillimeterMercurySecondsPerCubicMeter, MillimeterMercurySecondsPerCubicMeterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercurySecondPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 mmHg·s/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillimeterMercurySecondsPerLiter, MillimeterMercurySecondsPerLiterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercurySecondPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 мм рт.ст·с/л", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MillimeterMercurySecondsPerLiter, MillimeterMercurySecondsPerLiterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercurySecondPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 mmHg·s/ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillimeterMercurySecondsPerMilliliter, MillimeterMercurySecondsPerMilliliterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercurySecondPerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 мм рт.ст·с/мл", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MillimeterMercurySecondsPerMilliliter, MillimeterMercurySecondsPerMilliliterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercurySecondPerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 Pa·min/cm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PascalMinutesPerCubicCentimeter, PascalMinutesPerCubicCentimeterTolerance); - Assert.Equal(FluidResistanceUnit.PascalMinutePerCubicCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 Па·мин/см³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.PascalMinutesPerCubicCentimeter, PascalMinutesPerCubicCentimeterTolerance); - Assert.Equal(FluidResistanceUnit.PascalMinutePerCubicCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 Pa·min/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PascalMinutesPerCubicMeter, PascalMinutesPerCubicMeterTolerance); - Assert.Equal(FluidResistanceUnit.PascalMinutePerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 Па·мин/м³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.PascalMinutesPerCubicMeter, PascalMinutesPerCubicMeterTolerance); - Assert.Equal(FluidResistanceUnit.PascalMinutePerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 Pa·min/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PascalMinutesPerLiter, PascalMinutesPerLiterTolerance); - Assert.Equal(FluidResistanceUnit.PascalMinutePerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 Па·мин/л", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.PascalMinutesPerLiter, PascalMinutesPerLiterTolerance); - Assert.Equal(FluidResistanceUnit.PascalMinutePerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 Pa·min/ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PascalMinutesPerMilliliter, PascalMinutesPerMilliliterTolerance); - Assert.Equal(FluidResistanceUnit.PascalMinutePerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 Па·мин/мл", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.PascalMinutesPerMilliliter, PascalMinutesPerMilliliterTolerance); - Assert.Equal(FluidResistanceUnit.PascalMinutePerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 Pa·s/cm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PascalSecondsPerCubicCentimeter, PascalSecondsPerCubicCentimeterTolerance); - Assert.Equal(FluidResistanceUnit.PascalSecondPerCubicCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 Па·с/см³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.PascalSecondsPerCubicCentimeter, PascalSecondsPerCubicCentimeterTolerance); - Assert.Equal(FluidResistanceUnit.PascalSecondPerCubicCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 Pa·s/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PascalSecondsPerCubicMeter, PascalSecondsPerCubicMeterTolerance); - Assert.Equal(FluidResistanceUnit.PascalSecondPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 Па·с/м³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.PascalSecondsPerCubicMeter, PascalSecondsPerCubicMeterTolerance); - Assert.Equal(FluidResistanceUnit.PascalSecondPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 Pa·s/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PascalSecondsPerLiter, PascalSecondsPerLiterTolerance); - Assert.Equal(FluidResistanceUnit.PascalSecondPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 Па·с/л", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.PascalSecondsPerLiter, PascalSecondsPerLiterTolerance); - Assert.Equal(FluidResistanceUnit.PascalSecondPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 Pa·s/ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PascalSecondsPerMilliliter, PascalSecondsPerMilliliterTolerance); - Assert.Equal(FluidResistanceUnit.PascalSecondPerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 Па·с/мл", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.PascalSecondsPerMilliliter, PascalSecondsPerMilliliterTolerance); - Assert.Equal(FluidResistanceUnit.PascalSecondPerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 WU", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WoodUnits, WoodUnitsTolerance); - Assert.Equal(FluidResistanceUnit.WoodUnit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 HRU", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WoodUnits, WoodUnitsTolerance); - Assert.Equal(FluidResistanceUnit.WoodUnit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 ЕВ", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.WoodUnits, WoodUnitsTolerance); - Assert.Equal(FluidResistanceUnit.WoodUnit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FluidResistance.Parse("1 ЕГС", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.WoodUnits, WoodUnitsTolerance); - Assert.Equal(FluidResistanceUnit.WoodUnit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = FluidResistance.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 dyn·s/cm⁵", FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth, 4.2)] + [InlineData("en-US", "4.2 dyn·s·cm⁻⁵", FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth, 4.2)] + [InlineData("en-US", "4.2 MPa·s/m³", FluidResistanceUnit.MegapascalSecondPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 mmHg·min/cm³", FluidResistanceUnit.MillimeterMercuryMinutePerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 mmHg·min/m³", FluidResistanceUnit.MillimeterMercuryMinutePerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 mmHg·min/l", FluidResistanceUnit.MillimeterMercuryMinutePerLiter, 4.2)] + [InlineData("en-US", "4.2 mmHg·min/ml", FluidResistanceUnit.MillimeterMercuryMinutePerMilliliter, 4.2)] + [InlineData("en-US", "4.2 mmHg·s/cm³", FluidResistanceUnit.MillimeterMercurySecondPerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 mmHg·s/m³", FluidResistanceUnit.MillimeterMercurySecondPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 mmHg·s/l", FluidResistanceUnit.MillimeterMercurySecondPerLiter, 4.2)] + [InlineData("en-US", "4.2 mmHg·s/ml", FluidResistanceUnit.MillimeterMercurySecondPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 Pa·min/cm³", FluidResistanceUnit.PascalMinutePerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 Pa·min/m³", FluidResistanceUnit.PascalMinutePerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 Pa·min/l", FluidResistanceUnit.PascalMinutePerLiter, 4.2)] + [InlineData("en-US", "4.2 Pa·min/ml", FluidResistanceUnit.PascalMinutePerMilliliter, 4.2)] + [InlineData("en-US", "4.2 Pa·s/cm³", FluidResistanceUnit.PascalSecondPerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 Pa·s/m³", FluidResistanceUnit.PascalSecondPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 Pa·s/l", FluidResistanceUnit.PascalSecondPerLiter, 4.2)] + [InlineData("en-US", "4.2 Pa·s/ml", FluidResistanceUnit.PascalSecondPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 WU", FluidResistanceUnit.WoodUnit, 4.2)] + [InlineData("en-US", "4.2 HRU", FluidResistanceUnit.WoodUnit, 4.2)] + [InlineData("ru-RU", "4,2 дин·с/см⁵", FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth, 4.2)] + [InlineData("ru-RU", "4,2 дин·с·см⁻⁵", FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth, 4.2)] + [InlineData("ru-RU", "4,2 МПа·с/м³", FluidResistanceUnit.MegapascalSecondPerCubicMeter, 4.2)] + [InlineData("ru-RU", "4,2 мм рт.ст·мин/см³", FluidResistanceUnit.MillimeterMercuryMinutePerCubicCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 мм рт.ст·мин/м³", FluidResistanceUnit.MillimeterMercuryMinutePerCubicMeter, 4.2)] + [InlineData("ru-RU", "4,2 мм рт.ст·мин/л", FluidResistanceUnit.MillimeterMercuryMinutePerLiter, 4.2)] + [InlineData("ru-RU", "4,2 мм рт.ст·мин/мл", FluidResistanceUnit.MillimeterMercuryMinutePerMilliliter, 4.2)] + [InlineData("ru-RU", "4,2 мм рт.ст·с/см³", FluidResistanceUnit.MillimeterMercurySecondPerCubicCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 мм рт.ст·с/м³", FluidResistanceUnit.MillimeterMercurySecondPerCubicMeter, 4.2)] + [InlineData("ru-RU", "4,2 мм рт.ст·с/л", FluidResistanceUnit.MillimeterMercurySecondPerLiter, 4.2)] + [InlineData("ru-RU", "4,2 мм рт.ст·с/мл", FluidResistanceUnit.MillimeterMercurySecondPerMilliliter, 4.2)] + [InlineData("ru-RU", "4,2 Па·мин/см³", FluidResistanceUnit.PascalMinutePerCubicCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 Па·мин/м³", FluidResistanceUnit.PascalMinutePerCubicMeter, 4.2)] + [InlineData("ru-RU", "4,2 Па·мин/л", FluidResistanceUnit.PascalMinutePerLiter, 4.2)] + [InlineData("ru-RU", "4,2 Па·мин/мл", FluidResistanceUnit.PascalMinutePerMilliliter, 4.2)] + [InlineData("ru-RU", "4,2 Па·с/см³", FluidResistanceUnit.PascalSecondPerCubicCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 Па·с/м³", FluidResistanceUnit.PascalSecondPerCubicMeter, 4.2)] + [InlineData("ru-RU", "4,2 Па·с/л", FluidResistanceUnit.PascalSecondPerLiter, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(FluidResistance.TryParse("1 dyn·s/cm⁵", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DyneSecondsPerCentimeterToTheFifth, DyneSecondsPerCentimeterToTheFifthTolerance); - Assert.Equal(FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 dyn·s·cm⁻⁵", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DyneSecondsPerCentimeterToTheFifth, DyneSecondsPerCentimeterToTheFifthTolerance); - Assert.Equal(FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 дин·с/см⁵", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DyneSecondsPerCentimeterToTheFifth, DyneSecondsPerCentimeterToTheFifthTolerance); - Assert.Equal(FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 дин·с·см⁻⁵", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DyneSecondsPerCentimeterToTheFifth, DyneSecondsPerCentimeterToTheFifthTolerance); - Assert.Equal(FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 MPa·s/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegapascalSecondsPerCubicMeter, MegapascalSecondsPerCubicMeterTolerance); - Assert.Equal(FluidResistanceUnit.MegapascalSecondPerCubicMeter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 МПа·с/м³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegapascalSecondsPerCubicMeter, MegapascalSecondsPerCubicMeterTolerance); - Assert.Equal(FluidResistanceUnit.MegapascalSecondPerCubicMeter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 mmHg·min/cm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimeterMercuryMinutesPerCubicCentimeter, MillimeterMercuryMinutesPerCubicCentimeterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercuryMinutePerCubicCentimeter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 мм рт.ст·мин/см³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimeterMercuryMinutesPerCubicCentimeter, MillimeterMercuryMinutesPerCubicCentimeterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercuryMinutePerCubicCentimeter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 mmHg·min/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimeterMercuryMinutesPerCubicMeter, MillimeterMercuryMinutesPerCubicMeterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercuryMinutePerCubicMeter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 мм рт.ст·мин/м³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimeterMercuryMinutesPerCubicMeter, MillimeterMercuryMinutesPerCubicMeterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercuryMinutePerCubicMeter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 mmHg·min/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimeterMercuryMinutesPerLiter, MillimeterMercuryMinutesPerLiterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercuryMinutePerLiter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 мм рт.ст·мин/л", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimeterMercuryMinutesPerLiter, MillimeterMercuryMinutesPerLiterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercuryMinutePerLiter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 mmHg·min/ml", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimeterMercuryMinutesPerMilliliter, MillimeterMercuryMinutesPerMilliliterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercuryMinutePerMilliliter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 мм рт.ст·мин/мл", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimeterMercuryMinutesPerMilliliter, MillimeterMercuryMinutesPerMilliliterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercuryMinutePerMilliliter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 mmHg·s/cm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimeterMercurySecondsPerCubicCentimeter, MillimeterMercurySecondsPerCubicCentimeterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercurySecondPerCubicCentimeter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 мм рт.ст·с/см³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimeterMercurySecondsPerCubicCentimeter, MillimeterMercurySecondsPerCubicCentimeterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercurySecondPerCubicCentimeter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 mmHg·s/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimeterMercurySecondsPerCubicMeter, MillimeterMercurySecondsPerCubicMeterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercurySecondPerCubicMeter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 мм рт.ст·с/м³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimeterMercurySecondsPerCubicMeter, MillimeterMercurySecondsPerCubicMeterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercurySecondPerCubicMeter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 mmHg·s/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimeterMercurySecondsPerLiter, MillimeterMercurySecondsPerLiterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercurySecondPerLiter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 мм рт.ст·с/л", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimeterMercurySecondsPerLiter, MillimeterMercurySecondsPerLiterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercurySecondPerLiter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 mmHg·s/ml", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimeterMercurySecondsPerMilliliter, MillimeterMercurySecondsPerMilliliterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercurySecondPerMilliliter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 мм рт.ст·с/мл", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimeterMercurySecondsPerMilliliter, MillimeterMercurySecondsPerMilliliterTolerance); - Assert.Equal(FluidResistanceUnit.MillimeterMercurySecondPerMilliliter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 Pa·min/cm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PascalMinutesPerCubicCentimeter, PascalMinutesPerCubicCentimeterTolerance); - Assert.Equal(FluidResistanceUnit.PascalMinutePerCubicCentimeter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 Па·мин/см³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PascalMinutesPerCubicCentimeter, PascalMinutesPerCubicCentimeterTolerance); - Assert.Equal(FluidResistanceUnit.PascalMinutePerCubicCentimeter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 Pa·min/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PascalMinutesPerCubicMeter, PascalMinutesPerCubicMeterTolerance); - Assert.Equal(FluidResistanceUnit.PascalMinutePerCubicMeter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 Па·мин/м³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PascalMinutesPerCubicMeter, PascalMinutesPerCubicMeterTolerance); - Assert.Equal(FluidResistanceUnit.PascalMinutePerCubicMeter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 Pa·min/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PascalMinutesPerLiter, PascalMinutesPerLiterTolerance); - Assert.Equal(FluidResistanceUnit.PascalMinutePerLiter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 Па·мин/л", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PascalMinutesPerLiter, PascalMinutesPerLiterTolerance); - Assert.Equal(FluidResistanceUnit.PascalMinutePerLiter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 Pa·min/ml", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PascalMinutesPerMilliliter, PascalMinutesPerMilliliterTolerance); - Assert.Equal(FluidResistanceUnit.PascalMinutePerMilliliter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 Па·мин/мл", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PascalMinutesPerMilliliter, PascalMinutesPerMilliliterTolerance); - Assert.Equal(FluidResistanceUnit.PascalMinutePerMilliliter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 Pa·s/cm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PascalSecondsPerCubicCentimeter, PascalSecondsPerCubicCentimeterTolerance); - Assert.Equal(FluidResistanceUnit.PascalSecondPerCubicCentimeter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 Па·с/см³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PascalSecondsPerCubicCentimeter, PascalSecondsPerCubicCentimeterTolerance); - Assert.Equal(FluidResistanceUnit.PascalSecondPerCubicCentimeter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 Pa·s/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PascalSecondsPerCubicMeter, PascalSecondsPerCubicMeterTolerance); - Assert.Equal(FluidResistanceUnit.PascalSecondPerCubicMeter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 Па·с/м³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PascalSecondsPerCubicMeter, PascalSecondsPerCubicMeterTolerance); - Assert.Equal(FluidResistanceUnit.PascalSecondPerCubicMeter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 Pa·s/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PascalSecondsPerLiter, PascalSecondsPerLiterTolerance); - Assert.Equal(FluidResistanceUnit.PascalSecondPerLiter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 Па·с/л", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PascalSecondsPerLiter, PascalSecondsPerLiterTolerance); - Assert.Equal(FluidResistanceUnit.PascalSecondPerLiter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 Pa·s/ml", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PascalSecondsPerMilliliter, PascalSecondsPerMilliliterTolerance); - Assert.Equal(FluidResistanceUnit.PascalSecondPerMilliliter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 Па·с/мл", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PascalSecondsPerMilliliter, PascalSecondsPerMilliliterTolerance); - Assert.Equal(FluidResistanceUnit.PascalSecondPerMilliliter, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 WU", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WoodUnits, WoodUnitsTolerance); - Assert.Equal(FluidResistanceUnit.WoodUnit, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 HRU", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WoodUnits, WoodUnitsTolerance); - Assert.Equal(FluidResistanceUnit.WoodUnit, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 ЕВ", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WoodUnits, WoodUnitsTolerance); - Assert.Equal(FluidResistanceUnit.WoodUnit, parsed.Unit); - } - - { - Assert.True(FluidResistance.TryParse("1 ЕГС", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WoodUnits, WoodUnitsTolerance); - Assert.Equal(FluidResistanceUnit.WoodUnit, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(FluidResistance.TryParse(quantityString, out FluidResistance parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -1321,6 +885,64 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, FluidR Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth, "dyn·s/cm⁵")] + [InlineData("en-US", FluidResistanceUnit.MegapascalSecondPerCubicMeter, "MPa·s/m³")] + [InlineData("en-US", FluidResistanceUnit.MillimeterMercuryMinutePerCubicCentimeter, "mmHg·min/cm³")] + [InlineData("en-US", FluidResistanceUnit.MillimeterMercuryMinutePerCubicMeter, "mmHg·min/m³")] + [InlineData("en-US", FluidResistanceUnit.MillimeterMercuryMinutePerLiter, "mmHg·min/l")] + [InlineData("en-US", FluidResistanceUnit.MillimeterMercuryMinutePerMilliliter, "mmHg·min/ml")] + [InlineData("en-US", FluidResistanceUnit.MillimeterMercurySecondPerCubicCentimeter, "mmHg·s/cm³")] + [InlineData("en-US", FluidResistanceUnit.MillimeterMercurySecondPerCubicMeter, "mmHg·s/m³")] + [InlineData("en-US", FluidResistanceUnit.MillimeterMercurySecondPerLiter, "mmHg·s/l")] + [InlineData("en-US", FluidResistanceUnit.MillimeterMercurySecondPerMilliliter, "mmHg·s/ml")] + [InlineData("en-US", FluidResistanceUnit.PascalMinutePerCubicCentimeter, "Pa·min/cm³")] + [InlineData("en-US", FluidResistanceUnit.PascalMinutePerCubicMeter, "Pa·min/m³")] + [InlineData("en-US", FluidResistanceUnit.PascalMinutePerLiter, "Pa·min/l")] + [InlineData("en-US", FluidResistanceUnit.PascalMinutePerMilliliter, "Pa·min/ml")] + [InlineData("en-US", FluidResistanceUnit.PascalSecondPerCubicCentimeter, "Pa·s/cm³")] + [InlineData("en-US", FluidResistanceUnit.PascalSecondPerCubicMeter, "Pa·s/m³")] + [InlineData("en-US", FluidResistanceUnit.PascalSecondPerLiter, "Pa·s/l")] + [InlineData("en-US", FluidResistanceUnit.PascalSecondPerMilliliter, "Pa·s/ml")] + [InlineData("en-US", FluidResistanceUnit.WoodUnit, "WU")] + [InlineData("ru-RU", FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth, "дин·с/см⁵")] + [InlineData("ru-RU", FluidResistanceUnit.MegapascalSecondPerCubicMeter, "МПа·с/м³")] + [InlineData("ru-RU", FluidResistanceUnit.MillimeterMercuryMinutePerCubicCentimeter, "мм рт.ст·мин/см³")] + [InlineData("ru-RU", FluidResistanceUnit.MillimeterMercuryMinutePerCubicMeter, "мм рт.ст·мин/м³")] + [InlineData("ru-RU", FluidResistanceUnit.MillimeterMercuryMinutePerLiter, "мм рт.ст·мин/л")] + [InlineData("ru-RU", FluidResistanceUnit.MillimeterMercuryMinutePerMilliliter, "мм рт.ст·мин/мл")] + [InlineData("ru-RU", FluidResistanceUnit.MillimeterMercurySecondPerCubicCentimeter, "мм рт.ст·с/см³")] + [InlineData("ru-RU", FluidResistanceUnit.MillimeterMercurySecondPerCubicMeter, "мм рт.ст·с/м³")] + [InlineData("ru-RU", FluidResistanceUnit.MillimeterMercurySecondPerLiter, "мм рт.ст·с/л")] + [InlineData("ru-RU", FluidResistanceUnit.MillimeterMercurySecondPerMilliliter, "мм рт.ст·с/мл")] + [InlineData("ru-RU", FluidResistanceUnit.PascalMinutePerCubicCentimeter, "Па·мин/см³")] + [InlineData("ru-RU", FluidResistanceUnit.PascalMinutePerCubicMeter, "Па·мин/м³")] + [InlineData("ru-RU", FluidResistanceUnit.PascalMinutePerLiter, "Па·мин/л")] + [InlineData("ru-RU", FluidResistanceUnit.PascalMinutePerMilliliter, "Па·мин/мл")] + [InlineData("ru-RU", FluidResistanceUnit.PascalSecondPerCubicCentimeter, "Па·с/см³")] + [InlineData("ru-RU", FluidResistanceUnit.PascalSecondPerCubicMeter, "Па·с/м³")] + [InlineData("ru-RU", FluidResistanceUnit.PascalSecondPerLiter, "Па·с/л")] + [InlineData("ru-RU", FluidResistanceUnit.PascalSecondPerMilliliter, "Па·с/мл")] + [InlineData("ru-RU", FluidResistanceUnit.WoodUnit, "ЕВ")] + public void GetAbbreviationForCulture(string culture, FluidResistanceUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = FluidResistance.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(FluidResistance.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = FluidResistance.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(FluidResistanceUnit unit) @@ -1351,6 +973,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); }); } @@ -1374,50 +997,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] @@ -1463,8 +1088,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); @@ -1501,23 +1124,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = FluidResistance.FromPascalSecondsPerCubicMeter(1); - Assert.True(v.Equals(FluidResistance.FromPascalSecondsPerCubicMeter(1), PascalSecondsPerCubicMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(FluidResistance.Zero, PascalSecondsPerCubicMeterTolerance, ComparisonType.Relative)); - Assert.True(FluidResistance.FromPascalSecondsPerCubicMeter(100).Equals(FluidResistance.FromPascalSecondsPerCubicMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(FluidResistance.FromPascalSecondsPerCubicMeter(100).Equals(FluidResistance.FromPascalSecondsPerCubicMeter(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = FluidResistance.FromPascalSecondsPerCubicMeter(1); - Assert.Throws(() => v.Equals(FluidResistance.FromPascalSecondsPerCubicMeter(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1532,6 +1138,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(pascalsecondpercubicmeter.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = FluidResistance.FromPascalSecondsPerCubicMeter(1); + var negativeTolerance = FluidResistance.FromPascalSecondsPerCubicMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1548,6 +1180,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() { @@ -1642,158 +1286,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = FluidResistance.FromPascalSecondsPerCubicMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = FluidResistance.FromPascalSecondsPerCubicMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = FluidResistance.FromPascalSecondsPerCubicMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = FluidResistance.FromPascalSecondsPerCubicMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = FluidResistance.FromPascalSecondsPerCubicMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = FluidResistance.FromPascalSecondsPerCubicMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = FluidResistance.FromPascalSecondsPerCubicMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = FluidResistance.FromPascalSecondsPerCubicMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = FluidResistance.FromPascalSecondsPerCubicMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = FluidResistance.FromPascalSecondsPerCubicMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = FluidResistance.FromPascalSecondsPerCubicMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = FluidResistance.FromPascalSecondsPerCubicMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = FluidResistance.FromPascalSecondsPerCubicMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = FluidResistance.FromPascalSecondsPerCubicMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = FluidResistance.FromPascalSecondsPerCubicMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = FluidResistance.FromPascalSecondsPerCubicMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(FluidResistance))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = FluidResistance.FromPascalSecondsPerCubicMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(FluidResistanceUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = FluidResistance.FromPascalSecondsPerCubicMeter(1.0); - Assert.Equal(FluidResistance.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = FluidResistance.FromPascalSecondsPerCubicMeter(1.0); - Assert.Equal(FluidResistance.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = FluidResistance.FromPascalSecondsPerCubicMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = FluidResistance.FromPascalSecondsPerCubicMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = FluidResistance.FromPascalSecondsPerCubicMeter(1.0); - Assert.Equal(new {FluidResistance.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 cf0f1d22fc..81a1c3b34f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ForceChangeRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ForceChangeRateTestsBase.g.cs @@ -152,7 +152,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ForceChangeRate(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -165,15 +165,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ForceChangeRate_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ForceChangeRateUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ForceChangeRate(1, ForceChangeRateUnit.NewtonPerSecond); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ForceChangeRate.Zero, quantityInfo.Zero); Assert.Equal("ForceChangeRate", quantityInfo.Name); + Assert.Equal(ForceChangeRate.Zero, quantityInfo.Zero); + Assert.Equal(ForceChangeRate.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ForceChangeRate.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void ForceChangeRateInfo_CreateWithCustomUnitInfos() + { + ForceChangeRateUnit[] expectedUnits = [ForceChangeRateUnit.NewtonPerSecond]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -201,63 +219,63 @@ public void NewtonPerSecondToForceChangeRateUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ForceChangeRate.From(1, ForceChangeRateUnit.CentinewtonPerSecond); - AssertEx.EqualTolerance(1, quantity00.CentinewtonsPerSecond, CentinewtonsPerSecondTolerance); + Assert.Equal(1, quantity00.CentinewtonsPerSecond); Assert.Equal(ForceChangeRateUnit.CentinewtonPerSecond, quantity00.Unit); var quantity01 = ForceChangeRate.From(1, ForceChangeRateUnit.DecanewtonPerMinute); - AssertEx.EqualTolerance(1, quantity01.DecanewtonsPerMinute, DecanewtonsPerMinuteTolerance); + Assert.Equal(1, quantity01.DecanewtonsPerMinute); Assert.Equal(ForceChangeRateUnit.DecanewtonPerMinute, quantity01.Unit); var quantity02 = ForceChangeRate.From(1, ForceChangeRateUnit.DecanewtonPerSecond); - AssertEx.EqualTolerance(1, quantity02.DecanewtonsPerSecond, DecanewtonsPerSecondTolerance); + Assert.Equal(1, quantity02.DecanewtonsPerSecond); Assert.Equal(ForceChangeRateUnit.DecanewtonPerSecond, quantity02.Unit); var quantity03 = ForceChangeRate.From(1, ForceChangeRateUnit.DecinewtonPerSecond); - AssertEx.EqualTolerance(1, quantity03.DecinewtonsPerSecond, DecinewtonsPerSecondTolerance); + Assert.Equal(1, quantity03.DecinewtonsPerSecond); Assert.Equal(ForceChangeRateUnit.DecinewtonPerSecond, quantity03.Unit); var quantity04 = ForceChangeRate.From(1, ForceChangeRateUnit.KilonewtonPerMinute); - AssertEx.EqualTolerance(1, quantity04.KilonewtonsPerMinute, KilonewtonsPerMinuteTolerance); + Assert.Equal(1, quantity04.KilonewtonsPerMinute); Assert.Equal(ForceChangeRateUnit.KilonewtonPerMinute, quantity04.Unit); var quantity05 = ForceChangeRate.From(1, ForceChangeRateUnit.KilonewtonPerSecond); - AssertEx.EqualTolerance(1, quantity05.KilonewtonsPerSecond, KilonewtonsPerSecondTolerance); + Assert.Equal(1, quantity05.KilonewtonsPerSecond); Assert.Equal(ForceChangeRateUnit.KilonewtonPerSecond, quantity05.Unit); var quantity06 = ForceChangeRate.From(1, ForceChangeRateUnit.KilopoundForcePerMinute); - AssertEx.EqualTolerance(1, quantity06.KilopoundsForcePerMinute, KilopoundsForcePerMinuteTolerance); + Assert.Equal(1, quantity06.KilopoundsForcePerMinute); Assert.Equal(ForceChangeRateUnit.KilopoundForcePerMinute, quantity06.Unit); var quantity07 = ForceChangeRate.From(1, ForceChangeRateUnit.KilopoundForcePerSecond); - AssertEx.EqualTolerance(1, quantity07.KilopoundsForcePerSecond, KilopoundsForcePerSecondTolerance); + Assert.Equal(1, quantity07.KilopoundsForcePerSecond); Assert.Equal(ForceChangeRateUnit.KilopoundForcePerSecond, quantity07.Unit); var quantity08 = ForceChangeRate.From(1, ForceChangeRateUnit.MicronewtonPerSecond); - AssertEx.EqualTolerance(1, quantity08.MicronewtonsPerSecond, MicronewtonsPerSecondTolerance); + Assert.Equal(1, quantity08.MicronewtonsPerSecond); Assert.Equal(ForceChangeRateUnit.MicronewtonPerSecond, quantity08.Unit); var quantity09 = ForceChangeRate.From(1, ForceChangeRateUnit.MillinewtonPerSecond); - AssertEx.EqualTolerance(1, quantity09.MillinewtonsPerSecond, MillinewtonsPerSecondTolerance); + Assert.Equal(1, quantity09.MillinewtonsPerSecond); Assert.Equal(ForceChangeRateUnit.MillinewtonPerSecond, quantity09.Unit); var quantity10 = ForceChangeRate.From(1, ForceChangeRateUnit.NanonewtonPerSecond); - AssertEx.EqualTolerance(1, quantity10.NanonewtonsPerSecond, NanonewtonsPerSecondTolerance); + Assert.Equal(1, quantity10.NanonewtonsPerSecond); Assert.Equal(ForceChangeRateUnit.NanonewtonPerSecond, quantity10.Unit); var quantity11 = ForceChangeRate.From(1, ForceChangeRateUnit.NewtonPerMinute); - AssertEx.EqualTolerance(1, quantity11.NewtonsPerMinute, NewtonsPerMinuteTolerance); + Assert.Equal(1, quantity11.NewtonsPerMinute); Assert.Equal(ForceChangeRateUnit.NewtonPerMinute, quantity11.Unit); var quantity12 = ForceChangeRate.From(1, ForceChangeRateUnit.NewtonPerSecond); - AssertEx.EqualTolerance(1, quantity12.NewtonsPerSecond, NewtonsPerSecondTolerance); + Assert.Equal(1, quantity12.NewtonsPerSecond); Assert.Equal(ForceChangeRateUnit.NewtonPerSecond, quantity12.Unit); var quantity13 = ForceChangeRate.From(1, ForceChangeRateUnit.PoundForcePerMinute); - AssertEx.EqualTolerance(1, quantity13.PoundsForcePerMinute, PoundsForcePerMinuteTolerance); + Assert.Equal(1, quantity13.PoundsForcePerMinute); Assert.Equal(ForceChangeRateUnit.PoundForcePerMinute, quantity13.Unit); var quantity14 = ForceChangeRate.From(1, ForceChangeRateUnit.PoundForcePerSecond); - AssertEx.EqualTolerance(1, quantity14.PoundsForcePerSecond, PoundsForcePerSecondTolerance); + Assert.Equal(1, quantity14.PoundsForcePerSecond); Assert.Equal(ForceChangeRateUnit.PoundForcePerSecond, quantity14.Unit); } @@ -407,261 +425,60 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 cN/s", ForceChangeRateUnit.CentinewtonPerSecond, 4.2)] + [InlineData("en-US", "4.2 daN/min", ForceChangeRateUnit.DecanewtonPerMinute, 4.2)] + [InlineData("en-US", "4.2 daN/s", ForceChangeRateUnit.DecanewtonPerSecond, 4.2)] + [InlineData("en-US", "4.2 dN/s", ForceChangeRateUnit.DecinewtonPerSecond, 4.2)] + [InlineData("en-US", "4.2 kN/min", ForceChangeRateUnit.KilonewtonPerMinute, 4.2)] + [InlineData("en-US", "4.2 kN/s", ForceChangeRateUnit.KilonewtonPerSecond, 4.2)] + [InlineData("en-US", "4.2 kipf/min", ForceChangeRateUnit.KilopoundForcePerMinute, 4.2)] + [InlineData("en-US", "4.2 kip/min", ForceChangeRateUnit.KilopoundForcePerMinute, 4.2)] + [InlineData("en-US", "4.2 k/min", ForceChangeRateUnit.KilopoundForcePerMinute, 4.2)] + [InlineData("en-US", "4.2 kipf/s", ForceChangeRateUnit.KilopoundForcePerSecond, 4.2)] + [InlineData("en-US", "4.2 kip/s", ForceChangeRateUnit.KilopoundForcePerSecond, 4.2)] + [InlineData("en-US", "4.2 k/s", ForceChangeRateUnit.KilopoundForcePerSecond, 4.2)] + [InlineData("en-US", "4.2 µN/s", ForceChangeRateUnit.MicronewtonPerSecond, 4.2)] + [InlineData("en-US", "4.2 mN/s", ForceChangeRateUnit.MillinewtonPerSecond, 4.2)] + [InlineData("en-US", "4.2 nN/s", ForceChangeRateUnit.NanonewtonPerSecond, 4.2)] + [InlineData("en-US", "4.2 N/min", ForceChangeRateUnit.NewtonPerMinute, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = ForceChangeRate.Parse("1 cN/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentinewtonsPerSecond, CentinewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.CentinewtonPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForceChangeRate.Parse("1 daN/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecanewtonsPerMinute, DecanewtonsPerMinuteTolerance); - Assert.Equal(ForceChangeRateUnit.DecanewtonPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForceChangeRate.Parse("1 daN/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecanewtonsPerSecond, DecanewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.DecanewtonPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForceChangeRate.Parse("1 dN/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecinewtonsPerSecond, DecinewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.DecinewtonPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForceChangeRate.Parse("1 kN/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerMinute, KilonewtonsPerMinuteTolerance); - Assert.Equal(ForceChangeRateUnit.KilonewtonPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForceChangeRate.Parse("1 kN/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerSecond, KilonewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.KilonewtonPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForceChangeRate.Parse("1 kipf/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerMinute, KilopoundsForcePerMinuteTolerance); - Assert.Equal(ForceChangeRateUnit.KilopoundForcePerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForceChangeRate.Parse("1 kip/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerMinute, KilopoundsForcePerMinuteTolerance); - Assert.Equal(ForceChangeRateUnit.KilopoundForcePerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForceChangeRate.Parse("1 k/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerMinute, KilopoundsForcePerMinuteTolerance); - Assert.Equal(ForceChangeRateUnit.KilopoundForcePerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForceChangeRate.Parse("1 kipf/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSecond, KilopoundsForcePerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.KilopoundForcePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForceChangeRate.Parse("1 kip/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSecond, KilopoundsForcePerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.KilopoundForcePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForceChangeRate.Parse("1 k/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSecond, KilopoundsForcePerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.KilopoundForcePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForceChangeRate.Parse("1 µN/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicronewtonsPerSecond, MicronewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.MicronewtonPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForceChangeRate.Parse("1 mN/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillinewtonsPerSecond, MillinewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.MillinewtonPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForceChangeRate.Parse("1 nN/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanonewtonsPerSecond, NanonewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.NanonewtonPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForceChangeRate.Parse("1 N/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonsPerMinute, NewtonsPerMinuteTolerance); - Assert.Equal(ForceChangeRateUnit.NewtonPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForceChangeRate.Parse("1 N/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonsPerSecond, NewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.NewtonPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForceChangeRate.Parse("1 lbf/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerMinute, PoundsForcePerMinuteTolerance); - Assert.Equal(ForceChangeRateUnit.PoundForcePerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForceChangeRate.Parse("1 lbf/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSecond, PoundsForcePerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.PoundForcePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ForceChangeRate.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 cN/s", ForceChangeRateUnit.CentinewtonPerSecond, 4.2)] + [InlineData("en-US", "4.2 daN/min", ForceChangeRateUnit.DecanewtonPerMinute, 4.2)] + [InlineData("en-US", "4.2 daN/s", ForceChangeRateUnit.DecanewtonPerSecond, 4.2)] + [InlineData("en-US", "4.2 dN/s", ForceChangeRateUnit.DecinewtonPerSecond, 4.2)] + [InlineData("en-US", "4.2 kN/min", ForceChangeRateUnit.KilonewtonPerMinute, 4.2)] + [InlineData("en-US", "4.2 kN/s", ForceChangeRateUnit.KilonewtonPerSecond, 4.2)] + [InlineData("en-US", "4.2 kipf/min", ForceChangeRateUnit.KilopoundForcePerMinute, 4.2)] + [InlineData("en-US", "4.2 kip/min", ForceChangeRateUnit.KilopoundForcePerMinute, 4.2)] + [InlineData("en-US", "4.2 k/min", ForceChangeRateUnit.KilopoundForcePerMinute, 4.2)] + [InlineData("en-US", "4.2 kipf/s", ForceChangeRateUnit.KilopoundForcePerSecond, 4.2)] + [InlineData("en-US", "4.2 kip/s", ForceChangeRateUnit.KilopoundForcePerSecond, 4.2)] + [InlineData("en-US", "4.2 k/s", ForceChangeRateUnit.KilopoundForcePerSecond, 4.2)] + [InlineData("en-US", "4.2 µN/s", ForceChangeRateUnit.MicronewtonPerSecond, 4.2)] + [InlineData("en-US", "4.2 mN/s", ForceChangeRateUnit.MillinewtonPerSecond, 4.2)] + [InlineData("en-US", "4.2 nN/s", ForceChangeRateUnit.NanonewtonPerSecond, 4.2)] + [InlineData("en-US", "4.2 N/min", ForceChangeRateUnit.NewtonPerMinute, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(ForceChangeRate.TryParse("1 cN/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentinewtonsPerSecond, CentinewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.CentinewtonPerSecond, parsed.Unit); - } - - { - Assert.True(ForceChangeRate.TryParse("1 daN/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecanewtonsPerMinute, DecanewtonsPerMinuteTolerance); - Assert.Equal(ForceChangeRateUnit.DecanewtonPerMinute, parsed.Unit); - } - - { - Assert.True(ForceChangeRate.TryParse("1 daN/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecanewtonsPerSecond, DecanewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.DecanewtonPerSecond, parsed.Unit); - } - - { - Assert.True(ForceChangeRate.TryParse("1 dN/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecinewtonsPerSecond, DecinewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.DecinewtonPerSecond, parsed.Unit); - } - - { - Assert.True(ForceChangeRate.TryParse("1 kN/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerMinute, KilonewtonsPerMinuteTolerance); - Assert.Equal(ForceChangeRateUnit.KilonewtonPerMinute, parsed.Unit); - } - - { - Assert.True(ForceChangeRate.TryParse("1 kN/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerSecond, KilonewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.KilonewtonPerSecond, parsed.Unit); - } - - { - Assert.True(ForceChangeRate.TryParse("1 kipf/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerMinute, KilopoundsForcePerMinuteTolerance); - Assert.Equal(ForceChangeRateUnit.KilopoundForcePerMinute, parsed.Unit); - } - - { - Assert.True(ForceChangeRate.TryParse("1 kip/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerMinute, KilopoundsForcePerMinuteTolerance); - Assert.Equal(ForceChangeRateUnit.KilopoundForcePerMinute, parsed.Unit); - } - - { - Assert.True(ForceChangeRate.TryParse("1 k/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerMinute, KilopoundsForcePerMinuteTolerance); - Assert.Equal(ForceChangeRateUnit.KilopoundForcePerMinute, parsed.Unit); - } - - { - Assert.True(ForceChangeRate.TryParse("1 kipf/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSecond, KilopoundsForcePerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.KilopoundForcePerSecond, parsed.Unit); - } - - { - Assert.True(ForceChangeRate.TryParse("1 kip/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSecond, KilopoundsForcePerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.KilopoundForcePerSecond, parsed.Unit); - } - - { - Assert.True(ForceChangeRate.TryParse("1 k/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSecond, KilopoundsForcePerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.KilopoundForcePerSecond, parsed.Unit); - } - - { - Assert.True(ForceChangeRate.TryParse("1 µN/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicronewtonsPerSecond, MicronewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.MicronewtonPerSecond, parsed.Unit); - } - - { - Assert.True(ForceChangeRate.TryParse("1 mN/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillinewtonsPerSecond, MillinewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.MillinewtonPerSecond, parsed.Unit); - } - - { - Assert.True(ForceChangeRate.TryParse("1 nN/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanonewtonsPerSecond, NanonewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.NanonewtonPerSecond, parsed.Unit); - } - - { - Assert.True(ForceChangeRate.TryParse("1 N/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonsPerMinute, NewtonsPerMinuteTolerance); - Assert.Equal(ForceChangeRateUnit.NewtonPerMinute, parsed.Unit); - } - - { - Assert.True(ForceChangeRate.TryParse("1 N/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonsPerSecond, NewtonsPerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.NewtonPerSecond, parsed.Unit); - } - - { - Assert.True(ForceChangeRate.TryParse("1 lbf/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerMinute, PoundsForcePerMinuteTolerance); - Assert.Equal(ForceChangeRateUnit.PoundForcePerMinute, parsed.Unit); - } - - { - Assert.True(ForceChangeRate.TryParse("1 lbf/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSecond, PoundsForcePerSecondTolerance); - Assert.Equal(ForceChangeRateUnit.PoundForcePerSecond, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ForceChangeRate.TryParse(quantityString, out ForceChangeRate parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -882,6 +699,41 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, ForceC Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ForceChangeRateUnit.CentinewtonPerSecond, "cN/s")] + [InlineData("en-US", ForceChangeRateUnit.DecanewtonPerMinute, "daN/min")] + [InlineData("en-US", ForceChangeRateUnit.DecanewtonPerSecond, "daN/s")] + [InlineData("en-US", ForceChangeRateUnit.DecinewtonPerSecond, "dN/s")] + [InlineData("en-US", ForceChangeRateUnit.KilonewtonPerMinute, "kN/min")] + [InlineData("en-US", ForceChangeRateUnit.KilonewtonPerSecond, "kN/s")] + [InlineData("en-US", ForceChangeRateUnit.KilopoundForcePerMinute, "kipf/min")] + [InlineData("en-US", ForceChangeRateUnit.KilopoundForcePerSecond, "kipf/s")] + [InlineData("en-US", ForceChangeRateUnit.MicronewtonPerSecond, "µN/s")] + [InlineData("en-US", ForceChangeRateUnit.MillinewtonPerSecond, "mN/s")] + [InlineData("en-US", ForceChangeRateUnit.NanonewtonPerSecond, "nN/s")] + [InlineData("en-US", ForceChangeRateUnit.NewtonPerMinute, "N/min")] + [InlineData("en-US", ForceChangeRateUnit.NewtonPerSecond, "N/s")] + [InlineData("en-US", ForceChangeRateUnit.PoundForcePerMinute, "lbf/min")] + [InlineData("en-US", ForceChangeRateUnit.PoundForcePerSecond, "lbf/s")] + public void GetAbbreviationForCulture(string culture, ForceChangeRateUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ForceChangeRate.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ForceChangeRate.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ForceChangeRate.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ForceChangeRateUnit unit) @@ -912,6 +764,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); }); } @@ -935,46 +788,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] @@ -1020,8 +875,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); @@ -1058,23 +911,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = ForceChangeRate.FromNewtonsPerSecond(1); - Assert.True(v.Equals(ForceChangeRate.FromNewtonsPerSecond(1), NewtonsPerSecondTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ForceChangeRate.Zero, NewtonsPerSecondTolerance, ComparisonType.Relative)); - Assert.True(ForceChangeRate.FromNewtonsPerSecond(100).Equals(ForceChangeRate.FromNewtonsPerSecond(120), 0.3, ComparisonType.Relative)); - Assert.False(ForceChangeRate.FromNewtonsPerSecond(100).Equals(ForceChangeRate.FromNewtonsPerSecond(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = ForceChangeRate.FromNewtonsPerSecond(1); - Assert.Throws(() => v.Equals(ForceChangeRate.FromNewtonsPerSecond(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1089,6 +925,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(newtonpersecond.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = ForceChangeRate.FromNewtonsPerSecond(1); + var negativeTolerance = ForceChangeRate.FromNewtonsPerSecond(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1105,6 +967,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() { @@ -1191,158 +1065,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ForceChangeRate))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ForceChangeRateUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal(ForceChangeRate.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal(ForceChangeRate.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal(new {ForceChangeRate.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 d1d91822fd..2f85d7d37f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ForcePerLengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ForcePerLengthTestsBase.g.cs @@ -244,7 +244,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ForcePerLength(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -257,15 +257,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ForcePerLength_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ForcePerLengthUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ForcePerLength(1, ForcePerLengthUnit.NewtonPerMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ForcePerLength.Zero, quantityInfo.Zero); Assert.Equal("ForcePerLength", quantityInfo.Name); + Assert.Equal(ForcePerLength.Zero, quantityInfo.Zero); + Assert.Equal(ForcePerLength.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ForcePerLength.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void ForcePerLengthInfo_CreateWithCustomUnitInfos() + { + ForcePerLengthUnit[] expectedUnits = [ForcePerLengthUnit.NewtonPerMeter]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -316,155 +334,155 @@ public void NewtonPerMeterToForcePerLengthUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ForcePerLength.From(1, ForcePerLengthUnit.CentinewtonPerCentimeter); - AssertEx.EqualTolerance(1, quantity00.CentinewtonsPerCentimeter, CentinewtonsPerCentimeterTolerance); + Assert.Equal(1, quantity00.CentinewtonsPerCentimeter); Assert.Equal(ForcePerLengthUnit.CentinewtonPerCentimeter, quantity00.Unit); var quantity01 = ForcePerLength.From(1, ForcePerLengthUnit.CentinewtonPerMeter); - AssertEx.EqualTolerance(1, quantity01.CentinewtonsPerMeter, CentinewtonsPerMeterTolerance); + Assert.Equal(1, quantity01.CentinewtonsPerMeter); Assert.Equal(ForcePerLengthUnit.CentinewtonPerMeter, quantity01.Unit); var quantity02 = ForcePerLength.From(1, ForcePerLengthUnit.CentinewtonPerMillimeter); - AssertEx.EqualTolerance(1, quantity02.CentinewtonsPerMillimeter, CentinewtonsPerMillimeterTolerance); + Assert.Equal(1, quantity02.CentinewtonsPerMillimeter); Assert.Equal(ForcePerLengthUnit.CentinewtonPerMillimeter, quantity02.Unit); var quantity03 = ForcePerLength.From(1, ForcePerLengthUnit.DecanewtonPerCentimeter); - AssertEx.EqualTolerance(1, quantity03.DecanewtonsPerCentimeter, DecanewtonsPerCentimeterTolerance); + Assert.Equal(1, quantity03.DecanewtonsPerCentimeter); Assert.Equal(ForcePerLengthUnit.DecanewtonPerCentimeter, quantity03.Unit); var quantity04 = ForcePerLength.From(1, ForcePerLengthUnit.DecanewtonPerMeter); - AssertEx.EqualTolerance(1, quantity04.DecanewtonsPerMeter, DecanewtonsPerMeterTolerance); + Assert.Equal(1, quantity04.DecanewtonsPerMeter); Assert.Equal(ForcePerLengthUnit.DecanewtonPerMeter, quantity04.Unit); var quantity05 = ForcePerLength.From(1, ForcePerLengthUnit.DecanewtonPerMillimeter); - AssertEx.EqualTolerance(1, quantity05.DecanewtonsPerMillimeter, DecanewtonsPerMillimeterTolerance); + Assert.Equal(1, quantity05.DecanewtonsPerMillimeter); Assert.Equal(ForcePerLengthUnit.DecanewtonPerMillimeter, quantity05.Unit); var quantity06 = ForcePerLength.From(1, ForcePerLengthUnit.DecinewtonPerCentimeter); - AssertEx.EqualTolerance(1, quantity06.DecinewtonsPerCentimeter, DecinewtonsPerCentimeterTolerance); + Assert.Equal(1, quantity06.DecinewtonsPerCentimeter); Assert.Equal(ForcePerLengthUnit.DecinewtonPerCentimeter, quantity06.Unit); var quantity07 = ForcePerLength.From(1, ForcePerLengthUnit.DecinewtonPerMeter); - AssertEx.EqualTolerance(1, quantity07.DecinewtonsPerMeter, DecinewtonsPerMeterTolerance); + Assert.Equal(1, quantity07.DecinewtonsPerMeter); Assert.Equal(ForcePerLengthUnit.DecinewtonPerMeter, quantity07.Unit); var quantity08 = ForcePerLength.From(1, ForcePerLengthUnit.DecinewtonPerMillimeter); - AssertEx.EqualTolerance(1, quantity08.DecinewtonsPerMillimeter, DecinewtonsPerMillimeterTolerance); + Assert.Equal(1, quantity08.DecinewtonsPerMillimeter); Assert.Equal(ForcePerLengthUnit.DecinewtonPerMillimeter, quantity08.Unit); var quantity09 = ForcePerLength.From(1, ForcePerLengthUnit.KilogramForcePerCentimeter); - AssertEx.EqualTolerance(1, quantity09.KilogramsForcePerCentimeter, KilogramsForcePerCentimeterTolerance); + Assert.Equal(1, quantity09.KilogramsForcePerCentimeter); Assert.Equal(ForcePerLengthUnit.KilogramForcePerCentimeter, quantity09.Unit); var quantity10 = ForcePerLength.From(1, ForcePerLengthUnit.KilogramForcePerMeter); - AssertEx.EqualTolerance(1, quantity10.KilogramsForcePerMeter, KilogramsForcePerMeterTolerance); + Assert.Equal(1, quantity10.KilogramsForcePerMeter); Assert.Equal(ForcePerLengthUnit.KilogramForcePerMeter, quantity10.Unit); var quantity11 = ForcePerLength.From(1, ForcePerLengthUnit.KilogramForcePerMillimeter); - AssertEx.EqualTolerance(1, quantity11.KilogramsForcePerMillimeter, KilogramsForcePerMillimeterTolerance); + Assert.Equal(1, quantity11.KilogramsForcePerMillimeter); Assert.Equal(ForcePerLengthUnit.KilogramForcePerMillimeter, quantity11.Unit); var quantity12 = ForcePerLength.From(1, ForcePerLengthUnit.KilonewtonPerCentimeter); - AssertEx.EqualTolerance(1, quantity12.KilonewtonsPerCentimeter, KilonewtonsPerCentimeterTolerance); + Assert.Equal(1, quantity12.KilonewtonsPerCentimeter); Assert.Equal(ForcePerLengthUnit.KilonewtonPerCentimeter, quantity12.Unit); var quantity13 = ForcePerLength.From(1, ForcePerLengthUnit.KilonewtonPerMeter); - AssertEx.EqualTolerance(1, quantity13.KilonewtonsPerMeter, KilonewtonsPerMeterTolerance); + Assert.Equal(1, quantity13.KilonewtonsPerMeter); Assert.Equal(ForcePerLengthUnit.KilonewtonPerMeter, quantity13.Unit); var quantity14 = ForcePerLength.From(1, ForcePerLengthUnit.KilonewtonPerMillimeter); - AssertEx.EqualTolerance(1, quantity14.KilonewtonsPerMillimeter, KilonewtonsPerMillimeterTolerance); + Assert.Equal(1, quantity14.KilonewtonsPerMillimeter); Assert.Equal(ForcePerLengthUnit.KilonewtonPerMillimeter, quantity14.Unit); var quantity15 = ForcePerLength.From(1, ForcePerLengthUnit.KilopoundForcePerFoot); - AssertEx.EqualTolerance(1, quantity15.KilopoundsForcePerFoot, KilopoundsForcePerFootTolerance); + Assert.Equal(1, quantity15.KilopoundsForcePerFoot); Assert.Equal(ForcePerLengthUnit.KilopoundForcePerFoot, quantity15.Unit); var quantity16 = ForcePerLength.From(1, ForcePerLengthUnit.KilopoundForcePerInch); - AssertEx.EqualTolerance(1, quantity16.KilopoundsForcePerInch, KilopoundsForcePerInchTolerance); + Assert.Equal(1, quantity16.KilopoundsForcePerInch); Assert.Equal(ForcePerLengthUnit.KilopoundForcePerInch, quantity16.Unit); var quantity17 = ForcePerLength.From(1, ForcePerLengthUnit.MeganewtonPerCentimeter); - AssertEx.EqualTolerance(1, quantity17.MeganewtonsPerCentimeter, MeganewtonsPerCentimeterTolerance); + Assert.Equal(1, quantity17.MeganewtonsPerCentimeter); Assert.Equal(ForcePerLengthUnit.MeganewtonPerCentimeter, quantity17.Unit); var quantity18 = ForcePerLength.From(1, ForcePerLengthUnit.MeganewtonPerMeter); - AssertEx.EqualTolerance(1, quantity18.MeganewtonsPerMeter, MeganewtonsPerMeterTolerance); + Assert.Equal(1, quantity18.MeganewtonsPerMeter); Assert.Equal(ForcePerLengthUnit.MeganewtonPerMeter, quantity18.Unit); var quantity19 = ForcePerLength.From(1, ForcePerLengthUnit.MeganewtonPerMillimeter); - AssertEx.EqualTolerance(1, quantity19.MeganewtonsPerMillimeter, MeganewtonsPerMillimeterTolerance); + Assert.Equal(1, quantity19.MeganewtonsPerMillimeter); Assert.Equal(ForcePerLengthUnit.MeganewtonPerMillimeter, quantity19.Unit); var quantity20 = ForcePerLength.From(1, ForcePerLengthUnit.MicronewtonPerCentimeter); - AssertEx.EqualTolerance(1, quantity20.MicronewtonsPerCentimeter, MicronewtonsPerCentimeterTolerance); + Assert.Equal(1, quantity20.MicronewtonsPerCentimeter); Assert.Equal(ForcePerLengthUnit.MicronewtonPerCentimeter, quantity20.Unit); var quantity21 = ForcePerLength.From(1, ForcePerLengthUnit.MicronewtonPerMeter); - AssertEx.EqualTolerance(1, quantity21.MicronewtonsPerMeter, MicronewtonsPerMeterTolerance); + Assert.Equal(1, quantity21.MicronewtonsPerMeter); Assert.Equal(ForcePerLengthUnit.MicronewtonPerMeter, quantity21.Unit); var quantity22 = ForcePerLength.From(1, ForcePerLengthUnit.MicronewtonPerMillimeter); - AssertEx.EqualTolerance(1, quantity22.MicronewtonsPerMillimeter, MicronewtonsPerMillimeterTolerance); + Assert.Equal(1, quantity22.MicronewtonsPerMillimeter); Assert.Equal(ForcePerLengthUnit.MicronewtonPerMillimeter, quantity22.Unit); var quantity23 = ForcePerLength.From(1, ForcePerLengthUnit.MillinewtonPerCentimeter); - AssertEx.EqualTolerance(1, quantity23.MillinewtonsPerCentimeter, MillinewtonsPerCentimeterTolerance); + Assert.Equal(1, quantity23.MillinewtonsPerCentimeter); Assert.Equal(ForcePerLengthUnit.MillinewtonPerCentimeter, quantity23.Unit); var quantity24 = ForcePerLength.From(1, ForcePerLengthUnit.MillinewtonPerMeter); - AssertEx.EqualTolerance(1, quantity24.MillinewtonsPerMeter, MillinewtonsPerMeterTolerance); + Assert.Equal(1, quantity24.MillinewtonsPerMeter); Assert.Equal(ForcePerLengthUnit.MillinewtonPerMeter, quantity24.Unit); var quantity25 = ForcePerLength.From(1, ForcePerLengthUnit.MillinewtonPerMillimeter); - AssertEx.EqualTolerance(1, quantity25.MillinewtonsPerMillimeter, MillinewtonsPerMillimeterTolerance); + Assert.Equal(1, quantity25.MillinewtonsPerMillimeter); Assert.Equal(ForcePerLengthUnit.MillinewtonPerMillimeter, quantity25.Unit); var quantity26 = ForcePerLength.From(1, ForcePerLengthUnit.NanonewtonPerCentimeter); - AssertEx.EqualTolerance(1, quantity26.NanonewtonsPerCentimeter, NanonewtonsPerCentimeterTolerance); + Assert.Equal(1, quantity26.NanonewtonsPerCentimeter); Assert.Equal(ForcePerLengthUnit.NanonewtonPerCentimeter, quantity26.Unit); var quantity27 = ForcePerLength.From(1, ForcePerLengthUnit.NanonewtonPerMeter); - AssertEx.EqualTolerance(1, quantity27.NanonewtonsPerMeter, NanonewtonsPerMeterTolerance); + Assert.Equal(1, quantity27.NanonewtonsPerMeter); Assert.Equal(ForcePerLengthUnit.NanonewtonPerMeter, quantity27.Unit); var quantity28 = ForcePerLength.From(1, ForcePerLengthUnit.NanonewtonPerMillimeter); - AssertEx.EqualTolerance(1, quantity28.NanonewtonsPerMillimeter, NanonewtonsPerMillimeterTolerance); + Assert.Equal(1, quantity28.NanonewtonsPerMillimeter); Assert.Equal(ForcePerLengthUnit.NanonewtonPerMillimeter, quantity28.Unit); var quantity29 = ForcePerLength.From(1, ForcePerLengthUnit.NewtonPerCentimeter); - AssertEx.EqualTolerance(1, quantity29.NewtonsPerCentimeter, NewtonsPerCentimeterTolerance); + Assert.Equal(1, quantity29.NewtonsPerCentimeter); Assert.Equal(ForcePerLengthUnit.NewtonPerCentimeter, quantity29.Unit); var quantity30 = ForcePerLength.From(1, ForcePerLengthUnit.NewtonPerMeter); - AssertEx.EqualTolerance(1, quantity30.NewtonsPerMeter, NewtonsPerMeterTolerance); + Assert.Equal(1, quantity30.NewtonsPerMeter); Assert.Equal(ForcePerLengthUnit.NewtonPerMeter, quantity30.Unit); var quantity31 = ForcePerLength.From(1, ForcePerLengthUnit.NewtonPerMillimeter); - AssertEx.EqualTolerance(1, quantity31.NewtonsPerMillimeter, NewtonsPerMillimeterTolerance); + Assert.Equal(1, quantity31.NewtonsPerMillimeter); Assert.Equal(ForcePerLengthUnit.NewtonPerMillimeter, quantity31.Unit); var quantity32 = ForcePerLength.From(1, ForcePerLengthUnit.PoundForcePerFoot); - AssertEx.EqualTolerance(1, quantity32.PoundsForcePerFoot, PoundsForcePerFootTolerance); + Assert.Equal(1, quantity32.PoundsForcePerFoot); Assert.Equal(ForcePerLengthUnit.PoundForcePerFoot, quantity32.Unit); var quantity33 = ForcePerLength.From(1, ForcePerLengthUnit.PoundForcePerInch); - AssertEx.EqualTolerance(1, quantity33.PoundsForcePerInch, PoundsForcePerInchTolerance); + Assert.Equal(1, quantity33.PoundsForcePerInch); Assert.Equal(ForcePerLengthUnit.PoundForcePerInch, quantity33.Unit); var quantity34 = ForcePerLength.From(1, ForcePerLengthUnit.PoundForcePerYard); - AssertEx.EqualTolerance(1, quantity34.PoundsForcePerYard, PoundsForcePerYardTolerance); + Assert.Equal(1, quantity34.PoundsForcePerYard); Assert.Equal(ForcePerLengthUnit.PoundForcePerYard, quantity34.Unit); var quantity35 = ForcePerLength.From(1, ForcePerLengthUnit.TonneForcePerCentimeter); - AssertEx.EqualTolerance(1, quantity35.TonnesForcePerCentimeter, TonnesForcePerCentimeterTolerance); + Assert.Equal(1, quantity35.TonnesForcePerCentimeter); Assert.Equal(ForcePerLengthUnit.TonneForcePerCentimeter, quantity35.Unit); var quantity36 = ForcePerLength.From(1, ForcePerLengthUnit.TonneForcePerMeter); - AssertEx.EqualTolerance(1, quantity36.TonnesForcePerMeter, TonnesForcePerMeterTolerance); + Assert.Equal(1, quantity36.TonnesForcePerMeter); Assert.Equal(ForcePerLengthUnit.TonneForcePerMeter, quantity36.Unit); var quantity37 = ForcePerLength.From(1, ForcePerLengthUnit.TonneForcePerMillimeter); - AssertEx.EqualTolerance(1, quantity37.TonnesForcePerMillimeter, TonnesForcePerMillimeterTolerance); + Assert.Equal(1, quantity37.TonnesForcePerMillimeter); Assert.Equal(ForcePerLengthUnit.TonneForcePerMillimeter, quantity37.Unit); } @@ -637,602 +655,118 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 cN/cm", ForcePerLengthUnit.CentinewtonPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 cN/m", ForcePerLengthUnit.CentinewtonPerMeter, 4.2)] + [InlineData("en-US", "4.2 cN/mm", ForcePerLengthUnit.CentinewtonPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 daN/cm", ForcePerLengthUnit.DecanewtonPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 daN/m", ForcePerLengthUnit.DecanewtonPerMeter, 4.2)] + [InlineData("en-US", "4.2 daN/mm", ForcePerLengthUnit.DecanewtonPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 dN/cm", ForcePerLengthUnit.DecinewtonPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 dN/m", ForcePerLengthUnit.DecinewtonPerMeter, 4.2)] + [InlineData("en-US", "4.2 dN/mm", ForcePerLengthUnit.DecinewtonPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 kgf/cm", ForcePerLengthUnit.KilogramForcePerCentimeter, 4.2)] + [InlineData("en-US", "4.2 kgf/m", ForcePerLengthUnit.KilogramForcePerMeter, 4.2)] + [InlineData("en-US", "4.2 kgf/mm", ForcePerLengthUnit.KilogramForcePerMillimeter, 4.2)] + [InlineData("en-US", "4.2 kN/cm", ForcePerLengthUnit.KilonewtonPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 kN/m", ForcePerLengthUnit.KilonewtonPerMeter, 4.2)] + [InlineData("en-US", "4.2 kN/mm", ForcePerLengthUnit.KilonewtonPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 kipf/ft", ForcePerLengthUnit.KilopoundForcePerFoot, 4.2)] + [InlineData("en-US", "4.2 kip/ft", ForcePerLengthUnit.KilopoundForcePerFoot, 4.2)] + [InlineData("en-US", "4.2 k/ft", ForcePerLengthUnit.KilopoundForcePerFoot, 4.2)] + [InlineData("en-US", "4.2 kipf/in", ForcePerLengthUnit.KilopoundForcePerInch, 4.2)] + [InlineData("en-US", "4.2 kip/in", ForcePerLengthUnit.KilopoundForcePerInch, 4.2)] + [InlineData("en-US", "4.2 k/in", ForcePerLengthUnit.KilopoundForcePerInch, 4.2)] + [InlineData("en-US", "4.2 MN/cm", ForcePerLengthUnit.MeganewtonPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 MN/m", ForcePerLengthUnit.MeganewtonPerMeter, 4.2)] + [InlineData("en-US", "4.2 MN/mm", ForcePerLengthUnit.MeganewtonPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 µN/cm", ForcePerLengthUnit.MicronewtonPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 µN/m", ForcePerLengthUnit.MicronewtonPerMeter, 4.2)] + [InlineData("en-US", "4.2 µN/mm", ForcePerLengthUnit.MicronewtonPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 mN/cm", ForcePerLengthUnit.MillinewtonPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 mN/m", ForcePerLengthUnit.MillinewtonPerMeter, 4.2)] + [InlineData("en-US", "4.2 mN/mm", ForcePerLengthUnit.MillinewtonPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 nN/cm", ForcePerLengthUnit.NanonewtonPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 nN/m", ForcePerLengthUnit.NanonewtonPerMeter, 4.2)] + [InlineData("en-US", "4.2 nN/mm", ForcePerLengthUnit.NanonewtonPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 N/cm", ForcePerLengthUnit.NewtonPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 N/m", ForcePerLengthUnit.NewtonPerMeter, 4.2)] + [InlineData("en-US", "4.2 N/mm", ForcePerLengthUnit.NewtonPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 lbf/ft", ForcePerLengthUnit.PoundForcePerFoot, 4.2)] + [InlineData("en-US", "4.2 lbf/in", ForcePerLengthUnit.PoundForcePerInch, 4.2)] + [InlineData("en-US", "4.2 lbf/yd", ForcePerLengthUnit.PoundForcePerYard, 4.2)] + [InlineData("en-US", "4.2 tf/cm", ForcePerLengthUnit.TonneForcePerCentimeter, 4.2)] + [InlineData("en-US", "4.2 tf/m", ForcePerLengthUnit.TonneForcePerMeter, 4.2)] + [InlineData("en-US", "4.2 tf/mm", ForcePerLengthUnit.TonneForcePerMillimeter, 4.2)] + [InlineData("ru-RU", "4,2 кгс/см", ForcePerLengthUnit.KilogramForcePerCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 кгс/м", ForcePerLengthUnit.KilogramForcePerMeter, 4.2)] + [InlineData("ru-RU", "4,2 кгс/мм", ForcePerLengthUnit.KilogramForcePerMillimeter, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = ForcePerLength.Parse("1 cN/cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentinewtonsPerCentimeter, CentinewtonsPerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.CentinewtonPerCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 cN/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentinewtonsPerMeter, CentinewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.CentinewtonPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 cN/mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentinewtonsPerMillimeter, CentinewtonsPerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.CentinewtonPerMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 daN/cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecanewtonsPerCentimeter, DecanewtonsPerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.DecanewtonPerCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 daN/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecanewtonsPerMeter, DecanewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.DecanewtonPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 daN/mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecanewtonsPerMillimeter, DecanewtonsPerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.DecanewtonPerMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 dN/cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecinewtonsPerCentimeter, DecinewtonsPerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.DecinewtonPerCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 dN/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecinewtonsPerMeter, DecinewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.DecinewtonPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 dN/mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecinewtonsPerMillimeter, DecinewtonsPerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.DecinewtonPerMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 kgf/cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerCentimeter, KilogramsForcePerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.KilogramForcePerCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 кгс/см", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerCentimeter, KilogramsForcePerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.KilogramForcePerCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 kgf/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerMeter, KilogramsForcePerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.KilogramForcePerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 кгс/м", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerMeter, KilogramsForcePerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.KilogramForcePerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 kgf/mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerMillimeter, KilogramsForcePerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.KilogramForcePerMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 кгс/мм", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerMillimeter, KilogramsForcePerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.KilogramForcePerMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 kN/cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerCentimeter, KilonewtonsPerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.KilonewtonPerCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 kN/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerMeter, KilonewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.KilonewtonPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 kN/mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerMillimeter, KilonewtonsPerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.KilonewtonPerMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 kipf/ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerFoot, KilopoundsForcePerFootTolerance); - Assert.Equal(ForcePerLengthUnit.KilopoundForcePerFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 kip/ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerFoot, KilopoundsForcePerFootTolerance); - Assert.Equal(ForcePerLengthUnit.KilopoundForcePerFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 k/ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerFoot, KilopoundsForcePerFootTolerance); - Assert.Equal(ForcePerLengthUnit.KilopoundForcePerFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 kipf/in", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerInch, KilopoundsForcePerInchTolerance); - Assert.Equal(ForcePerLengthUnit.KilopoundForcePerInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 kip/in", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerInch, KilopoundsForcePerInchTolerance); - Assert.Equal(ForcePerLengthUnit.KilopoundForcePerInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 k/in", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerInch, KilopoundsForcePerInchTolerance); - Assert.Equal(ForcePerLengthUnit.KilopoundForcePerInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 MN/cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MeganewtonsPerCentimeter, MeganewtonsPerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.MeganewtonPerCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 MN/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MeganewtonsPerMeter, MeganewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.MeganewtonPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 MN/mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MeganewtonsPerMillimeter, MeganewtonsPerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.MeganewtonPerMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 µN/cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicronewtonsPerCentimeter, MicronewtonsPerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.MicronewtonPerCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 µN/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicronewtonsPerMeter, MicronewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.MicronewtonPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 µN/mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicronewtonsPerMillimeter, MicronewtonsPerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.MicronewtonPerMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 mN/cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillinewtonsPerCentimeter, MillinewtonsPerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.MillinewtonPerCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 mN/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillinewtonsPerMeter, MillinewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.MillinewtonPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 mN/mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillinewtonsPerMillimeter, MillinewtonsPerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.MillinewtonPerMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 nN/cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanonewtonsPerCentimeter, NanonewtonsPerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.NanonewtonPerCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 nN/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanonewtonsPerMeter, NanonewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.NanonewtonPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 nN/mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanonewtonsPerMillimeter, NanonewtonsPerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.NanonewtonPerMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 N/cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonsPerCentimeter, NewtonsPerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.NewtonPerCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 N/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonsPerMeter, NewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.NewtonPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 N/mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonsPerMillimeter, NewtonsPerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.NewtonPerMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 lbf/ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerFoot, PoundsForcePerFootTolerance); - Assert.Equal(ForcePerLengthUnit.PoundForcePerFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 lbf/in", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerInch, PoundsForcePerInchTolerance); - Assert.Equal(ForcePerLengthUnit.PoundForcePerInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 lbf/yd", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerYard, PoundsForcePerYardTolerance); - Assert.Equal(ForcePerLengthUnit.PoundForcePerYard, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 tf/cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonnesForcePerCentimeter, TonnesForcePerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.TonneForcePerCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 тс/см", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.TonnesForcePerCentimeter, TonnesForcePerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.TonneForcePerCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 tf/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonnesForcePerMeter, TonnesForcePerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.TonneForcePerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 тс/м", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.TonnesForcePerMeter, TonnesForcePerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.TonneForcePerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 tf/mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonnesForcePerMillimeter, TonnesForcePerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.TonneForcePerMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ForcePerLength.Parse("1 тс/мм", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.TonnesForcePerMillimeter, TonnesForcePerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.TonneForcePerMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ForcePerLength.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 cN/cm", ForcePerLengthUnit.CentinewtonPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 cN/m", ForcePerLengthUnit.CentinewtonPerMeter, 4.2)] + [InlineData("en-US", "4.2 cN/mm", ForcePerLengthUnit.CentinewtonPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 daN/cm", ForcePerLengthUnit.DecanewtonPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 daN/m", ForcePerLengthUnit.DecanewtonPerMeter, 4.2)] + [InlineData("en-US", "4.2 daN/mm", ForcePerLengthUnit.DecanewtonPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 dN/cm", ForcePerLengthUnit.DecinewtonPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 dN/m", ForcePerLengthUnit.DecinewtonPerMeter, 4.2)] + [InlineData("en-US", "4.2 dN/mm", ForcePerLengthUnit.DecinewtonPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 kgf/cm", ForcePerLengthUnit.KilogramForcePerCentimeter, 4.2)] + [InlineData("en-US", "4.2 kgf/m", ForcePerLengthUnit.KilogramForcePerMeter, 4.2)] + [InlineData("en-US", "4.2 kgf/mm", ForcePerLengthUnit.KilogramForcePerMillimeter, 4.2)] + [InlineData("en-US", "4.2 kN/cm", ForcePerLengthUnit.KilonewtonPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 kN/m", ForcePerLengthUnit.KilonewtonPerMeter, 4.2)] + [InlineData("en-US", "4.2 kN/mm", ForcePerLengthUnit.KilonewtonPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 kipf/ft", ForcePerLengthUnit.KilopoundForcePerFoot, 4.2)] + [InlineData("en-US", "4.2 kip/ft", ForcePerLengthUnit.KilopoundForcePerFoot, 4.2)] + [InlineData("en-US", "4.2 k/ft", ForcePerLengthUnit.KilopoundForcePerFoot, 4.2)] + [InlineData("en-US", "4.2 kipf/in", ForcePerLengthUnit.KilopoundForcePerInch, 4.2)] + [InlineData("en-US", "4.2 kip/in", ForcePerLengthUnit.KilopoundForcePerInch, 4.2)] + [InlineData("en-US", "4.2 k/in", ForcePerLengthUnit.KilopoundForcePerInch, 4.2)] + [InlineData("en-US", "4.2 MN/cm", ForcePerLengthUnit.MeganewtonPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 MN/m", ForcePerLengthUnit.MeganewtonPerMeter, 4.2)] + [InlineData("en-US", "4.2 MN/mm", ForcePerLengthUnit.MeganewtonPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 µN/cm", ForcePerLengthUnit.MicronewtonPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 µN/m", ForcePerLengthUnit.MicronewtonPerMeter, 4.2)] + [InlineData("en-US", "4.2 µN/mm", ForcePerLengthUnit.MicronewtonPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 mN/cm", ForcePerLengthUnit.MillinewtonPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 mN/m", ForcePerLengthUnit.MillinewtonPerMeter, 4.2)] + [InlineData("en-US", "4.2 mN/mm", ForcePerLengthUnit.MillinewtonPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 nN/cm", ForcePerLengthUnit.NanonewtonPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 nN/m", ForcePerLengthUnit.NanonewtonPerMeter, 4.2)] + [InlineData("en-US", "4.2 nN/mm", ForcePerLengthUnit.NanonewtonPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 N/cm", ForcePerLengthUnit.NewtonPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 N/m", ForcePerLengthUnit.NewtonPerMeter, 4.2)] + [InlineData("en-US", "4.2 N/mm", ForcePerLengthUnit.NewtonPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 lbf/ft", ForcePerLengthUnit.PoundForcePerFoot, 4.2)] + [InlineData("en-US", "4.2 lbf/in", ForcePerLengthUnit.PoundForcePerInch, 4.2)] + [InlineData("en-US", "4.2 lbf/yd", ForcePerLengthUnit.PoundForcePerYard, 4.2)] + [InlineData("en-US", "4.2 tf/cm", ForcePerLengthUnit.TonneForcePerCentimeter, 4.2)] + [InlineData("en-US", "4.2 tf/m", ForcePerLengthUnit.TonneForcePerMeter, 4.2)] + [InlineData("en-US", "4.2 tf/mm", ForcePerLengthUnit.TonneForcePerMillimeter, 4.2)] + [InlineData("ru-RU", "4,2 кгс/см", ForcePerLengthUnit.KilogramForcePerCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 кгс/м", ForcePerLengthUnit.KilogramForcePerMeter, 4.2)] + [InlineData("ru-RU", "4,2 кгс/мм", ForcePerLengthUnit.KilogramForcePerMillimeter, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(ForcePerLength.TryParse("1 cN/cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentinewtonsPerCentimeter, CentinewtonsPerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.CentinewtonPerCentimeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 cN/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentinewtonsPerMeter, CentinewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.CentinewtonPerMeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 cN/mm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentinewtonsPerMillimeter, CentinewtonsPerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.CentinewtonPerMillimeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 daN/cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecanewtonsPerCentimeter, DecanewtonsPerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.DecanewtonPerCentimeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 daN/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecanewtonsPerMeter, DecanewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.DecanewtonPerMeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 daN/mm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecanewtonsPerMillimeter, DecanewtonsPerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.DecanewtonPerMillimeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 dN/cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecinewtonsPerCentimeter, DecinewtonsPerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.DecinewtonPerCentimeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 dN/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecinewtonsPerMeter, DecinewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.DecinewtonPerMeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 dN/mm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecinewtonsPerMillimeter, DecinewtonsPerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.DecinewtonPerMillimeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 kgf/cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerCentimeter, KilogramsForcePerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.KilogramForcePerCentimeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 кгс/см", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerCentimeter, KilogramsForcePerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.KilogramForcePerCentimeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 kgf/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerMeter, KilogramsForcePerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.KilogramForcePerMeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 кгс/м", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerMeter, KilogramsForcePerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.KilogramForcePerMeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 kgf/mm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerMillimeter, KilogramsForcePerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.KilogramForcePerMillimeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 кгс/мм", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerMillimeter, KilogramsForcePerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.KilogramForcePerMillimeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 kN/cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerCentimeter, KilonewtonsPerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.KilonewtonPerCentimeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 kN/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerMeter, KilonewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.KilonewtonPerMeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 kN/mm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerMillimeter, KilonewtonsPerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.KilonewtonPerMillimeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 kipf/ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerFoot, KilopoundsForcePerFootTolerance); - Assert.Equal(ForcePerLengthUnit.KilopoundForcePerFoot, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 kip/ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerFoot, KilopoundsForcePerFootTolerance); - Assert.Equal(ForcePerLengthUnit.KilopoundForcePerFoot, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 k/ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerFoot, KilopoundsForcePerFootTolerance); - Assert.Equal(ForcePerLengthUnit.KilopoundForcePerFoot, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 kipf/in", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerInch, KilopoundsForcePerInchTolerance); - Assert.Equal(ForcePerLengthUnit.KilopoundForcePerInch, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 kip/in", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerInch, KilopoundsForcePerInchTolerance); - Assert.Equal(ForcePerLengthUnit.KilopoundForcePerInch, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 k/in", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerInch, KilopoundsForcePerInchTolerance); - Assert.Equal(ForcePerLengthUnit.KilopoundForcePerInch, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 µN/cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicronewtonsPerCentimeter, MicronewtonsPerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.MicronewtonPerCentimeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 µN/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicronewtonsPerMeter, MicronewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.MicronewtonPerMeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 µN/mm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicronewtonsPerMillimeter, MicronewtonsPerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.MicronewtonPerMillimeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 nN/cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanonewtonsPerCentimeter, NanonewtonsPerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.NanonewtonPerCentimeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 nN/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanonewtonsPerMeter, NanonewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.NanonewtonPerMeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 nN/mm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanonewtonsPerMillimeter, NanonewtonsPerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.NanonewtonPerMillimeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 N/cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonsPerCentimeter, NewtonsPerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.NewtonPerCentimeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 N/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonsPerMeter, NewtonsPerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.NewtonPerMeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 N/mm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonsPerMillimeter, NewtonsPerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.NewtonPerMillimeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 lbf/ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerFoot, PoundsForcePerFootTolerance); - Assert.Equal(ForcePerLengthUnit.PoundForcePerFoot, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 lbf/in", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerInch, PoundsForcePerInchTolerance); - Assert.Equal(ForcePerLengthUnit.PoundForcePerInch, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 lbf/yd", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerYard, PoundsForcePerYardTolerance); - Assert.Equal(ForcePerLengthUnit.PoundForcePerYard, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 tf/cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonnesForcePerCentimeter, TonnesForcePerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.TonneForcePerCentimeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 тс/см", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonnesForcePerCentimeter, TonnesForcePerCentimeterTolerance); - Assert.Equal(ForcePerLengthUnit.TonneForcePerCentimeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 tf/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonnesForcePerMeter, TonnesForcePerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.TonneForcePerMeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 тс/м", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonnesForcePerMeter, TonnesForcePerMeterTolerance); - Assert.Equal(ForcePerLengthUnit.TonneForcePerMeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 tf/mm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonnesForcePerMillimeter, TonnesForcePerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.TonneForcePerMillimeter, parsed.Unit); - } - - { - Assert.True(ForcePerLength.TryParse("1 тс/мм", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonnesForcePerMillimeter, TonnesForcePerMillimeterTolerance); - Assert.Equal(ForcePerLengthUnit.TonneForcePerMillimeter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ForcePerLength.TryParse(quantityString, out ForcePerLength parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -1661,6 +1195,70 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, ForceP Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ForcePerLengthUnit.CentinewtonPerCentimeter, "cN/cm")] + [InlineData("en-US", ForcePerLengthUnit.CentinewtonPerMeter, "cN/m")] + [InlineData("en-US", ForcePerLengthUnit.CentinewtonPerMillimeter, "cN/mm")] + [InlineData("en-US", ForcePerLengthUnit.DecanewtonPerCentimeter, "daN/cm")] + [InlineData("en-US", ForcePerLengthUnit.DecanewtonPerMeter, "daN/m")] + [InlineData("en-US", ForcePerLengthUnit.DecanewtonPerMillimeter, "daN/mm")] + [InlineData("en-US", ForcePerLengthUnit.DecinewtonPerCentimeter, "dN/cm")] + [InlineData("en-US", ForcePerLengthUnit.DecinewtonPerMeter, "dN/m")] + [InlineData("en-US", ForcePerLengthUnit.DecinewtonPerMillimeter, "dN/mm")] + [InlineData("en-US", ForcePerLengthUnit.KilogramForcePerCentimeter, "kgf/cm")] + [InlineData("en-US", ForcePerLengthUnit.KilogramForcePerMeter, "kgf/m")] + [InlineData("en-US", ForcePerLengthUnit.KilogramForcePerMillimeter, "kgf/mm")] + [InlineData("en-US", ForcePerLengthUnit.KilonewtonPerCentimeter, "kN/cm")] + [InlineData("en-US", ForcePerLengthUnit.KilonewtonPerMeter, "kN/m")] + [InlineData("en-US", ForcePerLengthUnit.KilonewtonPerMillimeter, "kN/mm")] + [InlineData("en-US", ForcePerLengthUnit.KilopoundForcePerFoot, "kipf/ft")] + [InlineData("en-US", ForcePerLengthUnit.KilopoundForcePerInch, "kipf/in")] + [InlineData("en-US", ForcePerLengthUnit.MeganewtonPerCentimeter, "MN/cm")] + [InlineData("en-US", ForcePerLengthUnit.MeganewtonPerMeter, "MN/m")] + [InlineData("en-US", ForcePerLengthUnit.MeganewtonPerMillimeter, "MN/mm")] + [InlineData("en-US", ForcePerLengthUnit.MicronewtonPerCentimeter, "µN/cm")] + [InlineData("en-US", ForcePerLengthUnit.MicronewtonPerMeter, "µN/m")] + [InlineData("en-US", ForcePerLengthUnit.MicronewtonPerMillimeter, "µN/mm")] + [InlineData("en-US", ForcePerLengthUnit.MillinewtonPerCentimeter, "mN/cm")] + [InlineData("en-US", ForcePerLengthUnit.MillinewtonPerMeter, "mN/m")] + [InlineData("en-US", ForcePerLengthUnit.MillinewtonPerMillimeter, "mN/mm")] + [InlineData("en-US", ForcePerLengthUnit.NanonewtonPerCentimeter, "nN/cm")] + [InlineData("en-US", ForcePerLengthUnit.NanonewtonPerMeter, "nN/m")] + [InlineData("en-US", ForcePerLengthUnit.NanonewtonPerMillimeter, "nN/mm")] + [InlineData("en-US", ForcePerLengthUnit.NewtonPerCentimeter, "N/cm")] + [InlineData("en-US", ForcePerLengthUnit.NewtonPerMeter, "N/m")] + [InlineData("en-US", ForcePerLengthUnit.NewtonPerMillimeter, "N/mm")] + [InlineData("en-US", ForcePerLengthUnit.PoundForcePerFoot, "lbf/ft")] + [InlineData("en-US", ForcePerLengthUnit.PoundForcePerInch, "lbf/in")] + [InlineData("en-US", ForcePerLengthUnit.PoundForcePerYard, "lbf/yd")] + [InlineData("en-US", ForcePerLengthUnit.TonneForcePerCentimeter, "tf/cm")] + [InlineData("en-US", ForcePerLengthUnit.TonneForcePerMeter, "tf/m")] + [InlineData("en-US", ForcePerLengthUnit.TonneForcePerMillimeter, "tf/mm")] + [InlineData("ru-RU", ForcePerLengthUnit.KilogramForcePerCentimeter, "кгс/см")] + [InlineData("ru-RU", ForcePerLengthUnit.KilogramForcePerMeter, "кгс/м")] + [InlineData("ru-RU", ForcePerLengthUnit.KilogramForcePerMillimeter, "кгс/мм")] + [InlineData("ru-RU", ForcePerLengthUnit.TonneForcePerCentimeter, "тс/см")] + [InlineData("ru-RU", ForcePerLengthUnit.TonneForcePerMeter, "тс/м")] + [InlineData("ru-RU", ForcePerLengthUnit.TonneForcePerMillimeter, "тс/мм")] + public void GetAbbreviationForCulture(string culture, ForcePerLengthUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ForcePerLength.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ForcePerLength.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ForcePerLength.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ForcePerLengthUnit unit) @@ -1691,6 +1289,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); }); } @@ -1714,69 +1313,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] @@ -1822,8 +1423,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); @@ -1860,23 +1459,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = ForcePerLength.FromNewtonsPerMeter(1); - Assert.True(v.Equals(ForcePerLength.FromNewtonsPerMeter(1), NewtonsPerMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ForcePerLength.Zero, NewtonsPerMeterTolerance, ComparisonType.Relative)); - Assert.True(ForcePerLength.FromNewtonsPerMeter(100).Equals(ForcePerLength.FromNewtonsPerMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(ForcePerLength.FromNewtonsPerMeter(100).Equals(ForcePerLength.FromNewtonsPerMeter(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = ForcePerLength.FromNewtonsPerMeter(1); - Assert.Throws(() => v.Equals(ForcePerLength.FromNewtonsPerMeter(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1891,6 +1473,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(newtonpermeter.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = ForcePerLength.FromNewtonsPerMeter(1); + var negativeTolerance = ForcePerLength.FromNewtonsPerMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1907,6 +1515,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() { @@ -2039,158 +1659,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ForcePerLength))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ForcePerLengthUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal(ForcePerLength.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal(ForcePerLength.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal(new {ForcePerLength.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 396a09d566..660c2e26df 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ForceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ForceTestsBase.g.cs @@ -152,7 +152,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Force(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -165,15 +165,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Force_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ForceUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Force(1, ForceUnit.Newton); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Force.Zero, quantityInfo.Zero); Assert.Equal("Force", quantityInfo.Name); + Assert.Equal(Force.Zero, quantityInfo.Zero); + Assert.Equal(Force.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Force.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -201,63 +219,63 @@ public void NewtonToForceUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Force.From(1, ForceUnit.Decanewton); - AssertEx.EqualTolerance(1, quantity00.Decanewtons, DecanewtonsTolerance); + Assert.Equal(1, quantity00.Decanewtons); Assert.Equal(ForceUnit.Decanewton, quantity00.Unit); var quantity01 = Force.From(1, ForceUnit.Dyn); - AssertEx.EqualTolerance(1, quantity01.Dyne, DyneTolerance); + Assert.Equal(1, quantity01.Dyne); Assert.Equal(ForceUnit.Dyn, quantity01.Unit); var quantity02 = Force.From(1, ForceUnit.KilogramForce); - AssertEx.EqualTolerance(1, quantity02.KilogramsForce, KilogramsForceTolerance); + Assert.Equal(1, quantity02.KilogramsForce); Assert.Equal(ForceUnit.KilogramForce, quantity02.Unit); var quantity03 = Force.From(1, ForceUnit.Kilonewton); - AssertEx.EqualTolerance(1, quantity03.Kilonewtons, KilonewtonsTolerance); + Assert.Equal(1, quantity03.Kilonewtons); Assert.Equal(ForceUnit.Kilonewton, quantity03.Unit); var quantity04 = Force.From(1, ForceUnit.KiloPond); - AssertEx.EqualTolerance(1, quantity04.KiloPonds, KiloPondsTolerance); + Assert.Equal(1, quantity04.KiloPonds); Assert.Equal(ForceUnit.KiloPond, quantity04.Unit); var quantity05 = Force.From(1, ForceUnit.KilopoundForce); - AssertEx.EqualTolerance(1, quantity05.KilopoundsForce, KilopoundsForceTolerance); + Assert.Equal(1, quantity05.KilopoundsForce); Assert.Equal(ForceUnit.KilopoundForce, quantity05.Unit); var quantity06 = Force.From(1, ForceUnit.Meganewton); - AssertEx.EqualTolerance(1, quantity06.Meganewtons, MeganewtonsTolerance); + Assert.Equal(1, quantity06.Meganewtons); Assert.Equal(ForceUnit.Meganewton, quantity06.Unit); var quantity07 = Force.From(1, ForceUnit.Micronewton); - AssertEx.EqualTolerance(1, quantity07.Micronewtons, MicronewtonsTolerance); + Assert.Equal(1, quantity07.Micronewtons); Assert.Equal(ForceUnit.Micronewton, quantity07.Unit); var quantity08 = Force.From(1, ForceUnit.Millinewton); - AssertEx.EqualTolerance(1, quantity08.Millinewtons, MillinewtonsTolerance); + Assert.Equal(1, quantity08.Millinewtons); Assert.Equal(ForceUnit.Millinewton, quantity08.Unit); var quantity09 = Force.From(1, ForceUnit.Newton); - AssertEx.EqualTolerance(1, quantity09.Newtons, NewtonsTolerance); + Assert.Equal(1, quantity09.Newtons); Assert.Equal(ForceUnit.Newton, quantity09.Unit); var quantity10 = Force.From(1, ForceUnit.OunceForce); - AssertEx.EqualTolerance(1, quantity10.OunceForce, OunceForceTolerance); + Assert.Equal(1, quantity10.OunceForce); Assert.Equal(ForceUnit.OunceForce, quantity10.Unit); var quantity11 = Force.From(1, ForceUnit.Poundal); - AssertEx.EqualTolerance(1, quantity11.Poundals, PoundalsTolerance); + Assert.Equal(1, quantity11.Poundals); Assert.Equal(ForceUnit.Poundal, quantity11.Unit); var quantity12 = Force.From(1, ForceUnit.PoundForce); - AssertEx.EqualTolerance(1, quantity12.PoundsForce, PoundsForceTolerance); + Assert.Equal(1, quantity12.PoundsForce); Assert.Equal(ForceUnit.PoundForce, quantity12.Unit); var quantity13 = Force.From(1, ForceUnit.ShortTonForce); - AssertEx.EqualTolerance(1, quantity13.ShortTonsForce, ShortTonsForceTolerance); + Assert.Equal(1, quantity13.ShortTonsForce); Assert.Equal(ForceUnit.ShortTonForce, quantity13.Unit); var quantity14 = Force.From(1, ForceUnit.TonneForce); - AssertEx.EqualTolerance(1, quantity14.TonnesForce, TonnesForceTolerance); + Assert.Equal(1, quantity14.TonnesForce); Assert.Equal(ForceUnit.TonneForce, quantity14.Unit); } @@ -407,433 +425,102 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 daN", ForceUnit.Decanewton, 4.2)] + [InlineData("en-US", "4.2 dyn", ForceUnit.Dyn, 4.2)] + [InlineData("en-US", "4.2 kgf", ForceUnit.KilogramForce, 4.2)] + [InlineData("en-US", "4.2 kN", ForceUnit.Kilonewton, 4.2)] + [InlineData("en-US", "4.2 kp", ForceUnit.KiloPond, 4.2)] + [InlineData("en-US", "4.2 kipf", ForceUnit.KilopoundForce, 4.2)] + [InlineData("en-US", "4.2 kip", ForceUnit.KilopoundForce, 4.2)] + [InlineData("en-US", "4.2 k", ForceUnit.KilopoundForce, 4.2)] + [InlineData("en-US", "4.2 MN", ForceUnit.Meganewton, 4.2)] + [InlineData("en-US", "4.2 µN", ForceUnit.Micronewton, 4.2)] + [InlineData("en-US", "4.2 mN", ForceUnit.Millinewton, 4.2)] + [InlineData("en-US", "4.2 N", ForceUnit.Newton, 4.2)] + [InlineData("en-US", "4.2 ozf", ForceUnit.OunceForce, 4.2)] + [InlineData("en-US", "4.2 pdl", ForceUnit.Poundal, 4.2)] + [InlineData("en-US", "4.2 lbf", ForceUnit.PoundForce, 4.2)] + [InlineData("en-US", "4.2 tf (short)", ForceUnit.ShortTonForce, 4.2)] + [InlineData("en-US", "4.2 t (US)f", ForceUnit.ShortTonForce, 4.2)] + [InlineData("en-US", "4.2 short tons-force", ForceUnit.ShortTonForce, 4.2)] + [InlineData("en-US", "4.2 tf", ForceUnit.TonneForce, 4.2)] + [InlineData("en-US", "4.2 Ton", ForceUnit.TonneForce, 4.2)] + [InlineData("ru-RU", "4,2 даН", ForceUnit.Decanewton, 4.2)] + [InlineData("ru-RU", "4,2 дин", ForceUnit.Dyn, 4.2)] + [InlineData("ru-RU", "4,2 кН", ForceUnit.Kilonewton, 4.2)] + [InlineData("ru-RU", "4,2 кипф", ForceUnit.KilopoundForce, 4.2)] + [InlineData("ru-RU", "4,2 койка", ForceUnit.KilopoundForce, 4.2)] + [InlineData("ru-RU", "4,2 К", ForceUnit.KilopoundForce, 4.2)] + [InlineData("ru-RU", "4,2 МН", ForceUnit.Meganewton, 4.2)] + [InlineData("ru-RU", "4,2 мкН", ForceUnit.Micronewton, 4.2)] + [InlineData("ru-RU", "4,2 мН", ForceUnit.Millinewton, 4.2)] + [InlineData("ru-RU", "4,2 Н", ForceUnit.Newton, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = Force.Parse("1 daN", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Decanewtons, DecanewtonsTolerance); - Assert.Equal(ForceUnit.Decanewton, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 даН", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Decanewtons, DecanewtonsTolerance); - Assert.Equal(ForceUnit.Decanewton, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 dyn", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Dyne, DyneTolerance); - Assert.Equal(ForceUnit.Dyn, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 дин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Dyne, DyneTolerance); - Assert.Equal(ForceUnit.Dyn, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 kgf", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsForce, KilogramsForceTolerance); - Assert.Equal(ForceUnit.KilogramForce, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 кгс", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilogramsForce, KilogramsForceTolerance); - Assert.Equal(ForceUnit.KilogramForce, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 kN", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilonewtons, KilonewtonsTolerance); - Assert.Equal(ForceUnit.Kilonewton, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 кН", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Kilonewtons, KilonewtonsTolerance); - Assert.Equal(ForceUnit.Kilonewton, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 kp", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KiloPonds, KiloPondsTolerance); - Assert.Equal(ForceUnit.KiloPond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 кгс", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KiloPonds, KiloPondsTolerance); - Assert.Equal(ForceUnit.KiloPond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 kipf", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForce, KilopoundsForceTolerance); - Assert.Equal(ForceUnit.KilopoundForce, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 kip", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForce, KilopoundsForceTolerance); - Assert.Equal(ForceUnit.KilopoundForce, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 k", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForce, KilopoundsForceTolerance); - Assert.Equal(ForceUnit.KilopoundForce, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 кипф", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForce, KilopoundsForceTolerance); - Assert.Equal(ForceUnit.KilopoundForce, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 койка", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForce, KilopoundsForceTolerance); - Assert.Equal(ForceUnit.KilopoundForce, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 К", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForce, KilopoundsForceTolerance); - Assert.Equal(ForceUnit.KilopoundForce, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 MN", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Meganewtons, MeganewtonsTolerance); - Assert.Equal(ForceUnit.Meganewton, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 МН", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Meganewtons, MeganewtonsTolerance); - Assert.Equal(ForceUnit.Meganewton, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 µN", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Micronewtons, MicronewtonsTolerance); - Assert.Equal(ForceUnit.Micronewton, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 мкН", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Micronewtons, MicronewtonsTolerance); - Assert.Equal(ForceUnit.Micronewton, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 mN", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millinewtons, MillinewtonsTolerance); - Assert.Equal(ForceUnit.Millinewton, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 мН", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Millinewtons, MillinewtonsTolerance); - Assert.Equal(ForceUnit.Millinewton, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 N", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Newtons, NewtonsTolerance); - Assert.Equal(ForceUnit.Newton, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 Н", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Newtons, NewtonsTolerance); - Assert.Equal(ForceUnit.Newton, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 ozf", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.OunceForce, OunceForceTolerance); - Assert.Equal(ForceUnit.OunceForce, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 pdl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Poundals, PoundalsTolerance); - Assert.Equal(ForceUnit.Poundal, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 паундаль", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Poundals, PoundalsTolerance); - Assert.Equal(ForceUnit.Poundal, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 lbf", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsForce, PoundsForceTolerance); - Assert.Equal(ForceUnit.PoundForce, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 фунт-сила", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.PoundsForce, PoundsForceTolerance); - Assert.Equal(ForceUnit.PoundForce, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 tf (short)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ShortTonsForce, ShortTonsForceTolerance); - Assert.Equal(ForceUnit.ShortTonForce, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 t (US)f", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ShortTonsForce, ShortTonsForceTolerance); - Assert.Equal(ForceUnit.ShortTonForce, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 short tons-force", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ShortTonsForce, ShortTonsForceTolerance); - Assert.Equal(ForceUnit.ShortTonForce, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 tf", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonnesForce, TonnesForceTolerance); - Assert.Equal(ForceUnit.TonneForce, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 Ton", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonnesForce, TonnesForceTolerance); - Assert.Equal(ForceUnit.TonneForce, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Force.Parse("1 тс", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.TonnesForce, TonnesForceTolerance); - Assert.Equal(ForceUnit.TonneForce, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Force.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("ru-RU", "1 кгс")] // [KilogramForce, KiloPond] + public void ParseWithAmbiguousAbbreviation(string culture, string quantityString) { - { - Assert.True(Force.TryParse("1 daN", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Decanewtons, DecanewtonsTolerance); - Assert.Equal(ForceUnit.Decanewton, parsed.Unit); - } - - { - Assert.True(Force.TryParse("1 даН", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Decanewtons, DecanewtonsTolerance); - Assert.Equal(ForceUnit.Decanewton, parsed.Unit); - } - - { - Assert.True(Force.TryParse("1 dyn", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Dyne, DyneTolerance); - Assert.Equal(ForceUnit.Dyn, parsed.Unit); - } - - { - Assert.True(Force.TryParse("1 дин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Dyne, DyneTolerance); - Assert.Equal(ForceUnit.Dyn, parsed.Unit); - } - - { - Assert.True(Force.TryParse("1 kgf", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsForce, KilogramsForceTolerance); - Assert.Equal(ForceUnit.KilogramForce, parsed.Unit); - } - - { - Assert.True(Force.TryParse("1 kN", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilonewtons, KilonewtonsTolerance); - Assert.Equal(ForceUnit.Kilonewton, parsed.Unit); - } - - { - Assert.True(Force.TryParse("1 кН", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilonewtons, KilonewtonsTolerance); - Assert.Equal(ForceUnit.Kilonewton, parsed.Unit); - } - - { - Assert.True(Force.TryParse("1 kp", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KiloPonds, KiloPondsTolerance); - Assert.Equal(ForceUnit.KiloPond, parsed.Unit); - } - - { - Assert.True(Force.TryParse("1 kipf", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForce, KilopoundsForceTolerance); - Assert.Equal(ForceUnit.KilopoundForce, parsed.Unit); - } - - { - Assert.True(Force.TryParse("1 kip", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForce, KilopoundsForceTolerance); - Assert.Equal(ForceUnit.KilopoundForce, parsed.Unit); - } - - { - Assert.True(Force.TryParse("1 k", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForce, KilopoundsForceTolerance); - Assert.Equal(ForceUnit.KilopoundForce, parsed.Unit); - } - - { - Assert.True(Force.TryParse("1 кипф", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForce, KilopoundsForceTolerance); - Assert.Equal(ForceUnit.KilopoundForce, parsed.Unit); - } - - { - Assert.True(Force.TryParse("1 койка", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForce, KilopoundsForceTolerance); - Assert.Equal(ForceUnit.KilopoundForce, parsed.Unit); - } - - { - Assert.True(Force.TryParse("1 К", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForce, KilopoundsForceTolerance); - Assert.Equal(ForceUnit.KilopoundForce, parsed.Unit); - } - - { - Assert.True(Force.TryParse("1 µN", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Micronewtons, MicronewtonsTolerance); - Assert.Equal(ForceUnit.Micronewton, parsed.Unit); - } - - { - Assert.True(Force.TryParse("1 мкН", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Micronewtons, MicronewtonsTolerance); - Assert.Equal(ForceUnit.Micronewton, parsed.Unit); - } - - { - Assert.True(Force.TryParse("1 N", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Newtons, NewtonsTolerance); - Assert.Equal(ForceUnit.Newton, parsed.Unit); - } - - { - Assert.True(Force.TryParse("1 Н", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Newtons, NewtonsTolerance); - Assert.Equal(ForceUnit.Newton, parsed.Unit); - } - - { - Assert.True(Force.TryParse("1 ozf", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.OunceForce, OunceForceTolerance); - Assert.Equal(ForceUnit.OunceForce, parsed.Unit); - } - - { - Assert.True(Force.TryParse("1 pdl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Poundals, PoundalsTolerance); - Assert.Equal(ForceUnit.Poundal, parsed.Unit); - } - - { - Assert.True(Force.TryParse("1 паундаль", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Poundals, PoundalsTolerance); - Assert.Equal(ForceUnit.Poundal, parsed.Unit); - } - - { - Assert.True(Force.TryParse("1 lbf", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsForce, PoundsForceTolerance); - Assert.Equal(ForceUnit.PoundForce, parsed.Unit); - } - - { - Assert.True(Force.TryParse("1 фунт-сила", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsForce, PoundsForceTolerance); - Assert.Equal(ForceUnit.PoundForce, parsed.Unit); - } - - { - Assert.True(Force.TryParse("1 tf (short)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ShortTonsForce, ShortTonsForceTolerance); - Assert.Equal(ForceUnit.ShortTonForce, parsed.Unit); - } - - { - Assert.True(Force.TryParse("1 t (US)f", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ShortTonsForce, ShortTonsForceTolerance); - Assert.Equal(ForceUnit.ShortTonForce, parsed.Unit); - } - - { - Assert.True(Force.TryParse("1 short tons-force", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ShortTonsForce, ShortTonsForceTolerance); - Assert.Equal(ForceUnit.ShortTonForce, parsed.Unit); - } - - { - Assert.True(Force.TryParse("1 tf", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonnesForce, TonnesForceTolerance); - Assert.Equal(ForceUnit.TonneForce, parsed.Unit); - } - - { - Assert.True(Force.TryParse("1 Ton", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonnesForce, TonnesForceTolerance); - Assert.Equal(ForceUnit.TonneForce, parsed.Unit); - } + Assert.Throws(() => Force.Parse(quantityString, CultureInfo.GetCultureInfo(culture))); + } - { - Assert.True(Force.TryParse("1 тс", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonnesForce, TonnesForceTolerance); - Assert.Equal(ForceUnit.TonneForce, parsed.Unit); - } + [Theory] + [InlineData("en-US", "4.2 daN", ForceUnit.Decanewton, 4.2)] + [InlineData("en-US", "4.2 dyn", ForceUnit.Dyn, 4.2)] + [InlineData("en-US", "4.2 kgf", ForceUnit.KilogramForce, 4.2)] + [InlineData("en-US", "4.2 kN", ForceUnit.Kilonewton, 4.2)] + [InlineData("en-US", "4.2 kp", ForceUnit.KiloPond, 4.2)] + [InlineData("en-US", "4.2 kipf", ForceUnit.KilopoundForce, 4.2)] + [InlineData("en-US", "4.2 kip", ForceUnit.KilopoundForce, 4.2)] + [InlineData("en-US", "4.2 k", ForceUnit.KilopoundForce, 4.2)] + [InlineData("en-US", "4.2 MN", ForceUnit.Meganewton, 4.2)] + [InlineData("en-US", "4.2 µN", ForceUnit.Micronewton, 4.2)] + [InlineData("en-US", "4.2 mN", ForceUnit.Millinewton, 4.2)] + [InlineData("en-US", "4.2 N", ForceUnit.Newton, 4.2)] + [InlineData("en-US", "4.2 ozf", ForceUnit.OunceForce, 4.2)] + [InlineData("en-US", "4.2 pdl", ForceUnit.Poundal, 4.2)] + [InlineData("en-US", "4.2 lbf", ForceUnit.PoundForce, 4.2)] + [InlineData("en-US", "4.2 tf (short)", ForceUnit.ShortTonForce, 4.2)] + [InlineData("en-US", "4.2 t (US)f", ForceUnit.ShortTonForce, 4.2)] + [InlineData("en-US", "4.2 short tons-force", ForceUnit.ShortTonForce, 4.2)] + [InlineData("en-US", "4.2 tf", ForceUnit.TonneForce, 4.2)] + [InlineData("en-US", "4.2 Ton", ForceUnit.TonneForce, 4.2)] + [InlineData("ru-RU", "4,2 даН", ForceUnit.Decanewton, 4.2)] + [InlineData("ru-RU", "4,2 дин", ForceUnit.Dyn, 4.2)] + [InlineData("ru-RU", "4,2 кН", ForceUnit.Kilonewton, 4.2)] + [InlineData("ru-RU", "4,2 кипф", ForceUnit.KilopoundForce, 4.2)] + [InlineData("ru-RU", "4,2 койка", ForceUnit.KilopoundForce, 4.2)] + [InlineData("ru-RU", "4,2 К", ForceUnit.KilopoundForce, 4.2)] + [InlineData("ru-RU", "4,2 МН", ForceUnit.Meganewton, 4.2)] + [InlineData("ru-RU", "4,2 мкН", ForceUnit.Micronewton, 4.2)] + [InlineData("ru-RU", "4,2 мН", ForceUnit.Millinewton, 4.2)] + [InlineData("ru-RU", "4,2 Н", ForceUnit.Newton, 4.2)] + [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, decimal expectedValue) + { + using var _ = new CultureScope(culture); + Assert.True(Force.TryParse(quantityString, out Force parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); + } + [Theory] + [InlineData("ru-RU", "1 кгс")] // [KilogramForce, KiloPond] + public void TryParseWithAmbiguousAbbreviation(string culture, string quantityString) + { + Assert.False(Force.TryParse(quantityString, CultureInfo.GetCultureInfo(culture), out _)); } [Theory] @@ -1128,6 +815,54 @@ public void TryParseUnitWithAmbiguousAbbreviation(string culture, string abbrevi Assert.False(Force.TryParseUnit(abbreviation, CultureInfo.GetCultureInfo(culture), out _)); } + [Theory] + [InlineData("en-US", ForceUnit.Decanewton, "daN")] + [InlineData("en-US", ForceUnit.Dyn, "dyn")] + [InlineData("en-US", ForceUnit.KilogramForce, "kgf")] + [InlineData("en-US", ForceUnit.Kilonewton, "kN")] + [InlineData("en-US", ForceUnit.KiloPond, "kp")] + [InlineData("en-US", ForceUnit.KilopoundForce, "kipf")] + [InlineData("en-US", ForceUnit.Meganewton, "MN")] + [InlineData("en-US", ForceUnit.Micronewton, "µN")] + [InlineData("en-US", ForceUnit.Millinewton, "mN")] + [InlineData("en-US", ForceUnit.Newton, "N")] + [InlineData("en-US", ForceUnit.OunceForce, "ozf")] + [InlineData("en-US", ForceUnit.Poundal, "pdl")] + [InlineData("en-US", ForceUnit.PoundForce, "lbf")] + [InlineData("en-US", ForceUnit.ShortTonForce, "tf (short)")] + [InlineData("en-US", ForceUnit.TonneForce, "tf")] + [InlineData("ru-RU", ForceUnit.Decanewton, "даН")] + [InlineData("ru-RU", ForceUnit.Dyn, "дин")] + [InlineData("ru-RU", ForceUnit.KilogramForce, "кгс")] + [InlineData("ru-RU", ForceUnit.Kilonewton, "кН")] + [InlineData("ru-RU", ForceUnit.KiloPond, "кгс")] + [InlineData("ru-RU", ForceUnit.KilopoundForce, "кипф")] + [InlineData("ru-RU", ForceUnit.Meganewton, "МН")] + [InlineData("ru-RU", ForceUnit.Micronewton, "мкН")] + [InlineData("ru-RU", ForceUnit.Millinewton, "мН")] + [InlineData("ru-RU", ForceUnit.Newton, "Н")] + [InlineData("ru-RU", ForceUnit.Poundal, "паундаль")] + [InlineData("ru-RU", ForceUnit.PoundForce, "фунт-сила")] + [InlineData("ru-RU", ForceUnit.TonneForce, "тс")] + public void GetAbbreviationForCulture(string culture, ForceUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Force.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Force.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Force.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ForceUnit unit) @@ -1158,6 +893,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); }); } @@ -1181,46 +917,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] @@ -1266,8 +1004,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); @@ -1304,23 +1040,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = Force.FromNewtons(1); - Assert.True(v.Equals(Force.FromNewtons(1), NewtonsTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Force.Zero, NewtonsTolerance, ComparisonType.Relative)); - Assert.True(Force.FromNewtons(100).Equals(Force.FromNewtons(120), 0.3, ComparisonType.Relative)); - Assert.False(Force.FromNewtons(100).Equals(Force.FromNewtons(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = Force.FromNewtons(1); - Assert.Throws(() => v.Equals(Force.FromNewtons(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1335,6 +1054,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(newton.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = Force.FromNewtons(1); + var negativeTolerance = Force.FromNewtons(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1351,6 +1096,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() { @@ -1437,158 +1194,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Force.FromNewtons(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Force.FromNewtons(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Force.FromNewtons(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Force.FromNewtons(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Force.FromNewtons(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Force.FromNewtons(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Force.FromNewtons(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Force.FromNewtons(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Force.FromNewtons(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Force.FromNewtons(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Force.FromNewtons(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Force.FromNewtons(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Force.FromNewtons(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Force.FromNewtons(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Force.FromNewtons(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Force.FromNewtons(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Force))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Force.FromNewtons(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ForceUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Force.FromNewtons(1.0); - Assert.Equal(Force.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Force.FromNewtons(1.0); - Assert.Equal(Force.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Force.FromNewtons(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Force.FromNewtons(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Force.FromNewtons(1.0); - Assert.Equal(new {Force.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 5ef7abcd6c..4ca54ba155 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/FrequencyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/FrequencyTestsBase.g.cs @@ -140,7 +140,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Frequency(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -153,15 +153,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Frequency_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + FrequencyUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Frequency(1, FrequencyUnit.Hertz); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Frequency.Zero, quantityInfo.Zero); Assert.Equal("Frequency", quantityInfo.Name); + Assert.Equal(Frequency.Zero, quantityInfo.Zero); + Assert.Equal(Frequency.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Frequency.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void FrequencyInfo_CreateWithCustomUnitInfos() + { + FrequencyUnit[] expectedUnits = [FrequencyUnit.Hertz]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -186,51 +204,51 @@ public void HertzToFrequencyUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Frequency.From(1, FrequencyUnit.BeatPerMinute); - AssertEx.EqualTolerance(1, quantity00.BeatsPerMinute, BeatsPerMinuteTolerance); + Assert.Equal(1, quantity00.BeatsPerMinute); Assert.Equal(FrequencyUnit.BeatPerMinute, quantity00.Unit); var quantity01 = Frequency.From(1, FrequencyUnit.CyclePerHour); - AssertEx.EqualTolerance(1, quantity01.CyclesPerHour, CyclesPerHourTolerance); + Assert.Equal(1, quantity01.CyclesPerHour); Assert.Equal(FrequencyUnit.CyclePerHour, quantity01.Unit); var quantity02 = Frequency.From(1, FrequencyUnit.CyclePerMinute); - AssertEx.EqualTolerance(1, quantity02.CyclesPerMinute, CyclesPerMinuteTolerance); + Assert.Equal(1, quantity02.CyclesPerMinute); Assert.Equal(FrequencyUnit.CyclePerMinute, quantity02.Unit); var quantity03 = Frequency.From(1, FrequencyUnit.Gigahertz); - AssertEx.EqualTolerance(1, quantity03.Gigahertz, GigahertzTolerance); + Assert.Equal(1, quantity03.Gigahertz); Assert.Equal(FrequencyUnit.Gigahertz, quantity03.Unit); var quantity04 = Frequency.From(1, FrequencyUnit.Hertz); - AssertEx.EqualTolerance(1, quantity04.Hertz, HertzTolerance); + Assert.Equal(1, quantity04.Hertz); Assert.Equal(FrequencyUnit.Hertz, quantity04.Unit); var quantity05 = Frequency.From(1, FrequencyUnit.Kilohertz); - AssertEx.EqualTolerance(1, quantity05.Kilohertz, KilohertzTolerance); + Assert.Equal(1, quantity05.Kilohertz); Assert.Equal(FrequencyUnit.Kilohertz, quantity05.Unit); var quantity06 = Frequency.From(1, FrequencyUnit.Megahertz); - AssertEx.EqualTolerance(1, quantity06.Megahertz, MegahertzTolerance); + Assert.Equal(1, quantity06.Megahertz); Assert.Equal(FrequencyUnit.Megahertz, quantity06.Unit); var quantity07 = Frequency.From(1, FrequencyUnit.Microhertz); - AssertEx.EqualTolerance(1, quantity07.Microhertz, MicrohertzTolerance); + Assert.Equal(1, quantity07.Microhertz); Assert.Equal(FrequencyUnit.Microhertz, quantity07.Unit); var quantity08 = Frequency.From(1, FrequencyUnit.Millihertz); - AssertEx.EqualTolerance(1, quantity08.Millihertz, MillihertzTolerance); + Assert.Equal(1, quantity08.Millihertz); Assert.Equal(FrequencyUnit.Millihertz, quantity08.Unit); var quantity09 = Frequency.From(1, FrequencyUnit.PerSecond); - AssertEx.EqualTolerance(1, quantity09.PerSecond, PerSecondTolerance); + Assert.Equal(1, quantity09.PerSecond); Assert.Equal(FrequencyUnit.PerSecond, quantity09.Unit); var quantity10 = Frequency.From(1, FrequencyUnit.RadianPerSecond); - AssertEx.EqualTolerance(1, quantity10.RadiansPerSecond, RadiansPerSecondTolerance); + Assert.Equal(1, quantity10.RadiansPerSecond); Assert.Equal(FrequencyUnit.RadianPerSecond, quantity10.Unit); var quantity11 = Frequency.From(1, FrequencyUnit.Terahertz); - AssertEx.EqualTolerance(1, quantity11.Terahertz, TerahertzTolerance); + Assert.Equal(1, quantity11.Terahertz); Assert.Equal(FrequencyUnit.Terahertz, quantity11.Unit); } @@ -377,263 +395,64 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 bpm", FrequencyUnit.BeatPerMinute, 4.2)] + [InlineData("en-US", "4.2 cph", FrequencyUnit.CyclePerHour, 4.2)] + [InlineData("en-US", "4.2 cpm", FrequencyUnit.CyclePerMinute, 4.2)] + [InlineData("en-US", "4.2 GHz", FrequencyUnit.Gigahertz, 4.2)] + [InlineData("en-US", "4.2 Hz", FrequencyUnit.Hertz, 4.2)] + [InlineData("en-US", "4.2 kHz", FrequencyUnit.Kilohertz, 4.2)] + [InlineData("en-US", "4.2 MHz", FrequencyUnit.Megahertz, 4.2)] + [InlineData("en-US", "4.2 µHz", FrequencyUnit.Microhertz, 4.2)] + [InlineData("en-US", "4.2 mHz", FrequencyUnit.Millihertz, 4.2)] + [InlineData("en-US", "4.2 s⁻¹", FrequencyUnit.PerSecond, 4.2)] + [InlineData("en-US", "4.2 rad/s", FrequencyUnit.RadianPerSecond, 4.2)] + [InlineData("en-US", "4.2 THz", FrequencyUnit.Terahertz, 4.2)] + [InlineData("ru-RU", "4,2 ГГц", FrequencyUnit.Gigahertz, 4.2)] + [InlineData("ru-RU", "4,2 Гц", FrequencyUnit.Hertz, 4.2)] + [InlineData("ru-RU", "4,2 кГц", FrequencyUnit.Kilohertz, 4.2)] + [InlineData("ru-RU", "4,2 МГц", FrequencyUnit.Megahertz, 4.2)] + [InlineData("ru-RU", "4,2 мкГц", FrequencyUnit.Microhertz, 4.2)] + [InlineData("ru-RU", "4,2 мГц", FrequencyUnit.Millihertz, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = Frequency.Parse("1 bpm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.BeatsPerMinute, BeatsPerMinuteTolerance); - Assert.Equal(FrequencyUnit.BeatPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Frequency.Parse("1 cph", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CyclesPerHour, CyclesPerHourTolerance); - Assert.Equal(FrequencyUnit.CyclePerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Frequency.Parse("1 cpm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CyclesPerMinute, CyclesPerMinuteTolerance); - Assert.Equal(FrequencyUnit.CyclePerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Frequency.Parse("1 GHz", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Gigahertz, GigahertzTolerance); - Assert.Equal(FrequencyUnit.Gigahertz, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Frequency.Parse("1 ГГц", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Gigahertz, GigahertzTolerance); - Assert.Equal(FrequencyUnit.Gigahertz, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Frequency.Parse("1 Hz", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Hertz, HertzTolerance); - Assert.Equal(FrequencyUnit.Hertz, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Frequency.Parse("1 Гц", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Hertz, HertzTolerance); - Assert.Equal(FrequencyUnit.Hertz, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Frequency.Parse("1 kHz", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilohertz, KilohertzTolerance); - Assert.Equal(FrequencyUnit.Kilohertz, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Frequency.Parse("1 кГц", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Kilohertz, KilohertzTolerance); - Assert.Equal(FrequencyUnit.Kilohertz, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Frequency.Parse("1 MHz", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megahertz, MegahertzTolerance); - Assert.Equal(FrequencyUnit.Megahertz, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Frequency.Parse("1 МГц", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Megahertz, MegahertzTolerance); - Assert.Equal(FrequencyUnit.Megahertz, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Frequency.Parse("1 µHz", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microhertz, MicrohertzTolerance); - Assert.Equal(FrequencyUnit.Microhertz, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Frequency.Parse("1 мкГц", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Microhertz, MicrohertzTolerance); - Assert.Equal(FrequencyUnit.Microhertz, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Frequency.Parse("1 mHz", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millihertz, MillihertzTolerance); - Assert.Equal(FrequencyUnit.Millihertz, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Frequency.Parse("1 мГц", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Millihertz, MillihertzTolerance); - Assert.Equal(FrequencyUnit.Millihertz, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Frequency.Parse("1 s⁻¹", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PerSecond, PerSecondTolerance); - Assert.Equal(FrequencyUnit.PerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Frequency.Parse("1 с⁻¹", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.PerSecond, PerSecondTolerance); - Assert.Equal(FrequencyUnit.PerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Frequency.Parse("1 rad/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.RadiansPerSecond, RadiansPerSecondTolerance); - Assert.Equal(FrequencyUnit.RadianPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Frequency.Parse("1 рад/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.RadiansPerSecond, RadiansPerSecondTolerance); - Assert.Equal(FrequencyUnit.RadianPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Frequency.Parse("1 THz", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Terahertz, TerahertzTolerance); - Assert.Equal(FrequencyUnit.Terahertz, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Frequency.Parse("1 ТГц", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Terahertz, TerahertzTolerance); - Assert.Equal(FrequencyUnit.Terahertz, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Frequency.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 bpm", FrequencyUnit.BeatPerMinute, 4.2)] + [InlineData("en-US", "4.2 cph", FrequencyUnit.CyclePerHour, 4.2)] + [InlineData("en-US", "4.2 cpm", FrequencyUnit.CyclePerMinute, 4.2)] + [InlineData("en-US", "4.2 GHz", FrequencyUnit.Gigahertz, 4.2)] + [InlineData("en-US", "4.2 Hz", FrequencyUnit.Hertz, 4.2)] + [InlineData("en-US", "4.2 kHz", FrequencyUnit.Kilohertz, 4.2)] + [InlineData("en-US", "4.2 MHz", FrequencyUnit.Megahertz, 4.2)] + [InlineData("en-US", "4.2 µHz", FrequencyUnit.Microhertz, 4.2)] + [InlineData("en-US", "4.2 mHz", FrequencyUnit.Millihertz, 4.2)] + [InlineData("en-US", "4.2 s⁻¹", FrequencyUnit.PerSecond, 4.2)] + [InlineData("en-US", "4.2 rad/s", FrequencyUnit.RadianPerSecond, 4.2)] + [InlineData("en-US", "4.2 THz", FrequencyUnit.Terahertz, 4.2)] + [InlineData("ru-RU", "4,2 ГГц", FrequencyUnit.Gigahertz, 4.2)] + [InlineData("ru-RU", "4,2 Гц", FrequencyUnit.Hertz, 4.2)] + [InlineData("ru-RU", "4,2 кГц", FrequencyUnit.Kilohertz, 4.2)] + [InlineData("ru-RU", "4,2 МГц", FrequencyUnit.Megahertz, 4.2)] + [InlineData("ru-RU", "4,2 мкГц", FrequencyUnit.Microhertz, 4.2)] + [InlineData("ru-RU", "4,2 мГц", FrequencyUnit.Millihertz, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(Frequency.TryParse("1 bpm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BeatsPerMinute, BeatsPerMinuteTolerance); - Assert.Equal(FrequencyUnit.BeatPerMinute, parsed.Unit); - } - - { - Assert.True(Frequency.TryParse("1 cph", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CyclesPerHour, CyclesPerHourTolerance); - Assert.Equal(FrequencyUnit.CyclePerHour, parsed.Unit); - } - - { - Assert.True(Frequency.TryParse("1 cpm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CyclesPerMinute, CyclesPerMinuteTolerance); - Assert.Equal(FrequencyUnit.CyclePerMinute, parsed.Unit); - } - - { - Assert.True(Frequency.TryParse("1 GHz", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gigahertz, GigahertzTolerance); - Assert.Equal(FrequencyUnit.Gigahertz, parsed.Unit); - } - - { - Assert.True(Frequency.TryParse("1 ГГц", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gigahertz, GigahertzTolerance); - Assert.Equal(FrequencyUnit.Gigahertz, parsed.Unit); - } - - { - Assert.True(Frequency.TryParse("1 Hz", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Hertz, HertzTolerance); - Assert.Equal(FrequencyUnit.Hertz, parsed.Unit); - } - - { - Assert.True(Frequency.TryParse("1 Гц", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Hertz, HertzTolerance); - Assert.Equal(FrequencyUnit.Hertz, parsed.Unit); - } - - { - Assert.True(Frequency.TryParse("1 kHz", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilohertz, KilohertzTolerance); - Assert.Equal(FrequencyUnit.Kilohertz, parsed.Unit); - } - - { - Assert.True(Frequency.TryParse("1 кГц", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilohertz, KilohertzTolerance); - Assert.Equal(FrequencyUnit.Kilohertz, parsed.Unit); - } - - { - Assert.True(Frequency.TryParse("1 µHz", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microhertz, MicrohertzTolerance); - Assert.Equal(FrequencyUnit.Microhertz, parsed.Unit); - } - - { - Assert.True(Frequency.TryParse("1 мкГц", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microhertz, MicrohertzTolerance); - Assert.Equal(FrequencyUnit.Microhertz, parsed.Unit); - } - - { - Assert.True(Frequency.TryParse("1 s⁻¹", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PerSecond, PerSecondTolerance); - Assert.Equal(FrequencyUnit.PerSecond, parsed.Unit); - } - - { - Assert.True(Frequency.TryParse("1 с⁻¹", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PerSecond, PerSecondTolerance); - Assert.Equal(FrequencyUnit.PerSecond, parsed.Unit); - } - - { - Assert.True(Frequency.TryParse("1 rad/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.RadiansPerSecond, RadiansPerSecondTolerance); - Assert.Equal(FrequencyUnit.RadianPerSecond, parsed.Unit); - } - - { - Assert.True(Frequency.TryParse("1 рад/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.RadiansPerSecond, RadiansPerSecondTolerance); - Assert.Equal(FrequencyUnit.RadianPerSecond, parsed.Unit); - } - - { - Assert.True(Frequency.TryParse("1 THz", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Terahertz, TerahertzTolerance); - Assert.Equal(FrequencyUnit.Terahertz, parsed.Unit); - } - - { - Assert.True(Frequency.TryParse("1 ТГц", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Terahertz, TerahertzTolerance); - Assert.Equal(FrequencyUnit.Terahertz, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Frequency.TryParse(quantityString, out Frequency parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -834,6 +653,47 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Freque Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", FrequencyUnit.BeatPerMinute, "bpm")] + [InlineData("en-US", FrequencyUnit.CyclePerHour, "cph")] + [InlineData("en-US", FrequencyUnit.CyclePerMinute, "cpm")] + [InlineData("en-US", FrequencyUnit.Gigahertz, "GHz")] + [InlineData("en-US", FrequencyUnit.Hertz, "Hz")] + [InlineData("en-US", FrequencyUnit.Kilohertz, "kHz")] + [InlineData("en-US", FrequencyUnit.Megahertz, "MHz")] + [InlineData("en-US", FrequencyUnit.Microhertz, "µHz")] + [InlineData("en-US", FrequencyUnit.Millihertz, "mHz")] + [InlineData("en-US", FrequencyUnit.PerSecond, "s⁻¹")] + [InlineData("en-US", FrequencyUnit.RadianPerSecond, "rad/s")] + [InlineData("en-US", FrequencyUnit.Terahertz, "THz")] + [InlineData("ru-RU", FrequencyUnit.Gigahertz, "ГГц")] + [InlineData("ru-RU", FrequencyUnit.Hertz, "Гц")] + [InlineData("ru-RU", FrequencyUnit.Kilohertz, "кГц")] + [InlineData("ru-RU", FrequencyUnit.Megahertz, "МГц")] + [InlineData("ru-RU", FrequencyUnit.Microhertz, "мкГц")] + [InlineData("ru-RU", FrequencyUnit.Millihertz, "мГц")] + [InlineData("ru-RU", FrequencyUnit.PerSecond, "с⁻¹")] + [InlineData("ru-RU", FrequencyUnit.RadianPerSecond, "рад/с")] + [InlineData("ru-RU", FrequencyUnit.Terahertz, "ТГц")] + public void GetAbbreviationForCulture(string culture, FrequencyUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Frequency.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Frequency.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Frequency.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(FrequencyUnit unit) @@ -864,6 +724,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); }); } @@ -887,43 +748,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] @@ -969,8 +832,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); @@ -1007,23 +868,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = Frequency.FromHertz(1); - Assert.True(v.Equals(Frequency.FromHertz(1), HertzTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Frequency.Zero, HertzTolerance, ComparisonType.Relative)); - Assert.True(Frequency.FromHertz(100).Equals(Frequency.FromHertz(120), 0.3, ComparisonType.Relative)); - Assert.False(Frequency.FromHertz(100).Equals(Frequency.FromHertz(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = Frequency.FromHertz(1); - Assert.Throws(() => v.Equals(Frequency.FromHertz(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1038,6 +882,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(hertz.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = Frequency.FromHertz(1); + var negativeTolerance = Frequency.FromHertz(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1054,6 +924,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() { @@ -1134,158 +1016,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Frequency.FromHertz(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Frequency.FromHertz(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Frequency.FromHertz(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Frequency.FromHertz(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Frequency.FromHertz(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Frequency.FromHertz(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Frequency.FromHertz(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Frequency.FromHertz(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Frequency.FromHertz(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Frequency.FromHertz(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Frequency.FromHertz(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Frequency.FromHertz(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Frequency.FromHertz(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Frequency.FromHertz(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Frequency.FromHertz(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Frequency.FromHertz(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Frequency))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Frequency.FromHertz(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(FrequencyUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Frequency.FromHertz(1.0); - Assert.Equal(Frequency.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Frequency.FromHertz(1.0); - Assert.Equal(Frequency.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Frequency.FromHertz(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Frequency.FromHertz(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Frequency.FromHertz(1.0); - Assert.Equal(new {Frequency.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 f9baaa1571..797d3fa19a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/FuelEfficiencyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/FuelEfficiencyTestsBase.g.cs @@ -108,7 +108,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new FuelEfficiency(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -121,15 +121,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void FuelEfficiency_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + FuelEfficiencyUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new FuelEfficiency(1, FuelEfficiencyUnit.KilometerPerLiter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(FuelEfficiency.Zero, quantityInfo.Zero); Assert.Equal("FuelEfficiency", quantityInfo.Name); + Assert.Equal(FuelEfficiency.Zero, quantityInfo.Zero); + Assert.Equal(FuelEfficiency.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(FuelEfficiency.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void FuelEfficiencyInfo_CreateWithCustomUnitInfos() + { + FuelEfficiencyUnit[] expectedUnits = [FuelEfficiencyUnit.KilometerPerLiter]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -146,19 +164,19 @@ public void KilometerPerLiterToFuelEfficiencyUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = FuelEfficiency.From(1, FuelEfficiencyUnit.KilometerPerLiter); - AssertEx.EqualTolerance(1, quantity00.KilometersPerLiter, KilometersPerLiterTolerance); + Assert.Equal(1, quantity00.KilometersPerLiter); Assert.Equal(FuelEfficiencyUnit.KilometerPerLiter, quantity00.Unit); var quantity01 = FuelEfficiency.From(1, FuelEfficiencyUnit.LiterPer100Kilometers); - AssertEx.EqualTolerance(1, quantity01.LitersPer100Kilometers, LitersPer100KilometersTolerance); + Assert.Equal(1, quantity01.LitersPer100Kilometers); Assert.Equal(FuelEfficiencyUnit.LiterPer100Kilometers, quantity01.Unit); var quantity02 = FuelEfficiency.From(1, FuelEfficiencyUnit.MilePerUkGallon); - AssertEx.EqualTolerance(1, quantity02.MilesPerUkGallon, MilesPerUkGallonTolerance); + Assert.Equal(1, quantity02.MilesPerUkGallon); Assert.Equal(FuelEfficiencyUnit.MilePerUkGallon, quantity02.Unit); var quantity03 = FuelEfficiency.From(1, FuelEfficiencyUnit.MilePerUsGallon); - AssertEx.EqualTolerance(1, quantity03.MilesPerUsGallon, MilesPerUsGallonTolerance); + Assert.Equal(1, quantity03.MilesPerUsGallon); Assert.Equal(FuelEfficiencyUnit.MilePerUsGallon, quantity03.Unit); } @@ -297,66 +315,30 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 km/l", FuelEfficiencyUnit.KilometerPerLiter, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = FuelEfficiency.Parse("1 km/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilometersPerLiter, KilometersPerLiterTolerance); - Assert.Equal(FuelEfficiencyUnit.KilometerPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FuelEfficiency.Parse("1 l/100km", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.LitersPer100Kilometers, LitersPer100KilometersTolerance); - Assert.Equal(FuelEfficiencyUnit.LiterPer100Kilometers, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FuelEfficiency.Parse("1 mpg (imp.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilesPerUkGallon, MilesPerUkGallonTolerance); - Assert.Equal(FuelEfficiencyUnit.MilePerUkGallon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = FuelEfficiency.Parse("1 mpg (U.S.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilesPerUsGallon, MilesPerUsGallonTolerance); - Assert.Equal(FuelEfficiencyUnit.MilePerUsGallon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = FuelEfficiency.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 km/l", FuelEfficiencyUnit.KilometerPerLiter, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(FuelEfficiency.TryParse("1 km/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilometersPerLiter, KilometersPerLiterTolerance); - Assert.Equal(FuelEfficiencyUnit.KilometerPerLiter, parsed.Unit); - } - - { - Assert.True(FuelEfficiency.TryParse("1 l/100km", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.LitersPer100Kilometers, LitersPer100KilometersTolerance); - Assert.Equal(FuelEfficiencyUnit.LiterPer100Kilometers, parsed.Unit); - } - - { - Assert.True(FuelEfficiency.TryParse("1 mpg (imp.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilesPerUkGallon, MilesPerUkGallonTolerance); - Assert.Equal(FuelEfficiencyUnit.MilePerUkGallon, parsed.Unit); - } - - { - Assert.True(FuelEfficiency.TryParse("1 mpg (U.S.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilesPerUsGallon, MilesPerUsGallonTolerance); - Assert.Equal(FuelEfficiencyUnit.MilePerUsGallon, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(FuelEfficiency.TryParse(quantityString, out FuelEfficiency parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -457,6 +439,30 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, FuelEf Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", FuelEfficiencyUnit.KilometerPerLiter, "km/l")] + [InlineData("en-US", FuelEfficiencyUnit.LiterPer100Kilometers, "l/100km")] + [InlineData("en-US", FuelEfficiencyUnit.MilePerUkGallon, "mpg (imp.)")] + [InlineData("en-US", FuelEfficiencyUnit.MilePerUsGallon, "mpg (U.S.)")] + public void GetAbbreviationForCulture(string culture, FuelEfficiencyUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = FuelEfficiency.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(FuelEfficiency.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = FuelEfficiency.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(FuelEfficiencyUnit unit) @@ -487,6 +493,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); }); } @@ -510,35 +517,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] @@ -584,8 +593,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); @@ -623,34 +630,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = FuelEfficiency.FromKilometersPerLiter(1); - Assert.True(v.Equals(FuelEfficiency.FromKilometersPerLiter(1), KilometersPerLiterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(FuelEfficiency.Zero, KilometersPerLiterTolerance, ComparisonType.Relative)); - Assert.True(FuelEfficiency.FromKilometersPerLiter(100).Equals(FuelEfficiency.FromKilometersPerLiter(120), 0.3, ComparisonType.Relative)); - Assert.False(FuelEfficiency.FromKilometersPerLiter(100).Equals(FuelEfficiency.FromKilometersPerLiter(120), 0.1, ComparisonType.Relative)); + FuelEfficiency kilometerperliter = FuelEfficiency.FromKilometersPerLiter(1); + Assert.False(kilometerperliter.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = FuelEfficiency.FromKilometersPerLiter(1); - Assert.Throws(() => v.Equals(FuelEfficiency.FromKilometersPerLiter(1), -1, ComparisonType.Relative)); + FuelEfficiency kilometerperliter = FuelEfficiency.FromKilometersPerLiter(1); + Assert.False(kilometerperliter.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - FuelEfficiency kilometerperliter = FuelEfficiency.FromKilometersPerLiter(1); - Assert.False(kilometerperliter.Equals(new object())); + var quantity = FuelEfficiency.FromKilometersPerLiter(firstValue); + var otherQuantity = FuelEfficiency.FromKilometersPerLiter(secondValue); + FuelEfficiency maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - FuelEfficiency kilometerperliter = FuelEfficiency.FromKilometersPerLiter(1); - Assert.False(kilometerperliter.Equals(null)); + var quantity = FuelEfficiency.FromKilometersPerLiter(1); + var negativeTolerance = FuelEfficiency.FromKilometersPerLiter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -669,6 +685,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() { @@ -733,158 +761,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = FuelEfficiency.FromKilometersPerLiter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = FuelEfficiency.FromKilometersPerLiter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = FuelEfficiency.FromKilometersPerLiter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = FuelEfficiency.FromKilometersPerLiter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = FuelEfficiency.FromKilometersPerLiter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = FuelEfficiency.FromKilometersPerLiter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = FuelEfficiency.FromKilometersPerLiter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = FuelEfficiency.FromKilometersPerLiter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = FuelEfficiency.FromKilometersPerLiter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = FuelEfficiency.FromKilometersPerLiter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = FuelEfficiency.FromKilometersPerLiter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = FuelEfficiency.FromKilometersPerLiter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = FuelEfficiency.FromKilometersPerLiter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = FuelEfficiency.FromKilometersPerLiter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = FuelEfficiency.FromKilometersPerLiter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = FuelEfficiency.FromKilometersPerLiter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(FuelEfficiency))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = FuelEfficiency.FromKilometersPerLiter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(FuelEfficiencyUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = FuelEfficiency.FromKilometersPerLiter(1.0); - Assert.Equal(FuelEfficiency.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = FuelEfficiency.FromKilometersPerLiter(1.0); - Assert.Equal(FuelEfficiency.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = FuelEfficiency.FromKilometersPerLiter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = FuelEfficiency.FromKilometersPerLiter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = FuelEfficiency.FromKilometersPerLiter(1.0); - Assert.Equal(new {FuelEfficiency.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 f8ac807234..5a3a0661e8 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/HeatFluxTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/HeatFluxTestsBase.g.cs @@ -164,7 +164,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new HeatFlux(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -177,15 +177,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void HeatFlux_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + HeatFluxUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new HeatFlux(1, HeatFluxUnit.WattPerSquareMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(HeatFlux.Zero, quantityInfo.Zero); Assert.Equal("HeatFlux", quantityInfo.Name); + Assert.Equal(HeatFlux.Zero, quantityInfo.Zero); + Assert.Equal(HeatFlux.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(HeatFlux.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void HeatFluxInfo_CreateWithCustomUnitInfos() + { + HeatFluxUnit[] expectedUnits = [HeatFluxUnit.WattPerSquareMeter]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -216,75 +234,75 @@ public void WattPerSquareMeterToHeatFluxUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = HeatFlux.From(1, HeatFluxUnit.BtuPerHourSquareFoot); - AssertEx.EqualTolerance(1, quantity00.BtusPerHourSquareFoot, BtusPerHourSquareFootTolerance); + Assert.Equal(1, quantity00.BtusPerHourSquareFoot); Assert.Equal(HeatFluxUnit.BtuPerHourSquareFoot, quantity00.Unit); var quantity01 = HeatFlux.From(1, HeatFluxUnit.BtuPerMinuteSquareFoot); - AssertEx.EqualTolerance(1, quantity01.BtusPerMinuteSquareFoot, BtusPerMinuteSquareFootTolerance); + Assert.Equal(1, quantity01.BtusPerMinuteSquareFoot); Assert.Equal(HeatFluxUnit.BtuPerMinuteSquareFoot, quantity01.Unit); var quantity02 = HeatFlux.From(1, HeatFluxUnit.BtuPerSecondSquareFoot); - AssertEx.EqualTolerance(1, quantity02.BtusPerSecondSquareFoot, BtusPerSecondSquareFootTolerance); + Assert.Equal(1, quantity02.BtusPerSecondSquareFoot); Assert.Equal(HeatFluxUnit.BtuPerSecondSquareFoot, quantity02.Unit); var quantity03 = HeatFlux.From(1, HeatFluxUnit.BtuPerSecondSquareInch); - AssertEx.EqualTolerance(1, quantity03.BtusPerSecondSquareInch, BtusPerSecondSquareInchTolerance); + Assert.Equal(1, quantity03.BtusPerSecondSquareInch); Assert.Equal(HeatFluxUnit.BtuPerSecondSquareInch, quantity03.Unit); var quantity04 = HeatFlux.From(1, HeatFluxUnit.CaloriePerSecondSquareCentimeter); - AssertEx.EqualTolerance(1, quantity04.CaloriesPerSecondSquareCentimeter, CaloriesPerSecondSquareCentimeterTolerance); + Assert.Equal(1, quantity04.CaloriesPerSecondSquareCentimeter); Assert.Equal(HeatFluxUnit.CaloriePerSecondSquareCentimeter, quantity04.Unit); var quantity05 = HeatFlux.From(1, HeatFluxUnit.CentiwattPerSquareMeter); - AssertEx.EqualTolerance(1, quantity05.CentiwattsPerSquareMeter, CentiwattsPerSquareMeterTolerance); + Assert.Equal(1, quantity05.CentiwattsPerSquareMeter); Assert.Equal(HeatFluxUnit.CentiwattPerSquareMeter, quantity05.Unit); var quantity06 = HeatFlux.From(1, HeatFluxUnit.DeciwattPerSquareMeter); - AssertEx.EqualTolerance(1, quantity06.DeciwattsPerSquareMeter, DeciwattsPerSquareMeterTolerance); + Assert.Equal(1, quantity06.DeciwattsPerSquareMeter); Assert.Equal(HeatFluxUnit.DeciwattPerSquareMeter, quantity06.Unit); var quantity07 = HeatFlux.From(1, HeatFluxUnit.KilocaloriePerHourSquareMeter); - AssertEx.EqualTolerance(1, quantity07.KilocaloriesPerHourSquareMeter, KilocaloriesPerHourSquareMeterTolerance); + Assert.Equal(1, quantity07.KilocaloriesPerHourSquareMeter); Assert.Equal(HeatFluxUnit.KilocaloriePerHourSquareMeter, quantity07.Unit); var quantity08 = HeatFlux.From(1, HeatFluxUnit.KilocaloriePerSecondSquareCentimeter); - AssertEx.EqualTolerance(1, quantity08.KilocaloriesPerSecondSquareCentimeter, KilocaloriesPerSecondSquareCentimeterTolerance); + Assert.Equal(1, quantity08.KilocaloriesPerSecondSquareCentimeter); Assert.Equal(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter, quantity08.Unit); var quantity09 = HeatFlux.From(1, HeatFluxUnit.KilowattPerSquareMeter); - AssertEx.EqualTolerance(1, quantity09.KilowattsPerSquareMeter, KilowattsPerSquareMeterTolerance); + Assert.Equal(1, quantity09.KilowattsPerSquareMeter); Assert.Equal(HeatFluxUnit.KilowattPerSquareMeter, quantity09.Unit); var quantity10 = HeatFlux.From(1, HeatFluxUnit.MicrowattPerSquareMeter); - AssertEx.EqualTolerance(1, quantity10.MicrowattsPerSquareMeter, MicrowattsPerSquareMeterTolerance); + Assert.Equal(1, quantity10.MicrowattsPerSquareMeter); Assert.Equal(HeatFluxUnit.MicrowattPerSquareMeter, quantity10.Unit); var quantity11 = HeatFlux.From(1, HeatFluxUnit.MilliwattPerSquareMeter); - AssertEx.EqualTolerance(1, quantity11.MilliwattsPerSquareMeter, MilliwattsPerSquareMeterTolerance); + Assert.Equal(1, quantity11.MilliwattsPerSquareMeter); Assert.Equal(HeatFluxUnit.MilliwattPerSquareMeter, quantity11.Unit); var quantity12 = HeatFlux.From(1, HeatFluxUnit.NanowattPerSquareMeter); - AssertEx.EqualTolerance(1, quantity12.NanowattsPerSquareMeter, NanowattsPerSquareMeterTolerance); + Assert.Equal(1, quantity12.NanowattsPerSquareMeter); Assert.Equal(HeatFluxUnit.NanowattPerSquareMeter, quantity12.Unit); var quantity13 = HeatFlux.From(1, HeatFluxUnit.PoundForcePerFootSecond); - AssertEx.EqualTolerance(1, quantity13.PoundsForcePerFootSecond, PoundsForcePerFootSecondTolerance); + Assert.Equal(1, quantity13.PoundsForcePerFootSecond); Assert.Equal(HeatFluxUnit.PoundForcePerFootSecond, quantity13.Unit); var quantity14 = HeatFlux.From(1, HeatFluxUnit.PoundPerSecondCubed); - AssertEx.EqualTolerance(1, quantity14.PoundsPerSecondCubed, PoundsPerSecondCubedTolerance); + Assert.Equal(1, quantity14.PoundsPerSecondCubed); Assert.Equal(HeatFluxUnit.PoundPerSecondCubed, quantity14.Unit); var quantity15 = HeatFlux.From(1, HeatFluxUnit.WattPerSquareFoot); - AssertEx.EqualTolerance(1, quantity15.WattsPerSquareFoot, WattsPerSquareFootTolerance); + Assert.Equal(1, quantity15.WattsPerSquareFoot); Assert.Equal(HeatFluxUnit.WattPerSquareFoot, quantity15.Unit); var quantity16 = HeatFlux.From(1, HeatFluxUnit.WattPerSquareInch); - AssertEx.EqualTolerance(1, quantity16.WattsPerSquareInch, WattsPerSquareInchTolerance); + Assert.Equal(1, quantity16.WattsPerSquareInch); Assert.Equal(HeatFluxUnit.WattPerSquareInch, quantity16.Unit); var quantity17 = HeatFlux.From(1, HeatFluxUnit.WattPerSquareMeter); - AssertEx.EqualTolerance(1, quantity17.WattsPerSquareMeter, WattsPerSquareMeterTolerance); + Assert.Equal(1, quantity17.WattsPerSquareMeter); Assert.Equal(HeatFluxUnit.WattPerSquareMeter, quantity17.Unit); } @@ -437,261 +455,60 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 BTU/(h·ft²)", HeatFluxUnit.BtuPerHourSquareFoot, 4.2)] + [InlineData("en-US", "4.2 BTU/(min·ft²)", HeatFluxUnit.BtuPerMinuteSquareFoot, 4.2)] + [InlineData("en-US", "4.2 BTU/(s·ft²)", HeatFluxUnit.BtuPerSecondSquareFoot, 4.2)] + [InlineData("en-US", "4.2 BTU/(s·in²)", HeatFluxUnit.BtuPerSecondSquareInch, 4.2)] + [InlineData("en-US", "4.2 cal/(s·cm²)", HeatFluxUnit.CaloriePerSecondSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 cW/m²", HeatFluxUnit.CentiwattPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 dW/m²", HeatFluxUnit.DeciwattPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 kcal/(h·m²)", HeatFluxUnit.KilocaloriePerHourSquareMeter, 4.2)] + [InlineData("en-US", "4.2 kcal/(s·cm²)", HeatFluxUnit.KilocaloriePerSecondSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 kW/m²", HeatFluxUnit.KilowattPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 µW/m²", HeatFluxUnit.MicrowattPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 mW/m²", HeatFluxUnit.MilliwattPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 nW/m²", HeatFluxUnit.NanowattPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 lbf/(ft·s)", HeatFluxUnit.PoundForcePerFootSecond, 4.2)] + [InlineData("en-US", "4.2 lb/s³", HeatFluxUnit.PoundPerSecondCubed, 4.2)] + [InlineData("en-US", "4.2 lbm/s³", HeatFluxUnit.PoundPerSecondCubed, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = HeatFlux.Parse("1 BTU/(h·ft²)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.BtusPerHourSquareFoot, BtusPerHourSquareFootTolerance); - Assert.Equal(HeatFluxUnit.BtuPerHourSquareFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatFlux.Parse("1 BTU/(min·ft²)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.BtusPerMinuteSquareFoot, BtusPerMinuteSquareFootTolerance); - Assert.Equal(HeatFluxUnit.BtuPerMinuteSquareFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatFlux.Parse("1 BTU/(s·ft²)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.BtusPerSecondSquareFoot, BtusPerSecondSquareFootTolerance); - Assert.Equal(HeatFluxUnit.BtuPerSecondSquareFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatFlux.Parse("1 BTU/(s·in²)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.BtusPerSecondSquareInch, BtusPerSecondSquareInchTolerance); - Assert.Equal(HeatFluxUnit.BtuPerSecondSquareInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatFlux.Parse("1 cal/(s·cm²)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CaloriesPerSecondSquareCentimeter, CaloriesPerSecondSquareCentimeterTolerance); - Assert.Equal(HeatFluxUnit.CaloriePerSecondSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatFlux.Parse("1 cW/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentiwattsPerSquareMeter, CentiwattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.CentiwattPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatFlux.Parse("1 dW/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DeciwattsPerSquareMeter, DeciwattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.DeciwattPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatFlux.Parse("1 kcal/(h·m²)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilocaloriesPerHourSquareMeter, KilocaloriesPerHourSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.KilocaloriePerHourSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatFlux.Parse("1 kcal/(s·cm²)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilocaloriesPerSecondSquareCentimeter, KilocaloriesPerSecondSquareCentimeterTolerance); - Assert.Equal(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatFlux.Parse("1 kW/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilowattsPerSquareMeter, KilowattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.KilowattPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatFlux.Parse("1 µW/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrowattsPerSquareMeter, MicrowattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.MicrowattPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatFlux.Parse("1 mW/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilliwattsPerSquareMeter, MilliwattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.MilliwattPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatFlux.Parse("1 nW/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanowattsPerSquareMeter, NanowattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.NanowattPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatFlux.Parse("1 lbf/(ft·s)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerFootSecond, PoundsForcePerFootSecondTolerance); - Assert.Equal(HeatFluxUnit.PoundForcePerFootSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatFlux.Parse("1 lb/s³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerSecondCubed, PoundsPerSecondCubedTolerance); - Assert.Equal(HeatFluxUnit.PoundPerSecondCubed, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatFlux.Parse("1 lbm/s³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerSecondCubed, PoundsPerSecondCubedTolerance); - Assert.Equal(HeatFluxUnit.PoundPerSecondCubed, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatFlux.Parse("1 W/ft²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WattsPerSquareFoot, WattsPerSquareFootTolerance); - Assert.Equal(HeatFluxUnit.WattPerSquareFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatFlux.Parse("1 W/in²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WattsPerSquareInch, WattsPerSquareInchTolerance); - Assert.Equal(HeatFluxUnit.WattPerSquareInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatFlux.Parse("1 W/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WattsPerSquareMeter, WattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.WattPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = HeatFlux.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 BTU/(h·ft²)", HeatFluxUnit.BtuPerHourSquareFoot, 4.2)] + [InlineData("en-US", "4.2 BTU/(min·ft²)", HeatFluxUnit.BtuPerMinuteSquareFoot, 4.2)] + [InlineData("en-US", "4.2 BTU/(s·ft²)", HeatFluxUnit.BtuPerSecondSquareFoot, 4.2)] + [InlineData("en-US", "4.2 BTU/(s·in²)", HeatFluxUnit.BtuPerSecondSquareInch, 4.2)] + [InlineData("en-US", "4.2 cal/(s·cm²)", HeatFluxUnit.CaloriePerSecondSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 cW/m²", HeatFluxUnit.CentiwattPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 dW/m²", HeatFluxUnit.DeciwattPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 kcal/(h·m²)", HeatFluxUnit.KilocaloriePerHourSquareMeter, 4.2)] + [InlineData("en-US", "4.2 kcal/(s·cm²)", HeatFluxUnit.KilocaloriePerSecondSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 kW/m²", HeatFluxUnit.KilowattPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 µW/m²", HeatFluxUnit.MicrowattPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 mW/m²", HeatFluxUnit.MilliwattPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 nW/m²", HeatFluxUnit.NanowattPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 lbf/(ft·s)", HeatFluxUnit.PoundForcePerFootSecond, 4.2)] + [InlineData("en-US", "4.2 lb/s³", HeatFluxUnit.PoundPerSecondCubed, 4.2)] + [InlineData("en-US", "4.2 lbm/s³", HeatFluxUnit.PoundPerSecondCubed, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(HeatFlux.TryParse("1 BTU/(h·ft²)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BtusPerHourSquareFoot, BtusPerHourSquareFootTolerance); - Assert.Equal(HeatFluxUnit.BtuPerHourSquareFoot, parsed.Unit); - } - - { - Assert.True(HeatFlux.TryParse("1 BTU/(min·ft²)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BtusPerMinuteSquareFoot, BtusPerMinuteSquareFootTolerance); - Assert.Equal(HeatFluxUnit.BtuPerMinuteSquareFoot, parsed.Unit); - } - - { - Assert.True(HeatFlux.TryParse("1 BTU/(s·ft²)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BtusPerSecondSquareFoot, BtusPerSecondSquareFootTolerance); - Assert.Equal(HeatFluxUnit.BtuPerSecondSquareFoot, parsed.Unit); - } - - { - Assert.True(HeatFlux.TryParse("1 BTU/(s·in²)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BtusPerSecondSquareInch, BtusPerSecondSquareInchTolerance); - Assert.Equal(HeatFluxUnit.BtuPerSecondSquareInch, parsed.Unit); - } - - { - Assert.True(HeatFlux.TryParse("1 cal/(s·cm²)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CaloriesPerSecondSquareCentimeter, CaloriesPerSecondSquareCentimeterTolerance); - Assert.Equal(HeatFluxUnit.CaloriePerSecondSquareCentimeter, parsed.Unit); - } - - { - Assert.True(HeatFlux.TryParse("1 cW/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentiwattsPerSquareMeter, CentiwattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.CentiwattPerSquareMeter, parsed.Unit); - } - - { - Assert.True(HeatFlux.TryParse("1 dW/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DeciwattsPerSquareMeter, DeciwattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.DeciwattPerSquareMeter, parsed.Unit); - } - - { - Assert.True(HeatFlux.TryParse("1 kcal/(h·m²)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilocaloriesPerHourSquareMeter, KilocaloriesPerHourSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.KilocaloriePerHourSquareMeter, parsed.Unit); - } - - { - Assert.True(HeatFlux.TryParse("1 kcal/(s·cm²)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilocaloriesPerSecondSquareCentimeter, KilocaloriesPerSecondSquareCentimeterTolerance); - Assert.Equal(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter, parsed.Unit); - } - - { - Assert.True(HeatFlux.TryParse("1 kW/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilowattsPerSquareMeter, KilowattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.KilowattPerSquareMeter, parsed.Unit); - } - - { - Assert.True(HeatFlux.TryParse("1 µW/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrowattsPerSquareMeter, MicrowattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.MicrowattPerSquareMeter, parsed.Unit); - } - - { - Assert.True(HeatFlux.TryParse("1 mW/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilliwattsPerSquareMeter, MilliwattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.MilliwattPerSquareMeter, parsed.Unit); - } - - { - Assert.True(HeatFlux.TryParse("1 nW/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanowattsPerSquareMeter, NanowattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.NanowattPerSquareMeter, parsed.Unit); - } - - { - Assert.True(HeatFlux.TryParse("1 lbf/(ft·s)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerFootSecond, PoundsForcePerFootSecondTolerance); - Assert.Equal(HeatFluxUnit.PoundForcePerFootSecond, parsed.Unit); - } - - { - Assert.True(HeatFlux.TryParse("1 lb/s³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerSecondCubed, PoundsPerSecondCubedTolerance); - Assert.Equal(HeatFluxUnit.PoundPerSecondCubed, parsed.Unit); - } - - { - Assert.True(HeatFlux.TryParse("1 lbm/s³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerSecondCubed, PoundsPerSecondCubedTolerance); - Assert.Equal(HeatFluxUnit.PoundPerSecondCubed, parsed.Unit); - } - - { - Assert.True(HeatFlux.TryParse("1 W/ft²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattsPerSquareFoot, WattsPerSquareFootTolerance); - Assert.Equal(HeatFluxUnit.WattPerSquareFoot, parsed.Unit); - } - - { - Assert.True(HeatFlux.TryParse("1 W/in²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattsPerSquareInch, WattsPerSquareInchTolerance); - Assert.Equal(HeatFluxUnit.WattPerSquareInch, parsed.Unit); - } - - { - Assert.True(HeatFlux.TryParse("1 W/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattsPerSquareMeter, WattsPerSquareMeterTolerance); - Assert.Equal(HeatFluxUnit.WattPerSquareMeter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(HeatFlux.TryParse(quantityString, out HeatFlux parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -912,6 +729,44 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, HeatFl Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", HeatFluxUnit.BtuPerHourSquareFoot, "BTU/(h·ft²)")] + [InlineData("en-US", HeatFluxUnit.BtuPerMinuteSquareFoot, "BTU/(min·ft²)")] + [InlineData("en-US", HeatFluxUnit.BtuPerSecondSquareFoot, "BTU/(s·ft²)")] + [InlineData("en-US", HeatFluxUnit.BtuPerSecondSquareInch, "BTU/(s·in²)")] + [InlineData("en-US", HeatFluxUnit.CaloriePerSecondSquareCentimeter, "cal/(s·cm²)")] + [InlineData("en-US", HeatFluxUnit.CentiwattPerSquareMeter, "cW/m²")] + [InlineData("en-US", HeatFluxUnit.DeciwattPerSquareMeter, "dW/m²")] + [InlineData("en-US", HeatFluxUnit.KilocaloriePerHourSquareMeter, "kcal/(h·m²)")] + [InlineData("en-US", HeatFluxUnit.KilocaloriePerSecondSquareCentimeter, "kcal/(s·cm²)")] + [InlineData("en-US", HeatFluxUnit.KilowattPerSquareMeter, "kW/m²")] + [InlineData("en-US", HeatFluxUnit.MicrowattPerSquareMeter, "µW/m²")] + [InlineData("en-US", HeatFluxUnit.MilliwattPerSquareMeter, "mW/m²")] + [InlineData("en-US", HeatFluxUnit.NanowattPerSquareMeter, "nW/m²")] + [InlineData("en-US", HeatFluxUnit.PoundForcePerFootSecond, "lbf/(ft·s)")] + [InlineData("en-US", HeatFluxUnit.PoundPerSecondCubed, "lb/s³")] + [InlineData("en-US", HeatFluxUnit.WattPerSquareFoot, "W/ft²")] + [InlineData("en-US", HeatFluxUnit.WattPerSquareInch, "W/in²")] + [InlineData("en-US", HeatFluxUnit.WattPerSquareMeter, "W/m²")] + public void GetAbbreviationForCulture(string culture, HeatFluxUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = HeatFlux.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(HeatFlux.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = HeatFlux.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(HeatFluxUnit unit) @@ -942,6 +797,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); }); } @@ -965,49 +821,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] @@ -1053,8 +911,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); @@ -1091,23 +947,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = HeatFlux.FromWattsPerSquareMeter(1); - Assert.True(v.Equals(HeatFlux.FromWattsPerSquareMeter(1), WattsPerSquareMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(HeatFlux.Zero, WattsPerSquareMeterTolerance, ComparisonType.Relative)); - Assert.True(HeatFlux.FromWattsPerSquareMeter(100).Equals(HeatFlux.FromWattsPerSquareMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(HeatFlux.FromWattsPerSquareMeter(100).Equals(HeatFlux.FromWattsPerSquareMeter(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = HeatFlux.FromWattsPerSquareMeter(1); - Assert.Throws(() => v.Equals(HeatFlux.FromWattsPerSquareMeter(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1122,6 +961,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(wattpersquaremeter.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = HeatFlux.FromWattsPerSquareMeter(1); + var negativeTolerance = HeatFlux.FromWattsPerSquareMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1138,6 +1003,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() { @@ -1230,158 +1107,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(HeatFlux))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(HeatFluxUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal(HeatFlux.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal(HeatFlux.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal(new {HeatFlux.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 d882172177..5d3f24c360 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/HeatTransferCoefficientTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/HeatTransferCoefficientTestsBase.g.cs @@ -112,7 +112,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new HeatTransferCoefficient(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -125,15 +125,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void HeatTransferCoefficient_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + HeatTransferCoefficientUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new HeatTransferCoefficient(1, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(HeatTransferCoefficient.Zero, quantityInfo.Zero); Assert.Equal("HeatTransferCoefficient", quantityInfo.Name); + Assert.Equal(HeatTransferCoefficient.Zero, quantityInfo.Zero); + Assert.Equal(HeatTransferCoefficient.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(HeatTransferCoefficient.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void HeatTransferCoefficientInfo_CreateWithCustomUnitInfos() + { + HeatTransferCoefficientUnit[] expectedUnits = [HeatTransferCoefficientUnit.WattPerSquareMeterKelvin]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -151,23 +169,23 @@ public void WattPerSquareMeterKelvinToHeatTransferCoefficientUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = HeatTransferCoefficient.From(1, HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit); - AssertEx.EqualTolerance(1, quantity00.BtusPerHourSquareFootDegreeFahrenheit, BtusPerHourSquareFootDegreeFahrenheitTolerance); + Assert.Equal(1, quantity00.BtusPerHourSquareFootDegreeFahrenheit); Assert.Equal(HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit, quantity00.Unit); var quantity01 = HeatTransferCoefficient.From(1, HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius); - AssertEx.EqualTolerance(1, quantity01.CaloriesPerHourSquareMeterDegreeCelsius, CaloriesPerHourSquareMeterDegreeCelsiusTolerance); + Assert.Equal(1, quantity01.CaloriesPerHourSquareMeterDegreeCelsius); Assert.Equal(HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius, quantity01.Unit); var quantity02 = HeatTransferCoefficient.From(1, HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius); - AssertEx.EqualTolerance(1, quantity02.KilocaloriesPerHourSquareMeterDegreeCelsius, KilocaloriesPerHourSquareMeterDegreeCelsiusTolerance); + Assert.Equal(1, quantity02.KilocaloriesPerHourSquareMeterDegreeCelsius); Assert.Equal(HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius, quantity02.Unit); var quantity03 = HeatTransferCoefficient.From(1, HeatTransferCoefficientUnit.WattPerSquareMeterCelsius); - AssertEx.EqualTolerance(1, quantity03.WattsPerSquareMeterCelsius, WattsPerSquareMeterCelsiusTolerance); + Assert.Equal(1, quantity03.WattsPerSquareMeterCelsius); Assert.Equal(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, quantity03.Unit); var quantity04 = HeatTransferCoefficient.From(1, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin); - AssertEx.EqualTolerance(1, quantity04.WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance); + Assert.Equal(1, quantity04.WattsPerSquareMeterKelvin); Assert.Equal(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, quantity04.Unit); } @@ -307,196 +325,50 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 Btu/(h·ft²·°F)", HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit, 4.2)] + [InlineData("en-US", "4.2 Btu/(ft²·h·°F)", HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit, 4.2)] + [InlineData("en-US", "4.2 Btu/(hr·ft²·°F)", HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit, 4.2)] + [InlineData("en-US", "4.2 Btu/(ft²·hr·°F)", HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit, 4.2)] + [InlineData("en-US", "4.2 kcal/(h·m²·°C)", HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 kcal/(m²·h·°C)", HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 kcal/(hr·m²·°C)", HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 kcal/(m²·hr·°C)", HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 kkcal/(h·m²·°C)", HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 kkcal/(m²·h·°C)", HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 kkcal/(hr·m²·°C)", HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = HeatTransferCoefficient.Parse("1 Btu/(h·ft²·°F)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.BtusPerHourSquareFootDegreeFahrenheit, BtusPerHourSquareFootDegreeFahrenheitTolerance); - Assert.Equal(HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatTransferCoefficient.Parse("1 Btu/(ft²·h·°F)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.BtusPerHourSquareFootDegreeFahrenheit, BtusPerHourSquareFootDegreeFahrenheitTolerance); - Assert.Equal(HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatTransferCoefficient.Parse("1 Btu/(hr·ft²·°F)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.BtusPerHourSquareFootDegreeFahrenheit, BtusPerHourSquareFootDegreeFahrenheitTolerance); - Assert.Equal(HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatTransferCoefficient.Parse("1 Btu/(ft²·hr·°F)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.BtusPerHourSquareFootDegreeFahrenheit, BtusPerHourSquareFootDegreeFahrenheitTolerance); - Assert.Equal(HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatTransferCoefficient.Parse("1 kcal/(h·m²·°C)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CaloriesPerHourSquareMeterDegreeCelsius, CaloriesPerHourSquareMeterDegreeCelsiusTolerance); - Assert.Equal(HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatTransferCoefficient.Parse("1 kcal/(m²·h·°C)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CaloriesPerHourSquareMeterDegreeCelsius, CaloriesPerHourSquareMeterDegreeCelsiusTolerance); - Assert.Equal(HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatTransferCoefficient.Parse("1 kcal/(hr·m²·°C)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CaloriesPerHourSquareMeterDegreeCelsius, CaloriesPerHourSquareMeterDegreeCelsiusTolerance); - Assert.Equal(HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatTransferCoefficient.Parse("1 kcal/(m²·hr·°C)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CaloriesPerHourSquareMeterDegreeCelsius, CaloriesPerHourSquareMeterDegreeCelsiusTolerance); - Assert.Equal(HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatTransferCoefficient.Parse("1 kkcal/(h·m²·°C)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilocaloriesPerHourSquareMeterDegreeCelsius, KilocaloriesPerHourSquareMeterDegreeCelsiusTolerance); - Assert.Equal(HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatTransferCoefficient.Parse("1 kkcal/(m²·h·°C)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilocaloriesPerHourSquareMeterDegreeCelsius, KilocaloriesPerHourSquareMeterDegreeCelsiusTolerance); - Assert.Equal(HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatTransferCoefficient.Parse("1 kkcal/(hr·m²·°C)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilocaloriesPerHourSquareMeterDegreeCelsius, KilocaloriesPerHourSquareMeterDegreeCelsiusTolerance); - Assert.Equal(HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatTransferCoefficient.Parse("1 kkcal/(m²·hr·°C)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilocaloriesPerHourSquareMeterDegreeCelsius, KilocaloriesPerHourSquareMeterDegreeCelsiusTolerance); - Assert.Equal(HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatTransferCoefficient.Parse("1 W/(m²·°C)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WattsPerSquareMeterCelsius, WattsPerSquareMeterCelsiusTolerance); - Assert.Equal(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = HeatTransferCoefficient.Parse("1 W/(m²·K)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance); - Assert.Equal(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = HeatTransferCoefficient.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 Btu/(h·ft²·°F)", HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit, 4.2)] + [InlineData("en-US", "4.2 Btu/(ft²·h·°F)", HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit, 4.2)] + [InlineData("en-US", "4.2 Btu/(hr·ft²·°F)", HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit, 4.2)] + [InlineData("en-US", "4.2 Btu/(ft²·hr·°F)", HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit, 4.2)] + [InlineData("en-US", "4.2 kcal/(h·m²·°C)", HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 kcal/(m²·h·°C)", HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 kcal/(hr·m²·°C)", HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 kcal/(m²·hr·°C)", HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 kkcal/(h·m²·°C)", HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 kkcal/(m²·h·°C)", HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 kkcal/(hr·m²·°C)", HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(HeatTransferCoefficient.TryParse("1 Btu/(h·ft²·°F)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BtusPerHourSquareFootDegreeFahrenheit, BtusPerHourSquareFootDegreeFahrenheitTolerance); - Assert.Equal(HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit, parsed.Unit); - } - - { - Assert.True(HeatTransferCoefficient.TryParse("1 Btu/(ft²·h·°F)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BtusPerHourSquareFootDegreeFahrenheit, BtusPerHourSquareFootDegreeFahrenheitTolerance); - Assert.Equal(HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit, parsed.Unit); - } - - { - Assert.True(HeatTransferCoefficient.TryParse("1 Btu/(hr·ft²·°F)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BtusPerHourSquareFootDegreeFahrenheit, BtusPerHourSquareFootDegreeFahrenheitTolerance); - Assert.Equal(HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit, parsed.Unit); - } - - { - Assert.True(HeatTransferCoefficient.TryParse("1 Btu/(ft²·hr·°F)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BtusPerHourSquareFootDegreeFahrenheit, BtusPerHourSquareFootDegreeFahrenheitTolerance); - Assert.Equal(HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit, parsed.Unit); - } - - { - Assert.True(HeatTransferCoefficient.TryParse("1 kcal/(h·m²·°C)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CaloriesPerHourSquareMeterDegreeCelsius, CaloriesPerHourSquareMeterDegreeCelsiusTolerance); - Assert.Equal(HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius, parsed.Unit); - } - - { - Assert.True(HeatTransferCoefficient.TryParse("1 kcal/(m²·h·°C)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CaloriesPerHourSquareMeterDegreeCelsius, CaloriesPerHourSquareMeterDegreeCelsiusTolerance); - Assert.Equal(HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius, parsed.Unit); - } - - { - Assert.True(HeatTransferCoefficient.TryParse("1 kcal/(hr·m²·°C)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CaloriesPerHourSquareMeterDegreeCelsius, CaloriesPerHourSquareMeterDegreeCelsiusTolerance); - Assert.Equal(HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius, parsed.Unit); - } - - { - Assert.True(HeatTransferCoefficient.TryParse("1 kcal/(m²·hr·°C)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CaloriesPerHourSquareMeterDegreeCelsius, CaloriesPerHourSquareMeterDegreeCelsiusTolerance); - Assert.Equal(HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius, parsed.Unit); - } - - { - Assert.True(HeatTransferCoefficient.TryParse("1 kkcal/(h·m²·°C)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilocaloriesPerHourSquareMeterDegreeCelsius, KilocaloriesPerHourSquareMeterDegreeCelsiusTolerance); - Assert.Equal(HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius, parsed.Unit); - } - - { - Assert.True(HeatTransferCoefficient.TryParse("1 kkcal/(m²·h·°C)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilocaloriesPerHourSquareMeterDegreeCelsius, KilocaloriesPerHourSquareMeterDegreeCelsiusTolerance); - Assert.Equal(HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius, parsed.Unit); - } - - { - Assert.True(HeatTransferCoefficient.TryParse("1 kkcal/(hr·m²·°C)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilocaloriesPerHourSquareMeterDegreeCelsius, KilocaloriesPerHourSquareMeterDegreeCelsiusTolerance); - Assert.Equal(HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius, parsed.Unit); - } - - { - Assert.True(HeatTransferCoefficient.TryParse("1 kkcal/(m²·hr·°C)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilocaloriesPerHourSquareMeterDegreeCelsius, KilocaloriesPerHourSquareMeterDegreeCelsiusTolerance); - Assert.Equal(HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius, parsed.Unit); - } - - { - Assert.True(HeatTransferCoefficient.TryParse("1 W/(m²·°C)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattsPerSquareMeterCelsius, WattsPerSquareMeterCelsiusTolerance); - Assert.Equal(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, parsed.Unit); - } - - { - Assert.True(HeatTransferCoefficient.TryParse("1 W/(m²·K)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance); - Assert.Equal(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(HeatTransferCoefficient.TryParse(quantityString, out HeatTransferCoefficient parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -677,6 +549,31 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, HeatTr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit, "Btu/(h·ft²·°F)")] + [InlineData("en-US", HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius, "kcal/(h·m²·°C)")] + [InlineData("en-US", HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius, "kkcal/(h·m²·°C)")] + [InlineData("en-US", HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, "W/(m²·°C)")] + [InlineData("en-US", HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, "W/(m²·K)")] + public void GetAbbreviationForCulture(string culture, HeatTransferCoefficientUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = HeatTransferCoefficient.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(HeatTransferCoefficient.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = HeatTransferCoefficient.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(HeatTransferCoefficientUnit unit) @@ -707,6 +604,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); }); } @@ -730,36 +628,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] @@ -805,8 +705,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); @@ -844,34 +742,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1); - Assert.True(v.Equals(HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1), WattsPerSquareMeterKelvinTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(HeatTransferCoefficient.Zero, WattsPerSquareMeterKelvinTolerance, ComparisonType.Relative)); - Assert.True(HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(100).Equals(HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(120), 0.3, ComparisonType.Relative)); - Assert.False(HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(100).Equals(HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(120), 0.1, ComparisonType.Relative)); + HeatTransferCoefficient wattpersquaremeterkelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1); + Assert.False(wattpersquaremeterkelvin.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1); - Assert.Throws(() => v.Equals(HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1), -1, ComparisonType.Relative)); + HeatTransferCoefficient wattpersquaremeterkelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1); + Assert.False(wattpersquaremeterkelvin.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - HeatTransferCoefficient wattpersquaremeterkelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1); - Assert.False(wattpersquaremeterkelvin.Equals(new object())); + var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(firstValue); + var otherQuantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(secondValue); + HeatTransferCoefficient maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - HeatTransferCoefficient wattpersquaremeterkelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1); - Assert.False(wattpersquaremeterkelvin.Equals(null)); + var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1); + var negativeTolerance = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -890,6 +797,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() { @@ -956,158 +875,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(HeatTransferCoefficient))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(HeatTransferCoefficientUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal(HeatTransferCoefficient.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal(HeatTransferCoefficient.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal(new {HeatTransferCoefficient.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 2574b7da6a..991d276b30 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/IlluminanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/IlluminanceTestsBase.g.cs @@ -108,7 +108,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Illuminance(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -121,15 +121,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Illuminance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + IlluminanceUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Illuminance(1, IlluminanceUnit.Lux); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Illuminance.Zero, quantityInfo.Zero); Assert.Equal("Illuminance", quantityInfo.Name); + Assert.Equal(Illuminance.Zero, quantityInfo.Zero); + Assert.Equal(Illuminance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Illuminance.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void IlluminanceInfo_CreateWithCustomUnitInfos() + { + IlluminanceUnit[] expectedUnits = [IlluminanceUnit.Lux]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -146,19 +164,19 @@ public void LuxToIlluminanceUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Illuminance.From(1, IlluminanceUnit.Kilolux); - AssertEx.EqualTolerance(1, quantity00.Kilolux, KiloluxTolerance); + Assert.Equal(1, quantity00.Kilolux); Assert.Equal(IlluminanceUnit.Kilolux, quantity00.Unit); var quantity01 = Illuminance.From(1, IlluminanceUnit.Lux); - AssertEx.EqualTolerance(1, quantity01.Lux, LuxTolerance); + Assert.Equal(1, quantity01.Lux); Assert.Equal(IlluminanceUnit.Lux, quantity01.Unit); var quantity02 = Illuminance.From(1, IlluminanceUnit.Megalux); - AssertEx.EqualTolerance(1, quantity02.Megalux, MegaluxTolerance); + Assert.Equal(1, quantity02.Megalux); Assert.Equal(IlluminanceUnit.Megalux, quantity02.Unit); var quantity03 = Illuminance.From(1, IlluminanceUnit.Millilux); - AssertEx.EqualTolerance(1, quantity03.Millilux, MilliluxTolerance); + Assert.Equal(1, quantity03.Millilux); Assert.Equal(IlluminanceUnit.Millilux, quantity03.Unit); } @@ -297,54 +315,30 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 klx", IlluminanceUnit.Kilolux, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = Illuminance.Parse("1 klx", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilolux, KiloluxTolerance); - Assert.Equal(IlluminanceUnit.Kilolux, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Illuminance.Parse("1 lx", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Lux, LuxTolerance); - Assert.Equal(IlluminanceUnit.Lux, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Illuminance.Parse("1 Mlx", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megalux, MegaluxTolerance); - Assert.Equal(IlluminanceUnit.Megalux, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Illuminance.Parse("1 mlx", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millilux, MilliluxTolerance); - Assert.Equal(IlluminanceUnit.Millilux, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Illuminance.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 klx", IlluminanceUnit.Kilolux, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(Illuminance.TryParse("1 klx", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilolux, KiloluxTolerance); - Assert.Equal(IlluminanceUnit.Kilolux, parsed.Unit); - } - - { - Assert.True(Illuminance.TryParse("1 lx", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Lux, LuxTolerance); - Assert.Equal(IlluminanceUnit.Lux, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Illuminance.TryParse(quantityString, out Illuminance parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -445,6 +439,30 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Illumi Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", IlluminanceUnit.Kilolux, "klx")] + [InlineData("en-US", IlluminanceUnit.Lux, "lx")] + [InlineData("en-US", IlluminanceUnit.Megalux, "Mlx")] + [InlineData("en-US", IlluminanceUnit.Millilux, "mlx")] + public void GetAbbreviationForCulture(string culture, IlluminanceUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Illuminance.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Illuminance.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Illuminance.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(IlluminanceUnit unit) @@ -475,6 +493,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); }); } @@ -498,35 +517,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] @@ -572,8 +593,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); @@ -611,34 +630,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = Illuminance.FromLux(1); - Assert.True(v.Equals(Illuminance.FromLux(1), LuxTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Illuminance.Zero, LuxTolerance, ComparisonType.Relative)); - Assert.True(Illuminance.FromLux(100).Equals(Illuminance.FromLux(120), 0.3, ComparisonType.Relative)); - Assert.False(Illuminance.FromLux(100).Equals(Illuminance.FromLux(120), 0.1, ComparisonType.Relative)); + Illuminance lux = Illuminance.FromLux(1); + Assert.False(lux.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = Illuminance.FromLux(1); - Assert.Throws(() => v.Equals(Illuminance.FromLux(1), -1, ComparisonType.Relative)); + Illuminance lux = Illuminance.FromLux(1); + Assert.False(lux.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - Illuminance lux = Illuminance.FromLux(1); - Assert.False(lux.Equals(new object())); + var quantity = Illuminance.FromLux(firstValue); + var otherQuantity = Illuminance.FromLux(secondValue); + Illuminance maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - Illuminance lux = Illuminance.FromLux(1); - Assert.False(lux.Equals(null)); + var quantity = Illuminance.FromLux(1); + var negativeTolerance = Illuminance.FromLux(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -657,6 +685,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() { @@ -721,158 +761,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Illuminance.FromLux(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Illuminance.FromLux(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Illuminance.FromLux(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Illuminance.FromLux(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Illuminance.FromLux(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Illuminance.FromLux(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Illuminance.FromLux(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Illuminance.FromLux(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Illuminance.FromLux(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Illuminance.FromLux(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Illuminance.FromLux(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Illuminance.FromLux(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Illuminance.FromLux(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Illuminance.FromLux(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Illuminance.FromLux(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Illuminance.FromLux(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Illuminance))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Illuminance.FromLux(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(IlluminanceUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Illuminance.FromLux(1.0); - Assert.Equal(Illuminance.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Illuminance.FromLux(1.0); - Assert.Equal(Illuminance.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Illuminance.FromLux(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Illuminance.FromLux(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Illuminance.FromLux(1.0); - Assert.Equal(new {Illuminance.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 ff51e39a53..896da49301 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ImpulseTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ImpulseTestsBase.g.cs @@ -144,7 +144,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Impulse(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -157,15 +157,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Impulse_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ImpulseUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Impulse(1, ImpulseUnit.NewtonSecond); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Impulse.Zero, quantityInfo.Zero); Assert.Equal("Impulse", quantityInfo.Name); + Assert.Equal(Impulse.Zero, quantityInfo.Zero); + Assert.Equal(Impulse.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Impulse.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -191,55 +209,55 @@ public void NewtonSecondToImpulseUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Impulse.From(1, ImpulseUnit.CentinewtonSecond); - AssertEx.EqualTolerance(1, quantity00.CentinewtonSeconds, CentinewtonSecondsTolerance); + Assert.Equal(1, quantity00.CentinewtonSeconds); Assert.Equal(ImpulseUnit.CentinewtonSecond, quantity00.Unit); var quantity01 = Impulse.From(1, ImpulseUnit.DecanewtonSecond); - AssertEx.EqualTolerance(1, quantity01.DecanewtonSeconds, DecanewtonSecondsTolerance); + Assert.Equal(1, quantity01.DecanewtonSeconds); Assert.Equal(ImpulseUnit.DecanewtonSecond, quantity01.Unit); var quantity02 = Impulse.From(1, ImpulseUnit.DecinewtonSecond); - AssertEx.EqualTolerance(1, quantity02.DecinewtonSeconds, DecinewtonSecondsTolerance); + Assert.Equal(1, quantity02.DecinewtonSeconds); Assert.Equal(ImpulseUnit.DecinewtonSecond, quantity02.Unit); var quantity03 = Impulse.From(1, ImpulseUnit.KilogramMeterPerSecond); - AssertEx.EqualTolerance(1, quantity03.KilogramMetersPerSecond, KilogramMetersPerSecondTolerance); + Assert.Equal(1, quantity03.KilogramMetersPerSecond); Assert.Equal(ImpulseUnit.KilogramMeterPerSecond, quantity03.Unit); var quantity04 = Impulse.From(1, ImpulseUnit.KilonewtonSecond); - AssertEx.EqualTolerance(1, quantity04.KilonewtonSeconds, KilonewtonSecondsTolerance); + Assert.Equal(1, quantity04.KilonewtonSeconds); Assert.Equal(ImpulseUnit.KilonewtonSecond, quantity04.Unit); var quantity05 = Impulse.From(1, ImpulseUnit.MeganewtonSecond); - AssertEx.EqualTolerance(1, quantity05.MeganewtonSeconds, MeganewtonSecondsTolerance); + Assert.Equal(1, quantity05.MeganewtonSeconds); Assert.Equal(ImpulseUnit.MeganewtonSecond, quantity05.Unit); var quantity06 = Impulse.From(1, ImpulseUnit.MicronewtonSecond); - AssertEx.EqualTolerance(1, quantity06.MicronewtonSeconds, MicronewtonSecondsTolerance); + Assert.Equal(1, quantity06.MicronewtonSeconds); Assert.Equal(ImpulseUnit.MicronewtonSecond, quantity06.Unit); var quantity07 = Impulse.From(1, ImpulseUnit.MillinewtonSecond); - AssertEx.EqualTolerance(1, quantity07.MillinewtonSeconds, MillinewtonSecondsTolerance); + Assert.Equal(1, quantity07.MillinewtonSeconds); Assert.Equal(ImpulseUnit.MillinewtonSecond, quantity07.Unit); var quantity08 = Impulse.From(1, ImpulseUnit.NanonewtonSecond); - AssertEx.EqualTolerance(1, quantity08.NanonewtonSeconds, NanonewtonSecondsTolerance); + Assert.Equal(1, quantity08.NanonewtonSeconds); Assert.Equal(ImpulseUnit.NanonewtonSecond, quantity08.Unit); var quantity09 = Impulse.From(1, ImpulseUnit.NewtonSecond); - AssertEx.EqualTolerance(1, quantity09.NewtonSeconds, NewtonSecondsTolerance); + Assert.Equal(1, quantity09.NewtonSeconds); Assert.Equal(ImpulseUnit.NewtonSecond, quantity09.Unit); var quantity10 = Impulse.From(1, ImpulseUnit.PoundFootPerSecond); - AssertEx.EqualTolerance(1, quantity10.PoundFeetPerSecond, PoundFeetPerSecondTolerance); + Assert.Equal(1, quantity10.PoundFeetPerSecond); Assert.Equal(ImpulseUnit.PoundFootPerSecond, quantity10.Unit); var quantity11 = Impulse.From(1, ImpulseUnit.PoundForceSecond); - AssertEx.EqualTolerance(1, quantity11.PoundForceSeconds, PoundForceSecondsTolerance); + Assert.Equal(1, quantity11.PoundForceSeconds); Assert.Equal(ImpulseUnit.PoundForceSecond, quantity11.Unit); var quantity12 = Impulse.From(1, ImpulseUnit.SlugFootPerSecond); - AssertEx.EqualTolerance(1, quantity12.SlugFeetPerSecond, SlugFeetPerSecondTolerance); + Assert.Equal(1, quantity12.SlugFeetPerSecond); Assert.Equal(ImpulseUnit.SlugFootPerSecond, quantity12.Unit); } @@ -387,171 +405,48 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 cN·s", ImpulseUnit.CentinewtonSecond, 4.2)] + [InlineData("en-US", "4.2 daN·s", ImpulseUnit.DecanewtonSecond, 4.2)] + [InlineData("en-US", "4.2 dN·s", ImpulseUnit.DecinewtonSecond, 4.2)] + [InlineData("en-US", "4.2 kg·m/s", ImpulseUnit.KilogramMeterPerSecond, 4.2)] + [InlineData("en-US", "4.2 kN·s", ImpulseUnit.KilonewtonSecond, 4.2)] + [InlineData("en-US", "4.2 MN·s", ImpulseUnit.MeganewtonSecond, 4.2)] + [InlineData("en-US", "4.2 µN·s", ImpulseUnit.MicronewtonSecond, 4.2)] + [InlineData("en-US", "4.2 mN·s", ImpulseUnit.MillinewtonSecond, 4.2)] + [InlineData("en-US", "4.2 nN·s", ImpulseUnit.NanonewtonSecond, 4.2)] + [InlineData("en-US", "4.2 N·s", ImpulseUnit.NewtonSecond, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = Impulse.Parse("1 cN·s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentinewtonSeconds, CentinewtonSecondsTolerance); - Assert.Equal(ImpulseUnit.CentinewtonSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Impulse.Parse("1 daN·s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecanewtonSeconds, DecanewtonSecondsTolerance); - Assert.Equal(ImpulseUnit.DecanewtonSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Impulse.Parse("1 dN·s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecinewtonSeconds, DecinewtonSecondsTolerance); - Assert.Equal(ImpulseUnit.DecinewtonSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Impulse.Parse("1 kg·m/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramMetersPerSecond, KilogramMetersPerSecondTolerance); - Assert.Equal(ImpulseUnit.KilogramMeterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Impulse.Parse("1 kN·s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonSeconds, KilonewtonSecondsTolerance); - Assert.Equal(ImpulseUnit.KilonewtonSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Impulse.Parse("1 MN·s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MeganewtonSeconds, MeganewtonSecondsTolerance); - Assert.Equal(ImpulseUnit.MeganewtonSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Impulse.Parse("1 µN·s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicronewtonSeconds, MicronewtonSecondsTolerance); - Assert.Equal(ImpulseUnit.MicronewtonSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Impulse.Parse("1 mN·s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillinewtonSeconds, MillinewtonSecondsTolerance); - Assert.Equal(ImpulseUnit.MillinewtonSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Impulse.Parse("1 nN·s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanonewtonSeconds, NanonewtonSecondsTolerance); - Assert.Equal(ImpulseUnit.NanonewtonSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Impulse.Parse("1 N·s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonSeconds, NewtonSecondsTolerance); - Assert.Equal(ImpulseUnit.NewtonSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Impulse.Parse("1 lb·ft/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundFeetPerSecond, PoundFeetPerSecondTolerance); - Assert.Equal(ImpulseUnit.PoundFootPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Impulse.Parse("1 lbf·s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundForceSeconds, PoundForceSecondsTolerance); - Assert.Equal(ImpulseUnit.PoundForceSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Impulse.Parse("1 slug·ft/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SlugFeetPerSecond, SlugFeetPerSecondTolerance); - Assert.Equal(ImpulseUnit.SlugFootPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Impulse.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 cN·s", ImpulseUnit.CentinewtonSecond, 4.2)] + [InlineData("en-US", "4.2 daN·s", ImpulseUnit.DecanewtonSecond, 4.2)] + [InlineData("en-US", "4.2 dN·s", ImpulseUnit.DecinewtonSecond, 4.2)] + [InlineData("en-US", "4.2 kg·m/s", ImpulseUnit.KilogramMeterPerSecond, 4.2)] + [InlineData("en-US", "4.2 kN·s", ImpulseUnit.KilonewtonSecond, 4.2)] + [InlineData("en-US", "4.2 MN·s", ImpulseUnit.MeganewtonSecond, 4.2)] + [InlineData("en-US", "4.2 µN·s", ImpulseUnit.MicronewtonSecond, 4.2)] + [InlineData("en-US", "4.2 mN·s", ImpulseUnit.MillinewtonSecond, 4.2)] + [InlineData("en-US", "4.2 nN·s", ImpulseUnit.NanonewtonSecond, 4.2)] + [InlineData("en-US", "4.2 N·s", ImpulseUnit.NewtonSecond, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(Impulse.TryParse("1 cN·s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentinewtonSeconds, CentinewtonSecondsTolerance); - Assert.Equal(ImpulseUnit.CentinewtonSecond, parsed.Unit); - } - - { - Assert.True(Impulse.TryParse("1 daN·s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecanewtonSeconds, DecanewtonSecondsTolerance); - Assert.Equal(ImpulseUnit.DecanewtonSecond, parsed.Unit); - } - - { - Assert.True(Impulse.TryParse("1 dN·s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecinewtonSeconds, DecinewtonSecondsTolerance); - Assert.Equal(ImpulseUnit.DecinewtonSecond, parsed.Unit); - } - - { - Assert.True(Impulse.TryParse("1 kg·m/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramMetersPerSecond, KilogramMetersPerSecondTolerance); - Assert.Equal(ImpulseUnit.KilogramMeterPerSecond, parsed.Unit); - } - - { - Assert.True(Impulse.TryParse("1 kN·s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonSeconds, KilonewtonSecondsTolerance); - Assert.Equal(ImpulseUnit.KilonewtonSecond, parsed.Unit); - } - - { - Assert.True(Impulse.TryParse("1 µN·s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicronewtonSeconds, MicronewtonSecondsTolerance); - Assert.Equal(ImpulseUnit.MicronewtonSecond, parsed.Unit); - } - - { - Assert.True(Impulse.TryParse("1 nN·s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanonewtonSeconds, NanonewtonSecondsTolerance); - Assert.Equal(ImpulseUnit.NanonewtonSecond, parsed.Unit); - } - - { - Assert.True(Impulse.TryParse("1 N·s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonSeconds, NewtonSecondsTolerance); - Assert.Equal(ImpulseUnit.NewtonSecond, parsed.Unit); - } - - { - Assert.True(Impulse.TryParse("1 lb·ft/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundFeetPerSecond, PoundFeetPerSecondTolerance); - Assert.Equal(ImpulseUnit.PoundFootPerSecond, parsed.Unit); - } - - { - Assert.True(Impulse.TryParse("1 lbf·s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundForceSeconds, PoundForceSecondsTolerance); - Assert.Equal(ImpulseUnit.PoundForceSecond, parsed.Unit); - } - - { - Assert.True(Impulse.TryParse("1 slug·ft/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SlugFeetPerSecond, SlugFeetPerSecondTolerance); - Assert.Equal(ImpulseUnit.SlugFootPerSecond, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Impulse.TryParse(quantityString, out Impulse parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -724,6 +619,39 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Impuls Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ImpulseUnit.CentinewtonSecond, "cN·s")] + [InlineData("en-US", ImpulseUnit.DecanewtonSecond, "daN·s")] + [InlineData("en-US", ImpulseUnit.DecinewtonSecond, "dN·s")] + [InlineData("en-US", ImpulseUnit.KilogramMeterPerSecond, "kg·m/s")] + [InlineData("en-US", ImpulseUnit.KilonewtonSecond, "kN·s")] + [InlineData("en-US", ImpulseUnit.MeganewtonSecond, "MN·s")] + [InlineData("en-US", ImpulseUnit.MicronewtonSecond, "µN·s")] + [InlineData("en-US", ImpulseUnit.MillinewtonSecond, "mN·s")] + [InlineData("en-US", ImpulseUnit.NanonewtonSecond, "nN·s")] + [InlineData("en-US", ImpulseUnit.NewtonSecond, "N·s")] + [InlineData("en-US", ImpulseUnit.PoundFootPerSecond, "lb·ft/s")] + [InlineData("en-US", ImpulseUnit.PoundForceSecond, "lbf·s")] + [InlineData("en-US", ImpulseUnit.SlugFootPerSecond, "slug·ft/s")] + public void GetAbbreviationForCulture(string culture, ImpulseUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Impulse.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Impulse.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Impulse.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ImpulseUnit unit) @@ -754,6 +682,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); }); } @@ -777,44 +706,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] @@ -860,8 +791,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); @@ -899,34 +828,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = Impulse.FromNewtonSeconds(1); - Assert.True(v.Equals(Impulse.FromNewtonSeconds(1), NewtonSecondsTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Impulse.Zero, NewtonSecondsTolerance, ComparisonType.Relative)); - Assert.True(Impulse.FromNewtonSeconds(100).Equals(Impulse.FromNewtonSeconds(120), 0.3, ComparisonType.Relative)); - Assert.False(Impulse.FromNewtonSeconds(100).Equals(Impulse.FromNewtonSeconds(120), 0.1, ComparisonType.Relative)); + Impulse newtonsecond = Impulse.FromNewtonSeconds(1); + Assert.False(newtonsecond.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = Impulse.FromNewtonSeconds(1); - Assert.Throws(() => v.Equals(Impulse.FromNewtonSeconds(1), -1, ComparisonType.Relative)); + Impulse newtonsecond = Impulse.FromNewtonSeconds(1); + Assert.False(newtonsecond.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - Impulse newtonsecond = Impulse.FromNewtonSeconds(1); - Assert.False(newtonsecond.Equals(new object())); + var quantity = Impulse.FromNewtonSeconds(firstValue); + var otherQuantity = Impulse.FromNewtonSeconds(secondValue); + Impulse maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - Impulse newtonsecond = Impulse.FromNewtonSeconds(1); - Assert.False(newtonsecond.Equals(null)); + var quantity = Impulse.FromNewtonSeconds(1); + var negativeTolerance = Impulse.FromNewtonSeconds(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -945,6 +883,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() { @@ -1027,158 +977,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Impulse.FromNewtonSeconds(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Impulse.FromNewtonSeconds(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Impulse.FromNewtonSeconds(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Impulse.FromNewtonSeconds(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Impulse.FromNewtonSeconds(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Impulse.FromNewtonSeconds(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Impulse.FromNewtonSeconds(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Impulse.FromNewtonSeconds(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Impulse.FromNewtonSeconds(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Impulse.FromNewtonSeconds(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Impulse.FromNewtonSeconds(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Impulse.FromNewtonSeconds(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Impulse.FromNewtonSeconds(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Impulse.FromNewtonSeconds(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Impulse.FromNewtonSeconds(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Impulse.FromNewtonSeconds(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Impulse))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Impulse.FromNewtonSeconds(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ImpulseUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Impulse.FromNewtonSeconds(1.0); - Assert.Equal(Impulse.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Impulse.FromNewtonSeconds(1.0); - Assert.Equal(Impulse.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Impulse.FromNewtonSeconds(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Impulse.FromNewtonSeconds(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Impulse.FromNewtonSeconds(1.0); - Assert.Equal(new {Impulse.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 e8bdfe75ad..d250e1444c 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/InformationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/InformationTestsBase.g.cs @@ -188,15 +188,33 @@ public void Ctor_WithNaNValue_DoNotThrowsArgumentException() [Fact] public void Information_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + InformationUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Information(1, InformationUnit.Bit); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Information.Zero, quantityInfo.Zero); Assert.Equal("Information", quantityInfo.Name); + Assert.Equal(Information.Zero, quantityInfo.Zero); + Assert.Equal(Information.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Information.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -235,107 +253,107 @@ public void BitToInformationUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Information.From(1, InformationUnit.Bit); - AssertEx.EqualTolerance(1, quantity00.Bits, BitsTolerance); + Assert.Equal(1, quantity00.Bits); Assert.Equal(InformationUnit.Bit, quantity00.Unit); var quantity01 = Information.From(1, InformationUnit.Byte); - AssertEx.EqualTolerance(1, quantity01.Bytes, BytesTolerance); + Assert.Equal(1, quantity01.Bytes); Assert.Equal(InformationUnit.Byte, quantity01.Unit); var quantity02 = Information.From(1, InformationUnit.Exabit); - AssertEx.EqualTolerance(1, quantity02.Exabits, ExabitsTolerance); + Assert.Equal(1, quantity02.Exabits); Assert.Equal(InformationUnit.Exabit, quantity02.Unit); var quantity03 = Information.From(1, InformationUnit.Exabyte); - AssertEx.EqualTolerance(1, quantity03.Exabytes, ExabytesTolerance); + Assert.Equal(1, quantity03.Exabytes); Assert.Equal(InformationUnit.Exabyte, quantity03.Unit); var quantity04 = Information.From(1, InformationUnit.Exbibit); - AssertEx.EqualTolerance(1, quantity04.Exbibits, ExbibitsTolerance); + Assert.Equal(1, quantity04.Exbibits); Assert.Equal(InformationUnit.Exbibit, quantity04.Unit); var quantity05 = Information.From(1, InformationUnit.Exbibyte); - AssertEx.EqualTolerance(1, quantity05.Exbibytes, ExbibytesTolerance); + Assert.Equal(1, quantity05.Exbibytes); Assert.Equal(InformationUnit.Exbibyte, quantity05.Unit); var quantity06 = Information.From(1, InformationUnit.Gibibit); - AssertEx.EqualTolerance(1, quantity06.Gibibits, GibibitsTolerance); + Assert.Equal(1, quantity06.Gibibits); Assert.Equal(InformationUnit.Gibibit, quantity06.Unit); var quantity07 = Information.From(1, InformationUnit.Gibibyte); - AssertEx.EqualTolerance(1, quantity07.Gibibytes, GibibytesTolerance); + Assert.Equal(1, quantity07.Gibibytes); Assert.Equal(InformationUnit.Gibibyte, quantity07.Unit); var quantity08 = Information.From(1, InformationUnit.Gigabit); - AssertEx.EqualTolerance(1, quantity08.Gigabits, GigabitsTolerance); + Assert.Equal(1, quantity08.Gigabits); Assert.Equal(InformationUnit.Gigabit, quantity08.Unit); var quantity09 = Information.From(1, InformationUnit.Gigabyte); - AssertEx.EqualTolerance(1, quantity09.Gigabytes, GigabytesTolerance); + Assert.Equal(1, quantity09.Gigabytes); Assert.Equal(InformationUnit.Gigabyte, quantity09.Unit); var quantity10 = Information.From(1, InformationUnit.Kibibit); - AssertEx.EqualTolerance(1, quantity10.Kibibits, KibibitsTolerance); + Assert.Equal(1, quantity10.Kibibits); Assert.Equal(InformationUnit.Kibibit, quantity10.Unit); var quantity11 = Information.From(1, InformationUnit.Kibibyte); - AssertEx.EqualTolerance(1, quantity11.Kibibytes, KibibytesTolerance); + Assert.Equal(1, quantity11.Kibibytes); Assert.Equal(InformationUnit.Kibibyte, quantity11.Unit); var quantity12 = Information.From(1, InformationUnit.Kilobit); - AssertEx.EqualTolerance(1, quantity12.Kilobits, KilobitsTolerance); + Assert.Equal(1, quantity12.Kilobits); Assert.Equal(InformationUnit.Kilobit, quantity12.Unit); var quantity13 = Information.From(1, InformationUnit.Kilobyte); - AssertEx.EqualTolerance(1, quantity13.Kilobytes, KilobytesTolerance); + Assert.Equal(1, quantity13.Kilobytes); Assert.Equal(InformationUnit.Kilobyte, quantity13.Unit); var quantity14 = Information.From(1, InformationUnit.Mebibit); - AssertEx.EqualTolerance(1, quantity14.Mebibits, MebibitsTolerance); + Assert.Equal(1, quantity14.Mebibits); Assert.Equal(InformationUnit.Mebibit, quantity14.Unit); var quantity15 = Information.From(1, InformationUnit.Mebibyte); - AssertEx.EqualTolerance(1, quantity15.Mebibytes, MebibytesTolerance); + Assert.Equal(1, quantity15.Mebibytes); Assert.Equal(InformationUnit.Mebibyte, quantity15.Unit); var quantity16 = Information.From(1, InformationUnit.Megabit); - AssertEx.EqualTolerance(1, quantity16.Megabits, MegabitsTolerance); + Assert.Equal(1, quantity16.Megabits); Assert.Equal(InformationUnit.Megabit, quantity16.Unit); var quantity17 = Information.From(1, InformationUnit.Megabyte); - AssertEx.EqualTolerance(1, quantity17.Megabytes, MegabytesTolerance); + Assert.Equal(1, quantity17.Megabytes); Assert.Equal(InformationUnit.Megabyte, quantity17.Unit); var quantity18 = Information.From(1, InformationUnit.Pebibit); - AssertEx.EqualTolerance(1, quantity18.Pebibits, PebibitsTolerance); + Assert.Equal(1, quantity18.Pebibits); Assert.Equal(InformationUnit.Pebibit, quantity18.Unit); var quantity19 = Information.From(1, InformationUnit.Pebibyte); - AssertEx.EqualTolerance(1, quantity19.Pebibytes, PebibytesTolerance); + Assert.Equal(1, quantity19.Pebibytes); Assert.Equal(InformationUnit.Pebibyte, quantity19.Unit); var quantity20 = Information.From(1, InformationUnit.Petabit); - AssertEx.EqualTolerance(1, quantity20.Petabits, PetabitsTolerance); + Assert.Equal(1, quantity20.Petabits); Assert.Equal(InformationUnit.Petabit, quantity20.Unit); var quantity21 = Information.From(1, InformationUnit.Petabyte); - AssertEx.EqualTolerance(1, quantity21.Petabytes, PetabytesTolerance); + Assert.Equal(1, quantity21.Petabytes); Assert.Equal(InformationUnit.Petabyte, quantity21.Unit); var quantity22 = Information.From(1, InformationUnit.Tebibit); - AssertEx.EqualTolerance(1, quantity22.Tebibits, TebibitsTolerance); + Assert.Equal(1, quantity22.Tebibits); Assert.Equal(InformationUnit.Tebibit, quantity22.Unit); var quantity23 = Information.From(1, InformationUnit.Tebibyte); - AssertEx.EqualTolerance(1, quantity23.Tebibytes, TebibytesTolerance); + Assert.Equal(1, quantity23.Tebibytes); Assert.Equal(InformationUnit.Tebibyte, quantity23.Unit); var quantity24 = Information.From(1, InformationUnit.Terabit); - AssertEx.EqualTolerance(1, quantity24.Terabits, TerabitsTolerance); + Assert.Equal(1, quantity24.Terabits); Assert.Equal(InformationUnit.Terabit, quantity24.Unit); var quantity25 = Information.From(1, InformationUnit.Terabyte); - AssertEx.EqualTolerance(1, quantity25.Terabytes, TerabytesTolerance); + Assert.Equal(1, quantity25.Terabytes); Assert.Equal(InformationUnit.Terabyte, quantity25.Unit); } @@ -457,196 +475,74 @@ public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 b", InformationUnit.Bit, 4.2)] + [InlineData("en-US", "4.2 B", InformationUnit.Byte, 4.2)] + [InlineData("en-US", "4.2 Eb", InformationUnit.Exabit, 4.2)] + [InlineData("en-US", "4.2 EB", InformationUnit.Exabyte, 4.2)] + [InlineData("en-US", "4.2 Eib", InformationUnit.Exbibit, 4.2)] + [InlineData("en-US", "4.2 EiB", InformationUnit.Exbibyte, 4.2)] + [InlineData("en-US", "4.2 Gib", InformationUnit.Gibibit, 4.2)] + [InlineData("en-US", "4.2 GiB", InformationUnit.Gibibyte, 4.2)] + [InlineData("en-US", "4.2 Gb", InformationUnit.Gigabit, 4.2)] + [InlineData("en-US", "4.2 GB", InformationUnit.Gigabyte, 4.2)] + [InlineData("en-US", "4.2 Kib", InformationUnit.Kibibit, 4.2)] + [InlineData("en-US", "4.2 KiB", InformationUnit.Kibibyte, 4.2)] + [InlineData("en-US", "4.2 kb", InformationUnit.Kilobit, 4.2)] + [InlineData("en-US", "4.2 kB", InformationUnit.Kilobyte, 4.2)] + [InlineData("en-US", "4.2 Mib", InformationUnit.Mebibit, 4.2)] + [InlineData("en-US", "4.2 MiB", InformationUnit.Mebibyte, 4.2)] + [InlineData("en-US", "4.2 Mb", InformationUnit.Megabit, 4.2)] + [InlineData("en-US", "4.2 MB", InformationUnit.Megabyte, 4.2)] + [InlineData("en-US", "4.2 Pib", InformationUnit.Pebibit, 4.2)] + [InlineData("en-US", "4.2 PiB", InformationUnit.Pebibyte, 4.2)] + [InlineData("en-US", "4.2 Pb", InformationUnit.Petabit, 4.2)] + [InlineData("en-US", "4.2 PB", InformationUnit.Petabyte, 4.2)] + [InlineData("en-US", "4.2 Tib", InformationUnit.Tebibit, 4.2)] + [InlineData("en-US", "4.2 TiB", InformationUnit.Tebibyte, 4.2)] + [InlineData("en-US", "4.2 Tb", InformationUnit.Terabit, 4.2)] + [InlineData("en-US", "4.2 TB", InformationUnit.Terabyte, 4.2)] + public void Parse(string culture, string quantityString, InformationUnit expectedUnit, decimal expectedValue) { - try - { - var parsed = Information.Parse("1 b", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Bits, BitsTolerance); - Assert.Equal(InformationUnit.Bit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Information.Parse("1 B", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Bytes, BytesTolerance); - Assert.Equal(InformationUnit.Byte, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Information.Parse("1 Eb", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Exabits, ExabitsTolerance); - Assert.Equal(InformationUnit.Exabit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Information.Parse("1 EB", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Exabytes, ExabytesTolerance); - Assert.Equal(InformationUnit.Exabyte, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Information.Parse("1 Eib", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Exbibits, ExbibitsTolerance); - Assert.Equal(InformationUnit.Exbibit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Information.Parse("1 EiB", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Exbibytes, ExbibytesTolerance); - Assert.Equal(InformationUnit.Exbibyte, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Information.Parse("1 Gib", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Gibibits, GibibitsTolerance); - Assert.Equal(InformationUnit.Gibibit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Information.Parse("1 GiB", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Gibibytes, GibibytesTolerance); - Assert.Equal(InformationUnit.Gibibyte, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Information.Parse("1 Gb", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Gigabits, GigabitsTolerance); - Assert.Equal(InformationUnit.Gigabit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Information.Parse("1 GB", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Gigabytes, GigabytesTolerance); - Assert.Equal(InformationUnit.Gigabyte, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Information.Parse("1 Kib", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kibibits, KibibitsTolerance); - Assert.Equal(InformationUnit.Kibibit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Information.Parse("1 KiB", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kibibytes, KibibytesTolerance); - Assert.Equal(InformationUnit.Kibibyte, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Information.Parse("1 kb", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilobits, KilobitsTolerance); - Assert.Equal(InformationUnit.Kilobit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Information.Parse("1 kB", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilobytes, KilobytesTolerance); - Assert.Equal(InformationUnit.Kilobyte, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Information.Parse("1 Mib", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Mebibits, MebibitsTolerance); - Assert.Equal(InformationUnit.Mebibit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Information.Parse("1 MiB", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Mebibytes, MebibytesTolerance); - Assert.Equal(InformationUnit.Mebibyte, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Information.Parse("1 Mb", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megabits, MegabitsTolerance); - Assert.Equal(InformationUnit.Megabit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Information.Parse("1 MB", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megabytes, MegabytesTolerance); - Assert.Equal(InformationUnit.Megabyte, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Information.Parse("1 Pib", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Pebibits, PebibitsTolerance); - Assert.Equal(InformationUnit.Pebibit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Information.Parse("1 PiB", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Pebibytes, PebibytesTolerance); - Assert.Equal(InformationUnit.Pebibyte, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Information.Parse("1 Pb", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Petabits, PetabitsTolerance); - Assert.Equal(InformationUnit.Petabit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Information.Parse("1 PB", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Petabytes, PetabytesTolerance); - Assert.Equal(InformationUnit.Petabyte, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Information.Parse("1 Tib", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Tebibits, TebibitsTolerance); - Assert.Equal(InformationUnit.Tebibit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Information.Parse("1 TiB", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Tebibytes, TebibytesTolerance); - Assert.Equal(InformationUnit.Tebibyte, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Information.Parse("1 Tb", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Terabits, TerabitsTolerance); - Assert.Equal(InformationUnit.Terabit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Information.Parse("1 TB", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Terabytes, TerabytesTolerance); - Assert.Equal(InformationUnit.Terabyte, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Information.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 b", InformationUnit.Bit, 4.2)] + [InlineData("en-US", "4.2 B", InformationUnit.Byte, 4.2)] + [InlineData("en-US", "4.2 Eb", InformationUnit.Exabit, 4.2)] + [InlineData("en-US", "4.2 EB", InformationUnit.Exabyte, 4.2)] + [InlineData("en-US", "4.2 Eib", InformationUnit.Exbibit, 4.2)] + [InlineData("en-US", "4.2 EiB", InformationUnit.Exbibyte, 4.2)] + [InlineData("en-US", "4.2 Gib", InformationUnit.Gibibit, 4.2)] + [InlineData("en-US", "4.2 GiB", InformationUnit.Gibibyte, 4.2)] + [InlineData("en-US", "4.2 Gb", InformationUnit.Gigabit, 4.2)] + [InlineData("en-US", "4.2 GB", InformationUnit.Gigabyte, 4.2)] + [InlineData("en-US", "4.2 Kib", InformationUnit.Kibibit, 4.2)] + [InlineData("en-US", "4.2 KiB", InformationUnit.Kibibyte, 4.2)] + [InlineData("en-US", "4.2 kb", InformationUnit.Kilobit, 4.2)] + [InlineData("en-US", "4.2 kB", InformationUnit.Kilobyte, 4.2)] + [InlineData("en-US", "4.2 Mib", InformationUnit.Mebibit, 4.2)] + [InlineData("en-US", "4.2 MiB", InformationUnit.Mebibyte, 4.2)] + [InlineData("en-US", "4.2 Mb", InformationUnit.Megabit, 4.2)] + [InlineData("en-US", "4.2 MB", InformationUnit.Megabyte, 4.2)] + [InlineData("en-US", "4.2 Pib", InformationUnit.Pebibit, 4.2)] + [InlineData("en-US", "4.2 PiB", InformationUnit.Pebibyte, 4.2)] + [InlineData("en-US", "4.2 Pb", InformationUnit.Petabit, 4.2)] + [InlineData("en-US", "4.2 PB", InformationUnit.Petabyte, 4.2)] + [InlineData("en-US", "4.2 Tib", InformationUnit.Tebibit, 4.2)] + [InlineData("en-US", "4.2 TiB", InformationUnit.Tebibyte, 4.2)] + [InlineData("en-US", "4.2 Tb", InformationUnit.Terabit, 4.2)] + [InlineData("en-US", "4.2 TB", InformationUnit.Terabyte, 4.2)] + public void TryParse(string culture, string quantityString, InformationUnit expectedUnit, decimal expectedValue) { + using var _ = new CultureScope(culture); + Assert.True(Information.TryParse(quantityString, out Information parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -923,6 +819,52 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Inform Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", InformationUnit.Bit, "b")] + [InlineData("en-US", InformationUnit.Byte, "B")] + [InlineData("en-US", InformationUnit.Exabit, "Eb")] + [InlineData("en-US", InformationUnit.Exabyte, "EB")] + [InlineData("en-US", InformationUnit.Exbibit, "Eib")] + [InlineData("en-US", InformationUnit.Exbibyte, "EiB")] + [InlineData("en-US", InformationUnit.Gibibit, "Gib")] + [InlineData("en-US", InformationUnit.Gibibyte, "GiB")] + [InlineData("en-US", InformationUnit.Gigabit, "Gb")] + [InlineData("en-US", InformationUnit.Gigabyte, "GB")] + [InlineData("en-US", InformationUnit.Kibibit, "Kib")] + [InlineData("en-US", InformationUnit.Kibibyte, "KiB")] + [InlineData("en-US", InformationUnit.Kilobit, "kb")] + [InlineData("en-US", InformationUnit.Kilobyte, "kB")] + [InlineData("en-US", InformationUnit.Mebibit, "Mib")] + [InlineData("en-US", InformationUnit.Mebibyte, "MiB")] + [InlineData("en-US", InformationUnit.Megabit, "Mb")] + [InlineData("en-US", InformationUnit.Megabyte, "MB")] + [InlineData("en-US", InformationUnit.Pebibit, "Pib")] + [InlineData("en-US", InformationUnit.Pebibyte, "PiB")] + [InlineData("en-US", InformationUnit.Petabit, "Pb")] + [InlineData("en-US", InformationUnit.Petabyte, "PB")] + [InlineData("en-US", InformationUnit.Tebibit, "Tib")] + [InlineData("en-US", InformationUnit.Tebibyte, "TiB")] + [InlineData("en-US", InformationUnit.Terabit, "Tb")] + [InlineData("en-US", InformationUnit.Terabyte, "TB")] + public void GetAbbreviationForCulture(string culture, InformationUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Information.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Information.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Information.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(InformationUnit unit) @@ -953,6 +895,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); }); } @@ -976,57 +919,59 @@ 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.FromExbibits(bit.Exbibits).Bits, ExbibitsTolerance); - AssertEx.EqualTolerance(1, Information.FromExbibytes(bit.Exbibytes).Bits, ExbibytesTolerance); - AssertEx.EqualTolerance(1, Information.FromGibibits(bit.Gibibits).Bits, GibibitsTolerance); - AssertEx.EqualTolerance(1, Information.FromGibibytes(bit.Gibibytes).Bits, GibibytesTolerance); - AssertEx.EqualTolerance(1, Information.FromGigabits(bit.Gigabits).Bits, GigabitsTolerance); - AssertEx.EqualTolerance(1, Information.FromGigabytes(bit.Gigabytes).Bits, GigabytesTolerance); - AssertEx.EqualTolerance(1, Information.FromKibibits(bit.Kibibits).Bits, KibibitsTolerance); - AssertEx.EqualTolerance(1, Information.FromKibibytes(bit.Kibibytes).Bits, KibibytesTolerance); - AssertEx.EqualTolerance(1, Information.FromKilobits(bit.Kilobits).Bits, KilobitsTolerance); - AssertEx.EqualTolerance(1, Information.FromKilobytes(bit.Kilobytes).Bits, KilobytesTolerance); - AssertEx.EqualTolerance(1, Information.FromMebibits(bit.Mebibits).Bits, MebibitsTolerance); - AssertEx.EqualTolerance(1, Information.FromMebibytes(bit.Mebibytes).Bits, MebibytesTolerance); - AssertEx.EqualTolerance(1, Information.FromMegabits(bit.Megabits).Bits, MegabitsTolerance); - AssertEx.EqualTolerance(1, Information.FromMegabytes(bit.Megabytes).Bits, MegabytesTolerance); - AssertEx.EqualTolerance(1, Information.FromPebibits(bit.Pebibits).Bits, PebibitsTolerance); - AssertEx.EqualTolerance(1, Information.FromPebibytes(bit.Pebibytes).Bits, PebibytesTolerance); - AssertEx.EqualTolerance(1, Information.FromPetabits(bit.Petabits).Bits, PetabitsTolerance); - AssertEx.EqualTolerance(1, Information.FromPetabytes(bit.Petabytes).Bits, PetabytesTolerance); - AssertEx.EqualTolerance(1, Information.FromTebibits(bit.Tebibits).Bits, TebibitsTolerance); - AssertEx.EqualTolerance(1, Information.FromTebibytes(bit.Tebibytes).Bits, TebibytesTolerance); - AssertEx.EqualTolerance(1, Information.FromTerabits(bit.Terabits).Bits, TerabitsTolerance); - AssertEx.EqualTolerance(1, Information.FromTerabytes(bit.Terabytes).Bits, TerabytesTolerance); + 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.FromExbibits(bit.Exbibits).Bits); + Assert.Equal(3, Information.FromExbibytes(bit.Exbibytes).Bits); + Assert.Equal(3, Information.FromGibibits(bit.Gibibits).Bits); + Assert.Equal(3, Information.FromGibibytes(bit.Gibibytes).Bits); + Assert.Equal(3, Information.FromGigabits(bit.Gigabits).Bits); + Assert.Equal(3, Information.FromGigabytes(bit.Gigabytes).Bits); + Assert.Equal(3, Information.FromKibibits(bit.Kibibits).Bits); + Assert.Equal(3, Information.FromKibibytes(bit.Kibibytes).Bits); + Assert.Equal(3, Information.FromKilobits(bit.Kilobits).Bits); + Assert.Equal(3, Information.FromKilobytes(bit.Kilobytes).Bits); + Assert.Equal(3, Information.FromMebibits(bit.Mebibits).Bits); + Assert.Equal(3, Information.FromMebibytes(bit.Mebibytes).Bits); + Assert.Equal(3, Information.FromMegabits(bit.Megabits).Bits); + Assert.Equal(3, Information.FromMegabytes(bit.Megabytes).Bits); + Assert.Equal(3, Information.FromPebibits(bit.Pebibits).Bits); + Assert.Equal(3, Information.FromPebibytes(bit.Pebibytes).Bits); + Assert.Equal(3, Information.FromPetabits(bit.Petabits).Bits); + Assert.Equal(3, Information.FromPetabytes(bit.Petabytes).Bits); + Assert.Equal(3, Information.FromTebibits(bit.Tebibits).Bits); + Assert.Equal(3, Information.FromTebibytes(bit.Tebibytes).Bits); + Assert.Equal(3, Information.FromTerabits(bit.Terabits).Bits); + Assert.Equal(3, Information.FromTerabytes(bit.Terabytes).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] @@ -1072,8 +1017,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); @@ -1110,23 +1053,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = Information.FromBits(1); - Assert.True(v.Equals(Information.FromBits(1), BitsTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Information.Zero, BitsTolerance, ComparisonType.Relative)); - Assert.True(Information.FromBits(100).Equals(Information.FromBits(120), 0.3, ComparisonType.Relative)); - Assert.False(Information.FromBits(100).Equals(Information.FromBits(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = Information.FromBits(1); - Assert.Throws(() => v.Equals(Information.FromBits(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1141,6 +1067,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(bit.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = Information.FromBits(1); + var negativeTolerance = Information.FromBits(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1157,6 +1109,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() { @@ -1265,158 +1229,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Information.FromBits(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Information.FromBits(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Information.FromBits(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Information.FromBits(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Information.FromBits(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Information.FromBits(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Information.FromBits(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Information.FromBits(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Information.FromBits(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Information.FromBits(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Information.FromBits(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Information.FromBits(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Information.FromBits(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Information.FromBits(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Information.FromBits(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Information.FromBits(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Information))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Information.FromBits(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(InformationUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Information.FromBits(1.0); - Assert.Equal(Information.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Information.FromBits(1.0); - Assert.Equal(Information.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Information.FromBits(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Information.FromBits(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Information.FromBits(1.0); - Assert.Equal(new {Information.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 24026609c5..06f1309c34 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/IrradianceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/IrradianceTestsBase.g.cs @@ -148,7 +148,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Irradiance(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -161,15 +161,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Irradiance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + IrradianceUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Irradiance(1, IrradianceUnit.WattPerSquareMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Irradiance.Zero, quantityInfo.Zero); Assert.Equal("Irradiance", quantityInfo.Name); + Assert.Equal(Irradiance.Zero, quantityInfo.Zero); + Assert.Equal(Irradiance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Irradiance.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -196,59 +214,59 @@ public void WattPerSquareMeterToIrradianceUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Irradiance.From(1, IrradianceUnit.KilowattPerSquareCentimeter); - AssertEx.EqualTolerance(1, quantity00.KilowattsPerSquareCentimeter, KilowattsPerSquareCentimeterTolerance); + Assert.Equal(1, quantity00.KilowattsPerSquareCentimeter); Assert.Equal(IrradianceUnit.KilowattPerSquareCentimeter, quantity00.Unit); var quantity01 = Irradiance.From(1, IrradianceUnit.KilowattPerSquareMeter); - AssertEx.EqualTolerance(1, quantity01.KilowattsPerSquareMeter, KilowattsPerSquareMeterTolerance); + Assert.Equal(1, quantity01.KilowattsPerSquareMeter); Assert.Equal(IrradianceUnit.KilowattPerSquareMeter, quantity01.Unit); var quantity02 = Irradiance.From(1, IrradianceUnit.MegawattPerSquareCentimeter); - AssertEx.EqualTolerance(1, quantity02.MegawattsPerSquareCentimeter, MegawattsPerSquareCentimeterTolerance); + Assert.Equal(1, quantity02.MegawattsPerSquareCentimeter); Assert.Equal(IrradianceUnit.MegawattPerSquareCentimeter, quantity02.Unit); var quantity03 = Irradiance.From(1, IrradianceUnit.MegawattPerSquareMeter); - AssertEx.EqualTolerance(1, quantity03.MegawattsPerSquareMeter, MegawattsPerSquareMeterTolerance); + Assert.Equal(1, quantity03.MegawattsPerSquareMeter); Assert.Equal(IrradianceUnit.MegawattPerSquareMeter, quantity03.Unit); var quantity04 = Irradiance.From(1, IrradianceUnit.MicrowattPerSquareCentimeter); - AssertEx.EqualTolerance(1, quantity04.MicrowattsPerSquareCentimeter, MicrowattsPerSquareCentimeterTolerance); + Assert.Equal(1, quantity04.MicrowattsPerSquareCentimeter); Assert.Equal(IrradianceUnit.MicrowattPerSquareCentimeter, quantity04.Unit); var quantity05 = Irradiance.From(1, IrradianceUnit.MicrowattPerSquareMeter); - AssertEx.EqualTolerance(1, quantity05.MicrowattsPerSquareMeter, MicrowattsPerSquareMeterTolerance); + Assert.Equal(1, quantity05.MicrowattsPerSquareMeter); Assert.Equal(IrradianceUnit.MicrowattPerSquareMeter, quantity05.Unit); var quantity06 = Irradiance.From(1, IrradianceUnit.MilliwattPerSquareCentimeter); - AssertEx.EqualTolerance(1, quantity06.MilliwattsPerSquareCentimeter, MilliwattsPerSquareCentimeterTolerance); + Assert.Equal(1, quantity06.MilliwattsPerSquareCentimeter); Assert.Equal(IrradianceUnit.MilliwattPerSquareCentimeter, quantity06.Unit); var quantity07 = Irradiance.From(1, IrradianceUnit.MilliwattPerSquareMeter); - AssertEx.EqualTolerance(1, quantity07.MilliwattsPerSquareMeter, MilliwattsPerSquareMeterTolerance); + Assert.Equal(1, quantity07.MilliwattsPerSquareMeter); Assert.Equal(IrradianceUnit.MilliwattPerSquareMeter, quantity07.Unit); var quantity08 = Irradiance.From(1, IrradianceUnit.NanowattPerSquareCentimeter); - AssertEx.EqualTolerance(1, quantity08.NanowattsPerSquareCentimeter, NanowattsPerSquareCentimeterTolerance); + Assert.Equal(1, quantity08.NanowattsPerSquareCentimeter); Assert.Equal(IrradianceUnit.NanowattPerSquareCentimeter, quantity08.Unit); var quantity09 = Irradiance.From(1, IrradianceUnit.NanowattPerSquareMeter); - AssertEx.EqualTolerance(1, quantity09.NanowattsPerSquareMeter, NanowattsPerSquareMeterTolerance); + Assert.Equal(1, quantity09.NanowattsPerSquareMeter); Assert.Equal(IrradianceUnit.NanowattPerSquareMeter, quantity09.Unit); var quantity10 = Irradiance.From(1, IrradianceUnit.PicowattPerSquareCentimeter); - AssertEx.EqualTolerance(1, quantity10.PicowattsPerSquareCentimeter, PicowattsPerSquareCentimeterTolerance); + Assert.Equal(1, quantity10.PicowattsPerSquareCentimeter); Assert.Equal(IrradianceUnit.PicowattPerSquareCentimeter, quantity10.Unit); var quantity11 = Irradiance.From(1, IrradianceUnit.PicowattPerSquareMeter); - AssertEx.EqualTolerance(1, quantity11.PicowattsPerSquareMeter, PicowattsPerSquareMeterTolerance); + Assert.Equal(1, quantity11.PicowattsPerSquareMeter); Assert.Equal(IrradianceUnit.PicowattPerSquareMeter, quantity11.Unit); var quantity12 = Irradiance.From(1, IrradianceUnit.WattPerSquareCentimeter); - AssertEx.EqualTolerance(1, quantity12.WattsPerSquareCentimeter, WattsPerSquareCentimeterTolerance); + Assert.Equal(1, quantity12.WattsPerSquareCentimeter); Assert.Equal(IrradianceUnit.WattPerSquareCentimeter, quantity12.Unit); var quantity13 = Irradiance.From(1, IrradianceUnit.WattPerSquareMeter); - AssertEx.EqualTolerance(1, quantity13.WattsPerSquareMeter, WattsPerSquareMeterTolerance); + Assert.Equal(1, quantity13.WattsPerSquareMeter); Assert.Equal(IrradianceUnit.WattPerSquareMeter, quantity13.Unit); } @@ -397,172 +415,50 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 kW/cm²", IrradianceUnit.KilowattPerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 kW/m²", IrradianceUnit.KilowattPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 MW/cm²", IrradianceUnit.MegawattPerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 MW/m²", IrradianceUnit.MegawattPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 µW/cm²", IrradianceUnit.MicrowattPerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 µW/m²", IrradianceUnit.MicrowattPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 mW/cm²", IrradianceUnit.MilliwattPerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 mW/m²", IrradianceUnit.MilliwattPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 nW/cm²", IrradianceUnit.NanowattPerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 nW/m²", IrradianceUnit.NanowattPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 pW/cm²", IrradianceUnit.PicowattPerSquareCentimeter, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = Irradiance.Parse("1 kW/cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilowattsPerSquareCentimeter, KilowattsPerSquareCentimeterTolerance); - Assert.Equal(IrradianceUnit.KilowattPerSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Irradiance.Parse("1 kW/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilowattsPerSquareMeter, KilowattsPerSquareMeterTolerance); - Assert.Equal(IrradianceUnit.KilowattPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Irradiance.Parse("1 MW/cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegawattsPerSquareCentimeter, MegawattsPerSquareCentimeterTolerance); - Assert.Equal(IrradianceUnit.MegawattPerSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Irradiance.Parse("1 MW/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegawattsPerSquareMeter, MegawattsPerSquareMeterTolerance); - Assert.Equal(IrradianceUnit.MegawattPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Irradiance.Parse("1 µW/cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrowattsPerSquareCentimeter, MicrowattsPerSquareCentimeterTolerance); - Assert.Equal(IrradianceUnit.MicrowattPerSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Irradiance.Parse("1 µW/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrowattsPerSquareMeter, MicrowattsPerSquareMeterTolerance); - Assert.Equal(IrradianceUnit.MicrowattPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Irradiance.Parse("1 mW/cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilliwattsPerSquareCentimeter, MilliwattsPerSquareCentimeterTolerance); - Assert.Equal(IrradianceUnit.MilliwattPerSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Irradiance.Parse("1 mW/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilliwattsPerSquareMeter, MilliwattsPerSquareMeterTolerance); - Assert.Equal(IrradianceUnit.MilliwattPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Irradiance.Parse("1 nW/cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanowattsPerSquareCentimeter, NanowattsPerSquareCentimeterTolerance); - Assert.Equal(IrradianceUnit.NanowattPerSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Irradiance.Parse("1 nW/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanowattsPerSquareMeter, NanowattsPerSquareMeterTolerance); - Assert.Equal(IrradianceUnit.NanowattPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Irradiance.Parse("1 pW/cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PicowattsPerSquareCentimeter, PicowattsPerSquareCentimeterTolerance); - Assert.Equal(IrradianceUnit.PicowattPerSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Irradiance.Parse("1 pW/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PicowattsPerSquareMeter, PicowattsPerSquareMeterTolerance); - Assert.Equal(IrradianceUnit.PicowattPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Irradiance.Parse("1 W/cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WattsPerSquareCentimeter, WattsPerSquareCentimeterTolerance); - Assert.Equal(IrradianceUnit.WattPerSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Irradiance.Parse("1 W/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WattsPerSquareMeter, WattsPerSquareMeterTolerance); - Assert.Equal(IrradianceUnit.WattPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Irradiance.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 kW/cm²", IrradianceUnit.KilowattPerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 kW/m²", IrradianceUnit.KilowattPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 MW/cm²", IrradianceUnit.MegawattPerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 MW/m²", IrradianceUnit.MegawattPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 µW/cm²", IrradianceUnit.MicrowattPerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 µW/m²", IrradianceUnit.MicrowattPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 mW/cm²", IrradianceUnit.MilliwattPerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 mW/m²", IrradianceUnit.MilliwattPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 nW/cm²", IrradianceUnit.NanowattPerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 nW/m²", IrradianceUnit.NanowattPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 pW/cm²", IrradianceUnit.PicowattPerSquareCentimeter, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(Irradiance.TryParse("1 kW/cm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilowattsPerSquareCentimeter, KilowattsPerSquareCentimeterTolerance); - Assert.Equal(IrradianceUnit.KilowattPerSquareCentimeter, parsed.Unit); - } - - { - Assert.True(Irradiance.TryParse("1 kW/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilowattsPerSquareMeter, KilowattsPerSquareMeterTolerance); - Assert.Equal(IrradianceUnit.KilowattPerSquareMeter, parsed.Unit); - } - - { - Assert.True(Irradiance.TryParse("1 µW/cm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrowattsPerSquareCentimeter, MicrowattsPerSquareCentimeterTolerance); - Assert.Equal(IrradianceUnit.MicrowattPerSquareCentimeter, parsed.Unit); - } - - { - Assert.True(Irradiance.TryParse("1 µW/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrowattsPerSquareMeter, MicrowattsPerSquareMeterTolerance); - Assert.Equal(IrradianceUnit.MicrowattPerSquareMeter, parsed.Unit); - } - - { - Assert.True(Irradiance.TryParse("1 nW/cm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanowattsPerSquareCentimeter, NanowattsPerSquareCentimeterTolerance); - Assert.Equal(IrradianceUnit.NanowattPerSquareCentimeter, parsed.Unit); - } - - { - Assert.True(Irradiance.TryParse("1 nW/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanowattsPerSquareMeter, NanowattsPerSquareMeterTolerance); - Assert.Equal(IrradianceUnit.NanowattPerSquareMeter, parsed.Unit); - } - - { - Assert.True(Irradiance.TryParse("1 pW/cm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PicowattsPerSquareCentimeter, PicowattsPerSquareCentimeterTolerance); - Assert.Equal(IrradianceUnit.PicowattPerSquareCentimeter, parsed.Unit); - } - - { - Assert.True(Irradiance.TryParse("1 pW/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PicowattsPerSquareMeter, PicowattsPerSquareMeterTolerance); - Assert.Equal(IrradianceUnit.PicowattPerSquareMeter, parsed.Unit); - } - - { - Assert.True(Irradiance.TryParse("1 W/cm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattsPerSquareCentimeter, WattsPerSquareCentimeterTolerance); - Assert.Equal(IrradianceUnit.WattPerSquareCentimeter, parsed.Unit); - } - - { - Assert.True(Irradiance.TryParse("1 W/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattsPerSquareMeter, WattsPerSquareMeterTolerance); - Assert.Equal(IrradianceUnit.WattPerSquareMeter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Irradiance.TryParse(quantityString, out Irradiance parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -743,6 +639,40 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Irradi Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", IrradianceUnit.KilowattPerSquareCentimeter, "kW/cm²")] + [InlineData("en-US", IrradianceUnit.KilowattPerSquareMeter, "kW/m²")] + [InlineData("en-US", IrradianceUnit.MegawattPerSquareCentimeter, "MW/cm²")] + [InlineData("en-US", IrradianceUnit.MegawattPerSquareMeter, "MW/m²")] + [InlineData("en-US", IrradianceUnit.MicrowattPerSquareCentimeter, "µW/cm²")] + [InlineData("en-US", IrradianceUnit.MicrowattPerSquareMeter, "µW/m²")] + [InlineData("en-US", IrradianceUnit.MilliwattPerSquareCentimeter, "mW/cm²")] + [InlineData("en-US", IrradianceUnit.MilliwattPerSquareMeter, "mW/m²")] + [InlineData("en-US", IrradianceUnit.NanowattPerSquareCentimeter, "nW/cm²")] + [InlineData("en-US", IrradianceUnit.NanowattPerSquareMeter, "nW/m²")] + [InlineData("en-US", IrradianceUnit.PicowattPerSquareCentimeter, "pW/cm²")] + [InlineData("en-US", IrradianceUnit.PicowattPerSquareMeter, "pW/m²")] + [InlineData("en-US", IrradianceUnit.WattPerSquareCentimeter, "W/cm²")] + [InlineData("en-US", IrradianceUnit.WattPerSquareMeter, "W/m²")] + public void GetAbbreviationForCulture(string culture, IrradianceUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Irradiance.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Irradiance.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Irradiance.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(IrradianceUnit unit) @@ -773,6 +703,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); }); } @@ -796,45 +727,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] @@ -880,8 +813,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); @@ -919,34 +850,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = Irradiance.FromWattsPerSquareMeter(1); - Assert.True(v.Equals(Irradiance.FromWattsPerSquareMeter(1), WattsPerSquareMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Irradiance.Zero, WattsPerSquareMeterTolerance, ComparisonType.Relative)); - Assert.True(Irradiance.FromWattsPerSquareMeter(100).Equals(Irradiance.FromWattsPerSquareMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(Irradiance.FromWattsPerSquareMeter(100).Equals(Irradiance.FromWattsPerSquareMeter(120), 0.1, ComparisonType.Relative)); + Irradiance wattpersquaremeter = Irradiance.FromWattsPerSquareMeter(1); + Assert.False(wattpersquaremeter.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = Irradiance.FromWattsPerSquareMeter(1); - Assert.Throws(() => v.Equals(Irradiance.FromWattsPerSquareMeter(1), -1, ComparisonType.Relative)); + Irradiance wattpersquaremeter = Irradiance.FromWattsPerSquareMeter(1); + Assert.False(wattpersquaremeter.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - Irradiance wattpersquaremeter = Irradiance.FromWattsPerSquareMeter(1); - Assert.False(wattpersquaremeter.Equals(new object())); + var quantity = Irradiance.FromWattsPerSquareMeter(firstValue); + var otherQuantity = Irradiance.FromWattsPerSquareMeter(secondValue); + Irradiance maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - Irradiance wattpersquaremeter = Irradiance.FromWattsPerSquareMeter(1); - Assert.False(wattpersquaremeter.Equals(null)); + var quantity = Irradiance.FromWattsPerSquareMeter(1); + var negativeTolerance = Irradiance.FromWattsPerSquareMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -965,6 +905,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() { @@ -1049,158 +1001,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Irradiance))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(IrradianceUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal(Irradiance.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal(Irradiance.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal(new {Irradiance.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 a1946bd78b..d8c172c350 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/IrradiationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/IrradiationTestsBase.g.cs @@ -128,7 +128,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Irradiation(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -141,15 +141,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Irradiation_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + IrradiationUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Irradiation(1, IrradiationUnit.JoulePerSquareMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Irradiation.Zero, quantityInfo.Zero); Assert.Equal("Irradiation", quantityInfo.Name); + Assert.Equal(Irradiation.Zero, quantityInfo.Zero); + Assert.Equal(Irradiation.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Irradiation.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -171,39 +189,39 @@ public void JoulePerSquareMeterToIrradiationUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Irradiation.From(1, IrradiationUnit.BtuPerSquareFoot); - AssertEx.EqualTolerance(1, quantity00.BtusPerSquareFoot, BtusPerSquareFootTolerance); + Assert.Equal(1, quantity00.BtusPerSquareFoot); Assert.Equal(IrradiationUnit.BtuPerSquareFoot, quantity00.Unit); var quantity01 = Irradiation.From(1, IrradiationUnit.JoulePerSquareCentimeter); - AssertEx.EqualTolerance(1, quantity01.JoulesPerSquareCentimeter, JoulesPerSquareCentimeterTolerance); + Assert.Equal(1, quantity01.JoulesPerSquareCentimeter); Assert.Equal(IrradiationUnit.JoulePerSquareCentimeter, quantity01.Unit); var quantity02 = Irradiation.From(1, IrradiationUnit.JoulePerSquareMeter); - AssertEx.EqualTolerance(1, quantity02.JoulesPerSquareMeter, JoulesPerSquareMeterTolerance); + Assert.Equal(1, quantity02.JoulesPerSquareMeter); Assert.Equal(IrradiationUnit.JoulePerSquareMeter, quantity02.Unit); var quantity03 = Irradiation.From(1, IrradiationUnit.JoulePerSquareMillimeter); - AssertEx.EqualTolerance(1, quantity03.JoulesPerSquareMillimeter, JoulesPerSquareMillimeterTolerance); + Assert.Equal(1, quantity03.JoulesPerSquareMillimeter); Assert.Equal(IrradiationUnit.JoulePerSquareMillimeter, quantity03.Unit); var quantity04 = Irradiation.From(1, IrradiationUnit.KilobtuPerSquareFoot); - AssertEx.EqualTolerance(1, quantity04.KilobtusPerSquareFoot, KilobtusPerSquareFootTolerance); + Assert.Equal(1, quantity04.KilobtusPerSquareFoot); Assert.Equal(IrradiationUnit.KilobtuPerSquareFoot, quantity04.Unit); var quantity05 = Irradiation.From(1, IrradiationUnit.KilojoulePerSquareMeter); - AssertEx.EqualTolerance(1, quantity05.KilojoulesPerSquareMeter, KilojoulesPerSquareMeterTolerance); + Assert.Equal(1, quantity05.KilojoulesPerSquareMeter); Assert.Equal(IrradiationUnit.KilojoulePerSquareMeter, quantity05.Unit); var quantity06 = Irradiation.From(1, IrradiationUnit.KilowattHourPerSquareMeter); - AssertEx.EqualTolerance(1, quantity06.KilowattHoursPerSquareMeter, KilowattHoursPerSquareMeterTolerance); + Assert.Equal(1, quantity06.KilowattHoursPerSquareMeter); Assert.Equal(IrradiationUnit.KilowattHourPerSquareMeter, quantity06.Unit); var quantity07 = Irradiation.From(1, IrradiationUnit.MillijoulePerSquareCentimeter); - AssertEx.EqualTolerance(1, quantity07.MillijoulesPerSquareCentimeter, MillijoulesPerSquareCentimeterTolerance); + Assert.Equal(1, quantity07.MillijoulesPerSquareCentimeter); Assert.Equal(IrradiationUnit.MillijoulePerSquareCentimeter, quantity07.Unit); var quantity08 = Irradiation.From(1, IrradiationUnit.WattHourPerSquareMeter); - AssertEx.EqualTolerance(1, quantity08.WattHoursPerSquareMeter, WattHoursPerSquareMeterTolerance); + Assert.Equal(1, quantity08.WattHoursPerSquareMeter); Assert.Equal(IrradiationUnit.WattHourPerSquareMeter, quantity08.Unit); } @@ -347,131 +365,40 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 Btu/ft²", IrradiationUnit.BtuPerSquareFoot, 4.2)] + [InlineData("en-US", "4.2 J/cm²", IrradiationUnit.JoulePerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 J/m²", IrradiationUnit.JoulePerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 J/mm²", IrradiationUnit.JoulePerSquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 kBtu/ft²", IrradiationUnit.KilobtuPerSquareFoot, 4.2)] + [InlineData("en-US", "4.2 kJ/m²", IrradiationUnit.KilojoulePerSquareMeter, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = Irradiation.Parse("1 Btu/ft²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.BtusPerSquareFoot, BtusPerSquareFootTolerance); - Assert.Equal(IrradiationUnit.BtuPerSquareFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Irradiation.Parse("1 J/cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.JoulesPerSquareCentimeter, JoulesPerSquareCentimeterTolerance); - Assert.Equal(IrradiationUnit.JoulePerSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Irradiation.Parse("1 J/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.JoulesPerSquareMeter, JoulesPerSquareMeterTolerance); - Assert.Equal(IrradiationUnit.JoulePerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Irradiation.Parse("1 J/mm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.JoulesPerSquareMillimeter, JoulesPerSquareMillimeterTolerance); - Assert.Equal(IrradiationUnit.JoulePerSquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Irradiation.Parse("1 kBtu/ft²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilobtusPerSquareFoot, KilobtusPerSquareFootTolerance); - Assert.Equal(IrradiationUnit.KilobtuPerSquareFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Irradiation.Parse("1 kJ/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilojoulesPerSquareMeter, KilojoulesPerSquareMeterTolerance); - Assert.Equal(IrradiationUnit.KilojoulePerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Irradiation.Parse("1 kWh/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilowattHoursPerSquareMeter, KilowattHoursPerSquareMeterTolerance); - Assert.Equal(IrradiationUnit.KilowattHourPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Irradiation.Parse("1 mJ/cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillijoulesPerSquareCentimeter, MillijoulesPerSquareCentimeterTolerance); - Assert.Equal(IrradiationUnit.MillijoulePerSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Irradiation.Parse("1 Wh/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WattHoursPerSquareMeter, WattHoursPerSquareMeterTolerance); - Assert.Equal(IrradiationUnit.WattHourPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Irradiation.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 Btu/ft²", IrradiationUnit.BtuPerSquareFoot, 4.2)] + [InlineData("en-US", "4.2 J/cm²", IrradiationUnit.JoulePerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 J/m²", IrradiationUnit.JoulePerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 J/mm²", IrradiationUnit.JoulePerSquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 kBtu/ft²", IrradiationUnit.KilobtuPerSquareFoot, 4.2)] + [InlineData("en-US", "4.2 kJ/m²", IrradiationUnit.KilojoulePerSquareMeter, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(Irradiation.TryParse("1 Btu/ft²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BtusPerSquareFoot, BtusPerSquareFootTolerance); - Assert.Equal(IrradiationUnit.BtuPerSquareFoot, parsed.Unit); - } - - { - Assert.True(Irradiation.TryParse("1 J/cm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.JoulesPerSquareCentimeter, JoulesPerSquareCentimeterTolerance); - Assert.Equal(IrradiationUnit.JoulePerSquareCentimeter, parsed.Unit); - } - - { - Assert.True(Irradiation.TryParse("1 J/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.JoulesPerSquareMeter, JoulesPerSquareMeterTolerance); - Assert.Equal(IrradiationUnit.JoulePerSquareMeter, parsed.Unit); - } - - { - Assert.True(Irradiation.TryParse("1 J/mm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.JoulesPerSquareMillimeter, JoulesPerSquareMillimeterTolerance); - Assert.Equal(IrradiationUnit.JoulePerSquareMillimeter, parsed.Unit); - } - - { - Assert.True(Irradiation.TryParse("1 kBtu/ft²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilobtusPerSquareFoot, KilobtusPerSquareFootTolerance); - Assert.Equal(IrradiationUnit.KilobtuPerSquareFoot, parsed.Unit); - } - - { - Assert.True(Irradiation.TryParse("1 kJ/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilojoulesPerSquareMeter, KilojoulesPerSquareMeterTolerance); - Assert.Equal(IrradiationUnit.KilojoulePerSquareMeter, parsed.Unit); - } - - { - Assert.True(Irradiation.TryParse("1 kWh/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilowattHoursPerSquareMeter, KilowattHoursPerSquareMeterTolerance); - Assert.Equal(IrradiationUnit.KilowattHourPerSquareMeter, parsed.Unit); - } - - { - Assert.True(Irradiation.TryParse("1 mJ/cm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillijoulesPerSquareCentimeter, MillijoulesPerSquareCentimeterTolerance); - Assert.Equal(IrradiationUnit.MillijoulePerSquareCentimeter, parsed.Unit); - } - - { - Assert.True(Irradiation.TryParse("1 Wh/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattHoursPerSquareMeter, WattHoursPerSquareMeterTolerance); - Assert.Equal(IrradiationUnit.WattHourPerSquareMeter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Irradiation.TryParse(quantityString, out Irradiation parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -612,6 +539,35 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Irradi Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", IrradiationUnit.BtuPerSquareFoot, "Btu/ft²")] + [InlineData("en-US", IrradiationUnit.JoulePerSquareCentimeter, "J/cm²")] + [InlineData("en-US", IrradiationUnit.JoulePerSquareMeter, "J/m²")] + [InlineData("en-US", IrradiationUnit.JoulePerSquareMillimeter, "J/mm²")] + [InlineData("en-US", IrradiationUnit.KilobtuPerSquareFoot, "kBtu/ft²")] + [InlineData("en-US", IrradiationUnit.KilojoulePerSquareMeter, "kJ/m²")] + [InlineData("en-US", IrradiationUnit.KilowattHourPerSquareMeter, "kWh/m²")] + [InlineData("en-US", IrradiationUnit.MillijoulePerSquareCentimeter, "mJ/cm²")] + [InlineData("en-US", IrradiationUnit.WattHourPerSquareMeter, "Wh/m²")] + public void GetAbbreviationForCulture(string culture, IrradiationUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Irradiation.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Irradiation.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Irradiation.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(IrradiationUnit unit) @@ -642,6 +598,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); }); } @@ -665,40 +622,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] @@ -744,8 +703,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); @@ -783,34 +740,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = Irradiation.FromJoulesPerSquareMeter(1); - Assert.True(v.Equals(Irradiation.FromJoulesPerSquareMeter(1), JoulesPerSquareMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Irradiation.Zero, JoulesPerSquareMeterTolerance, ComparisonType.Relative)); - Assert.True(Irradiation.FromJoulesPerSquareMeter(100).Equals(Irradiation.FromJoulesPerSquareMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(Irradiation.FromJoulesPerSquareMeter(100).Equals(Irradiation.FromJoulesPerSquareMeter(120), 0.1, ComparisonType.Relative)); + Irradiation joulepersquaremeter = Irradiation.FromJoulesPerSquareMeter(1); + Assert.False(joulepersquaremeter.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = Irradiation.FromJoulesPerSquareMeter(1); - Assert.Throws(() => v.Equals(Irradiation.FromJoulesPerSquareMeter(1), -1, ComparisonType.Relative)); + Irradiation joulepersquaremeter = Irradiation.FromJoulesPerSquareMeter(1); + Assert.False(joulepersquaremeter.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - Irradiation joulepersquaremeter = Irradiation.FromJoulesPerSquareMeter(1); - Assert.False(joulepersquaremeter.Equals(new object())); + var quantity = Irradiation.FromJoulesPerSquareMeter(firstValue); + var otherQuantity = Irradiation.FromJoulesPerSquareMeter(secondValue); + Irradiation maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - Irradiation joulepersquaremeter = Irradiation.FromJoulesPerSquareMeter(1); - Assert.False(joulepersquaremeter.Equals(null)); + var quantity = Irradiation.FromJoulesPerSquareMeter(1); + var negativeTolerance = Irradiation.FromJoulesPerSquareMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -829,6 +795,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() { @@ -903,158 +881,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Irradiation))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(IrradiationUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal(Irradiation.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal(Irradiation.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal(new {Irradiation.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 d902463dc6..c791634d4a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/JerkTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/JerkTestsBase.g.cs @@ -136,7 +136,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Jerk(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -149,15 +149,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Jerk_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + JerkUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Jerk(1, JerkUnit.MeterPerSecondCubed); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Jerk.Zero, quantityInfo.Zero); Assert.Equal("Jerk", quantityInfo.Name); + Assert.Equal(Jerk.Zero, quantityInfo.Zero); + Assert.Equal(Jerk.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Jerk.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + [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] @@ -181,47 +199,47 @@ public void MeterPerSecondCubedToJerkUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Jerk.From(1, JerkUnit.CentimeterPerSecondCubed); - AssertEx.EqualTolerance(1, quantity00.CentimetersPerSecondCubed, CentimetersPerSecondCubedTolerance); + Assert.Equal(1, quantity00.CentimetersPerSecondCubed); Assert.Equal(JerkUnit.CentimeterPerSecondCubed, quantity00.Unit); var quantity01 = Jerk.From(1, JerkUnit.DecimeterPerSecondCubed); - AssertEx.EqualTolerance(1, quantity01.DecimetersPerSecondCubed, DecimetersPerSecondCubedTolerance); + Assert.Equal(1, quantity01.DecimetersPerSecondCubed); Assert.Equal(JerkUnit.DecimeterPerSecondCubed, quantity01.Unit); var quantity02 = Jerk.From(1, JerkUnit.FootPerSecondCubed); - AssertEx.EqualTolerance(1, quantity02.FeetPerSecondCubed, FeetPerSecondCubedTolerance); + Assert.Equal(1, quantity02.FeetPerSecondCubed); Assert.Equal(JerkUnit.FootPerSecondCubed, quantity02.Unit); var quantity03 = Jerk.From(1, JerkUnit.InchPerSecondCubed); - AssertEx.EqualTolerance(1, quantity03.InchesPerSecondCubed, InchesPerSecondCubedTolerance); + Assert.Equal(1, quantity03.InchesPerSecondCubed); Assert.Equal(JerkUnit.InchPerSecondCubed, quantity03.Unit); var quantity04 = Jerk.From(1, JerkUnit.KilometerPerSecondCubed); - AssertEx.EqualTolerance(1, quantity04.KilometersPerSecondCubed, KilometersPerSecondCubedTolerance); + Assert.Equal(1, quantity04.KilometersPerSecondCubed); Assert.Equal(JerkUnit.KilometerPerSecondCubed, quantity04.Unit); var quantity05 = Jerk.From(1, JerkUnit.MeterPerSecondCubed); - AssertEx.EqualTolerance(1, quantity05.MetersPerSecondCubed, MetersPerSecondCubedTolerance); + Assert.Equal(1, quantity05.MetersPerSecondCubed); Assert.Equal(JerkUnit.MeterPerSecondCubed, quantity05.Unit); var quantity06 = Jerk.From(1, JerkUnit.MicrometerPerSecondCubed); - AssertEx.EqualTolerance(1, quantity06.MicrometersPerSecondCubed, MicrometersPerSecondCubedTolerance); + Assert.Equal(1, quantity06.MicrometersPerSecondCubed); Assert.Equal(JerkUnit.MicrometerPerSecondCubed, quantity06.Unit); var quantity07 = Jerk.From(1, JerkUnit.MillimeterPerSecondCubed); - AssertEx.EqualTolerance(1, quantity07.MillimetersPerSecondCubed, MillimetersPerSecondCubedTolerance); + Assert.Equal(1, quantity07.MillimetersPerSecondCubed); Assert.Equal(JerkUnit.MillimeterPerSecondCubed, quantity07.Unit); var quantity08 = Jerk.From(1, JerkUnit.MillistandardGravitiesPerSecond); - AssertEx.EqualTolerance(1, quantity08.MillistandardGravitiesPerSecond, MillistandardGravitiesPerSecondTolerance); + Assert.Equal(1, quantity08.MillistandardGravitiesPerSecond); Assert.Equal(JerkUnit.MillistandardGravitiesPerSecond, quantity08.Unit); var quantity09 = Jerk.From(1, JerkUnit.NanometerPerSecondCubed); - AssertEx.EqualTolerance(1, quantity09.NanometersPerSecondCubed, NanometersPerSecondCubedTolerance); + Assert.Equal(1, quantity09.NanometersPerSecondCubed); Assert.Equal(JerkUnit.NanometerPerSecondCubed, quantity09.Unit); var quantity10 = Jerk.From(1, JerkUnit.StandardGravitiesPerSecond); - AssertEx.EqualTolerance(1, quantity10.StandardGravitiesPerSecond, StandardGravitiesPerSecondTolerance); + Assert.Equal(1, quantity10.StandardGravitiesPerSecond); Assert.Equal(JerkUnit.StandardGravitiesPerSecond, quantity10.Unit); } @@ -367,300 +385,66 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 cm/s³", JerkUnit.CentimeterPerSecondCubed, 4.2)] + [InlineData("en-US", "4.2 dm/s³", JerkUnit.DecimeterPerSecondCubed, 4.2)] + [InlineData("en-US", "4.2 ft/s³", JerkUnit.FootPerSecondCubed, 4.2)] + [InlineData("en-US", "4.2 in/s³", JerkUnit.InchPerSecondCubed, 4.2)] + [InlineData("en-US", "4.2 km/s³", JerkUnit.KilometerPerSecondCubed, 4.2)] + [InlineData("en-US", "4.2 m/s³", JerkUnit.MeterPerSecondCubed, 4.2)] + [InlineData("en-US", "4.2 µm/s³", JerkUnit.MicrometerPerSecondCubed, 4.2)] + [InlineData("en-US", "4.2 mm/s³", JerkUnit.MillimeterPerSecondCubed, 4.2)] + [InlineData("en-US", "4.2 mg/s", JerkUnit.MillistandardGravitiesPerSecond, 4.2)] + [InlineData("en-US", "4.2 nm/s³", JerkUnit.NanometerPerSecondCubed, 4.2)] + [InlineData("en-US", "4.2 g/s", JerkUnit.StandardGravitiesPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 см/с³", JerkUnit.CentimeterPerSecondCubed, 4.2)] + [InlineData("ru-RU", "4,2 дм/с³", JerkUnit.DecimeterPerSecondCubed, 4.2)] + [InlineData("ru-RU", "4,2 фут/с³", JerkUnit.FootPerSecondCubed, 4.2)] + [InlineData("ru-RU", "4,2 дюйм/с³", JerkUnit.InchPerSecondCubed, 4.2)] + [InlineData("ru-RU", "4,2 км/с³", JerkUnit.KilometerPerSecondCubed, 4.2)] + [InlineData("ru-RU", "4,2 м/с³", JerkUnit.MeterPerSecondCubed, 4.2)] + [InlineData("ru-RU", "4,2 мкм/с³", JerkUnit.MicrometerPerSecondCubed, 4.2)] + [InlineData("ru-RU", "4,2 мм/с³", JerkUnit.MillimeterPerSecondCubed, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = Jerk.Parse("1 cm/s³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentimetersPerSecondCubed, CentimetersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.CentimeterPerSecondCubed, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Jerk.Parse("1 см/с³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CentimetersPerSecondCubed, CentimetersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.CentimeterPerSecondCubed, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Jerk.Parse("1 dm/s³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecimetersPerSecondCubed, DecimetersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.DecimeterPerSecondCubed, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Jerk.Parse("1 дм/с³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.DecimetersPerSecondCubed, DecimetersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.DecimeterPerSecondCubed, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Jerk.Parse("1 ft/s³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.FeetPerSecondCubed, FeetPerSecondCubedTolerance); - Assert.Equal(JerkUnit.FootPerSecondCubed, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Jerk.Parse("1 фут/с³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.FeetPerSecondCubed, FeetPerSecondCubedTolerance); - Assert.Equal(JerkUnit.FootPerSecondCubed, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Jerk.Parse("1 in/s³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InchesPerSecondCubed, InchesPerSecondCubedTolerance); - Assert.Equal(JerkUnit.InchPerSecondCubed, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Jerk.Parse("1 дюйм/с³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.InchesPerSecondCubed, InchesPerSecondCubedTolerance); - Assert.Equal(JerkUnit.InchPerSecondCubed, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Jerk.Parse("1 km/s³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilometersPerSecondCubed, KilometersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.KilometerPerSecondCubed, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Jerk.Parse("1 км/с³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilometersPerSecondCubed, KilometersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.KilometerPerSecondCubed, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Jerk.Parse("1 m/s³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MetersPerSecondCubed, MetersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.MeterPerSecondCubed, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Jerk.Parse("1 м/с³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MetersPerSecondCubed, MetersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.MeterPerSecondCubed, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Jerk.Parse("1 µm/s³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrometersPerSecondCubed, MicrometersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.MicrometerPerSecondCubed, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Jerk.Parse("1 мкм/с³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MicrometersPerSecondCubed, MicrometersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.MicrometerPerSecondCubed, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Jerk.Parse("1 mm/s³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillimetersPerSecondCubed, MillimetersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.MillimeterPerSecondCubed, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Jerk.Parse("1 мм/с³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MillimetersPerSecondCubed, MillimetersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.MillimeterPerSecondCubed, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Jerk.Parse("1 mg/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillistandardGravitiesPerSecond, MillistandardGravitiesPerSecondTolerance); - Assert.Equal(JerkUnit.MillistandardGravitiesPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Jerk.Parse("1 мg/s", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MillistandardGravitiesPerSecond, MillistandardGravitiesPerSecondTolerance); - Assert.Equal(JerkUnit.MillistandardGravitiesPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Jerk.Parse("1 nm/s³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanometersPerSecondCubed, NanometersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.NanometerPerSecondCubed, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Jerk.Parse("1 нм/с³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.NanometersPerSecondCubed, NanometersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.NanometerPerSecondCubed, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Jerk.Parse("1 g/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.StandardGravitiesPerSecond, StandardGravitiesPerSecondTolerance); - Assert.Equal(JerkUnit.StandardGravitiesPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Jerk.Parse("1 g/s", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.StandardGravitiesPerSecond, StandardGravitiesPerSecondTolerance); - Assert.Equal(JerkUnit.StandardGravitiesPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Jerk.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 cm/s³", JerkUnit.CentimeterPerSecondCubed, 4.2)] + [InlineData("en-US", "4.2 dm/s³", JerkUnit.DecimeterPerSecondCubed, 4.2)] + [InlineData("en-US", "4.2 ft/s³", JerkUnit.FootPerSecondCubed, 4.2)] + [InlineData("en-US", "4.2 in/s³", JerkUnit.InchPerSecondCubed, 4.2)] + [InlineData("en-US", "4.2 km/s³", JerkUnit.KilometerPerSecondCubed, 4.2)] + [InlineData("en-US", "4.2 m/s³", JerkUnit.MeterPerSecondCubed, 4.2)] + [InlineData("en-US", "4.2 µm/s³", JerkUnit.MicrometerPerSecondCubed, 4.2)] + [InlineData("en-US", "4.2 mm/s³", JerkUnit.MillimeterPerSecondCubed, 4.2)] + [InlineData("en-US", "4.2 mg/s", JerkUnit.MillistandardGravitiesPerSecond, 4.2)] + [InlineData("en-US", "4.2 nm/s³", JerkUnit.NanometerPerSecondCubed, 4.2)] + [InlineData("en-US", "4.2 g/s", JerkUnit.StandardGravitiesPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 см/с³", JerkUnit.CentimeterPerSecondCubed, 4.2)] + [InlineData("ru-RU", "4,2 дм/с³", JerkUnit.DecimeterPerSecondCubed, 4.2)] + [InlineData("ru-RU", "4,2 фут/с³", JerkUnit.FootPerSecondCubed, 4.2)] + [InlineData("ru-RU", "4,2 дюйм/с³", JerkUnit.InchPerSecondCubed, 4.2)] + [InlineData("ru-RU", "4,2 км/с³", JerkUnit.KilometerPerSecondCubed, 4.2)] + [InlineData("ru-RU", "4,2 м/с³", JerkUnit.MeterPerSecondCubed, 4.2)] + [InlineData("ru-RU", "4,2 мкм/с³", JerkUnit.MicrometerPerSecondCubed, 4.2)] + [InlineData("ru-RU", "4,2 мм/с³", JerkUnit.MillimeterPerSecondCubed, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(Jerk.TryParse("1 cm/s³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentimetersPerSecondCubed, CentimetersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.CentimeterPerSecondCubed, parsed.Unit); - } - - { - Assert.True(Jerk.TryParse("1 см/с³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentimetersPerSecondCubed, CentimetersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.CentimeterPerSecondCubed, parsed.Unit); - } - - { - Assert.True(Jerk.TryParse("1 dm/s³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecimetersPerSecondCubed, DecimetersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.DecimeterPerSecondCubed, parsed.Unit); - } - - { - Assert.True(Jerk.TryParse("1 дм/с³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecimetersPerSecondCubed, DecimetersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.DecimeterPerSecondCubed, parsed.Unit); - } - - { - Assert.True(Jerk.TryParse("1 ft/s³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.FeetPerSecondCubed, FeetPerSecondCubedTolerance); - Assert.Equal(JerkUnit.FootPerSecondCubed, parsed.Unit); - } - - { - Assert.True(Jerk.TryParse("1 фут/с³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.FeetPerSecondCubed, FeetPerSecondCubedTolerance); - Assert.Equal(JerkUnit.FootPerSecondCubed, parsed.Unit); - } - - { - Assert.True(Jerk.TryParse("1 in/s³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InchesPerSecondCubed, InchesPerSecondCubedTolerance); - Assert.Equal(JerkUnit.InchPerSecondCubed, parsed.Unit); - } - - { - Assert.True(Jerk.TryParse("1 дюйм/с³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InchesPerSecondCubed, InchesPerSecondCubedTolerance); - Assert.Equal(JerkUnit.InchPerSecondCubed, parsed.Unit); - } - - { - Assert.True(Jerk.TryParse("1 km/s³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilometersPerSecondCubed, KilometersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.KilometerPerSecondCubed, parsed.Unit); - } - - { - Assert.True(Jerk.TryParse("1 км/с³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilometersPerSecondCubed, KilometersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.KilometerPerSecondCubed, parsed.Unit); - } - - { - Assert.True(Jerk.TryParse("1 m/s³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetersPerSecondCubed, MetersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.MeterPerSecondCubed, parsed.Unit); - } - - { - Assert.True(Jerk.TryParse("1 м/с³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetersPerSecondCubed, MetersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.MeterPerSecondCubed, parsed.Unit); - } - - { - Assert.True(Jerk.TryParse("1 µm/s³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrometersPerSecondCubed, MicrometersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.MicrometerPerSecondCubed, parsed.Unit); - } - - { - Assert.True(Jerk.TryParse("1 мкм/с³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrometersPerSecondCubed, MicrometersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.MicrometerPerSecondCubed, parsed.Unit); - } - - { - Assert.True(Jerk.TryParse("1 mm/s³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimetersPerSecondCubed, MillimetersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.MillimeterPerSecondCubed, parsed.Unit); - } - - { - Assert.True(Jerk.TryParse("1 мм/с³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimetersPerSecondCubed, MillimetersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.MillimeterPerSecondCubed, parsed.Unit); - } - - { - Assert.True(Jerk.TryParse("1 mg/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillistandardGravitiesPerSecond, MillistandardGravitiesPerSecondTolerance); - Assert.Equal(JerkUnit.MillistandardGravitiesPerSecond, parsed.Unit); - } - - { - Assert.True(Jerk.TryParse("1 мg/s", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillistandardGravitiesPerSecond, MillistandardGravitiesPerSecondTolerance); - Assert.Equal(JerkUnit.MillistandardGravitiesPerSecond, parsed.Unit); - } - - { - Assert.True(Jerk.TryParse("1 nm/s³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanometersPerSecondCubed, NanometersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.NanometerPerSecondCubed, parsed.Unit); - } - - { - Assert.True(Jerk.TryParse("1 нм/с³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanometersPerSecondCubed, NanometersPerSecondCubedTolerance); - Assert.Equal(JerkUnit.NanometerPerSecondCubed, parsed.Unit); - } - - { - Assert.True(Jerk.TryParse("1 g/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.StandardGravitiesPerSecond, StandardGravitiesPerSecondTolerance); - Assert.Equal(JerkUnit.StandardGravitiesPerSecond, parsed.Unit); - } - - { - Assert.True(Jerk.TryParse("1 g/s", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.StandardGravitiesPerSecond, StandardGravitiesPerSecondTolerance); - Assert.Equal(JerkUnit.StandardGravitiesPerSecond, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Jerk.TryParse(quantityString, out Jerk parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -861,6 +645,48 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, JerkUn Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", JerkUnit.CentimeterPerSecondCubed, "cm/s³")] + [InlineData("en-US", JerkUnit.DecimeterPerSecondCubed, "dm/s³")] + [InlineData("en-US", JerkUnit.FootPerSecondCubed, "ft/s³")] + [InlineData("en-US", JerkUnit.InchPerSecondCubed, "in/s³")] + [InlineData("en-US", JerkUnit.KilometerPerSecondCubed, "km/s³")] + [InlineData("en-US", JerkUnit.MeterPerSecondCubed, "m/s³")] + [InlineData("en-US", JerkUnit.MicrometerPerSecondCubed, "µm/s³")] + [InlineData("en-US", JerkUnit.MillimeterPerSecondCubed, "mm/s³")] + [InlineData("en-US", JerkUnit.MillistandardGravitiesPerSecond, "mg/s")] + [InlineData("en-US", JerkUnit.NanometerPerSecondCubed, "nm/s³")] + [InlineData("en-US", JerkUnit.StandardGravitiesPerSecond, "g/s")] + [InlineData("ru-RU", JerkUnit.CentimeterPerSecondCubed, "см/с³")] + [InlineData("ru-RU", JerkUnit.DecimeterPerSecondCubed, "дм/с³")] + [InlineData("ru-RU", JerkUnit.FootPerSecondCubed, "фут/с³")] + [InlineData("ru-RU", JerkUnit.InchPerSecondCubed, "дюйм/с³")] + [InlineData("ru-RU", JerkUnit.KilometerPerSecondCubed, "км/с³")] + [InlineData("ru-RU", JerkUnit.MeterPerSecondCubed, "м/с³")] + [InlineData("ru-RU", JerkUnit.MicrometerPerSecondCubed, "мкм/с³")] + [InlineData("ru-RU", JerkUnit.MillimeterPerSecondCubed, "мм/с³")] + [InlineData("ru-RU", JerkUnit.MillistandardGravitiesPerSecond, "мg/s")] + [InlineData("ru-RU", JerkUnit.NanometerPerSecondCubed, "нм/с³")] + [InlineData("ru-RU", JerkUnit.StandardGravitiesPerSecond, "g/s")] + public void GetAbbreviationForCulture(string culture, JerkUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Jerk.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Jerk.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Jerk.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(JerkUnit unit) @@ -891,6 +717,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); }); } @@ -914,42 +741,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] @@ -995,8 +824,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); @@ -1033,23 +860,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = Jerk.FromMetersPerSecondCubed(1); - Assert.True(v.Equals(Jerk.FromMetersPerSecondCubed(1), MetersPerSecondCubedTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Jerk.Zero, MetersPerSecondCubedTolerance, ComparisonType.Relative)); - Assert.True(Jerk.FromMetersPerSecondCubed(100).Equals(Jerk.FromMetersPerSecondCubed(120), 0.3, ComparisonType.Relative)); - Assert.False(Jerk.FromMetersPerSecondCubed(100).Equals(Jerk.FromMetersPerSecondCubed(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = Jerk.FromMetersPerSecondCubed(1); - Assert.Throws(() => v.Equals(Jerk.FromMetersPerSecondCubed(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1064,6 +874,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(meterpersecondcubed.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = Jerk.FromMetersPerSecondCubed(1); + var negativeTolerance = Jerk.FromMetersPerSecondCubed(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1080,6 +916,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() { @@ -1158,158 +1006,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Jerk))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(JerkUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal(Jerk.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal(Jerk.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal(new {Jerk.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 eea29ac09d..23ecd4b202 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/KinematicViscosityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/KinematicViscosityTestsBase.g.cs @@ -128,7 +128,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new KinematicViscosity(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -141,15 +141,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void KinematicViscosity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + KinematicViscosityUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new KinematicViscosity(1, KinematicViscosityUnit.SquareMeterPerSecond); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(KinematicViscosity.Zero, quantityInfo.Zero); Assert.Equal("KinematicViscosity", quantityInfo.Name); + Assert.Equal(KinematicViscosity.Zero, quantityInfo.Zero); + Assert.Equal(KinematicViscosity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(KinematicViscosity.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void KinematicViscosityInfo_CreateWithCustomUnitInfos() + { + KinematicViscosityUnit[] expectedUnits = [KinematicViscosityUnit.SquareMeterPerSecond]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -171,39 +189,39 @@ public void SquareMeterPerSecondToKinematicViscosityUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = KinematicViscosity.From(1, KinematicViscosityUnit.Centistokes); - AssertEx.EqualTolerance(1, quantity00.Centistokes, CentistokesTolerance); + Assert.Equal(1, quantity00.Centistokes); Assert.Equal(KinematicViscosityUnit.Centistokes, quantity00.Unit); var quantity01 = KinematicViscosity.From(1, KinematicViscosityUnit.Decistokes); - AssertEx.EqualTolerance(1, quantity01.Decistokes, DecistokesTolerance); + Assert.Equal(1, quantity01.Decistokes); Assert.Equal(KinematicViscosityUnit.Decistokes, quantity01.Unit); var quantity02 = KinematicViscosity.From(1, KinematicViscosityUnit.Kilostokes); - AssertEx.EqualTolerance(1, quantity02.Kilostokes, KilostokesTolerance); + Assert.Equal(1, quantity02.Kilostokes); Assert.Equal(KinematicViscosityUnit.Kilostokes, quantity02.Unit); var quantity03 = KinematicViscosity.From(1, KinematicViscosityUnit.Microstokes); - AssertEx.EqualTolerance(1, quantity03.Microstokes, MicrostokesTolerance); + Assert.Equal(1, quantity03.Microstokes); Assert.Equal(KinematicViscosityUnit.Microstokes, quantity03.Unit); var quantity04 = KinematicViscosity.From(1, KinematicViscosityUnit.Millistokes); - AssertEx.EqualTolerance(1, quantity04.Millistokes, MillistokesTolerance); + Assert.Equal(1, quantity04.Millistokes); Assert.Equal(KinematicViscosityUnit.Millistokes, quantity04.Unit); var quantity05 = KinematicViscosity.From(1, KinematicViscosityUnit.Nanostokes); - AssertEx.EqualTolerance(1, quantity05.Nanostokes, NanostokesTolerance); + Assert.Equal(1, quantity05.Nanostokes); Assert.Equal(KinematicViscosityUnit.Nanostokes, quantity05.Unit); var quantity06 = KinematicViscosity.From(1, KinematicViscosityUnit.SquareFootPerSecond); - AssertEx.EqualTolerance(1, quantity06.SquareFeetPerSecond, SquareFeetPerSecondTolerance); + Assert.Equal(1, quantity06.SquareFeetPerSecond); Assert.Equal(KinematicViscosityUnit.SquareFootPerSecond, quantity06.Unit); var quantity07 = KinematicViscosity.From(1, KinematicViscosityUnit.SquareMeterPerSecond); - AssertEx.EqualTolerance(1, quantity07.SquareMetersPerSecond, SquareMetersPerSecondTolerance); + Assert.Equal(1, quantity07.SquareMetersPerSecond); Assert.Equal(KinematicViscosityUnit.SquareMeterPerSecond, quantity07.Unit); var quantity08 = KinematicViscosity.From(1, KinematicViscosityUnit.Stokes); - AssertEx.EqualTolerance(1, quantity08.Stokes, StokesTolerance); + Assert.Equal(1, quantity08.Stokes); Assert.Equal(KinematicViscosityUnit.Stokes, quantity08.Unit); } @@ -347,235 +365,56 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 cSt", KinematicViscosityUnit.Centistokes, 4.2)] + [InlineData("en-US", "4.2 dSt", KinematicViscosityUnit.Decistokes, 4.2)] + [InlineData("en-US", "4.2 kSt", KinematicViscosityUnit.Kilostokes, 4.2)] + [InlineData("en-US", "4.2 µSt", KinematicViscosityUnit.Microstokes, 4.2)] + [InlineData("en-US", "4.2 mSt", KinematicViscosityUnit.Millistokes, 4.2)] + [InlineData("en-US", "4.2 nSt", KinematicViscosityUnit.Nanostokes, 4.2)] + [InlineData("en-US", "4.2 ft²/s", KinematicViscosityUnit.SquareFootPerSecond, 4.2)] + [InlineData("en-US", "4.2 m²/s", KinematicViscosityUnit.SquareMeterPerSecond, 4.2)] + [InlineData("en-US", "4.2 St", KinematicViscosityUnit.Stokes, 4.2)] + [InlineData("ru-RU", "4,2 сСт", KinematicViscosityUnit.Centistokes, 4.2)] + [InlineData("ru-RU", "4,2 дСт", KinematicViscosityUnit.Decistokes, 4.2)] + [InlineData("ru-RU", "4,2 кСт", KinematicViscosityUnit.Kilostokes, 4.2)] + [InlineData("ru-RU", "4,2 мкСт", KinematicViscosityUnit.Microstokes, 4.2)] + [InlineData("ru-RU", "4,2 мСт", KinematicViscosityUnit.Millistokes, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = KinematicViscosity.Parse("1 cSt", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Centistokes, CentistokesTolerance); - Assert.Equal(KinematicViscosityUnit.Centistokes, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = KinematicViscosity.Parse("1 сСт", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Centistokes, CentistokesTolerance); - Assert.Equal(KinematicViscosityUnit.Centistokes, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = KinematicViscosity.Parse("1 dSt", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Decistokes, DecistokesTolerance); - Assert.Equal(KinematicViscosityUnit.Decistokes, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = KinematicViscosity.Parse("1 дСт", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Decistokes, DecistokesTolerance); - Assert.Equal(KinematicViscosityUnit.Decistokes, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = KinematicViscosity.Parse("1 kSt", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilostokes, KilostokesTolerance); - Assert.Equal(KinematicViscosityUnit.Kilostokes, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = KinematicViscosity.Parse("1 кСт", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Kilostokes, KilostokesTolerance); - Assert.Equal(KinematicViscosityUnit.Kilostokes, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = KinematicViscosity.Parse("1 µSt", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microstokes, MicrostokesTolerance); - Assert.Equal(KinematicViscosityUnit.Microstokes, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = KinematicViscosity.Parse("1 мкСт", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Microstokes, MicrostokesTolerance); - Assert.Equal(KinematicViscosityUnit.Microstokes, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = KinematicViscosity.Parse("1 mSt", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millistokes, MillistokesTolerance); - Assert.Equal(KinematicViscosityUnit.Millistokes, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = KinematicViscosity.Parse("1 мСт", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Millistokes, MillistokesTolerance); - Assert.Equal(KinematicViscosityUnit.Millistokes, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = KinematicViscosity.Parse("1 nSt", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanostokes, NanostokesTolerance); - Assert.Equal(KinematicViscosityUnit.Nanostokes, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = KinematicViscosity.Parse("1 нСт", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Nanostokes, NanostokesTolerance); - Assert.Equal(KinematicViscosityUnit.Nanostokes, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = KinematicViscosity.Parse("1 ft²/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SquareFeetPerSecond, SquareFeetPerSecondTolerance); - Assert.Equal(KinematicViscosityUnit.SquareFootPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = KinematicViscosity.Parse("1 m²/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SquareMetersPerSecond, SquareMetersPerSecondTolerance); - Assert.Equal(KinematicViscosityUnit.SquareMeterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = KinematicViscosity.Parse("1 м²/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.SquareMetersPerSecond, SquareMetersPerSecondTolerance); - Assert.Equal(KinematicViscosityUnit.SquareMeterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = KinematicViscosity.Parse("1 St", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Stokes, StokesTolerance); - Assert.Equal(KinematicViscosityUnit.Stokes, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = KinematicViscosity.Parse("1 Ст", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Stokes, StokesTolerance); - Assert.Equal(KinematicViscosityUnit.Stokes, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = KinematicViscosity.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 cSt", KinematicViscosityUnit.Centistokes, 4.2)] + [InlineData("en-US", "4.2 dSt", KinematicViscosityUnit.Decistokes, 4.2)] + [InlineData("en-US", "4.2 kSt", KinematicViscosityUnit.Kilostokes, 4.2)] + [InlineData("en-US", "4.2 µSt", KinematicViscosityUnit.Microstokes, 4.2)] + [InlineData("en-US", "4.2 mSt", KinematicViscosityUnit.Millistokes, 4.2)] + [InlineData("en-US", "4.2 nSt", KinematicViscosityUnit.Nanostokes, 4.2)] + [InlineData("en-US", "4.2 ft²/s", KinematicViscosityUnit.SquareFootPerSecond, 4.2)] + [InlineData("en-US", "4.2 m²/s", KinematicViscosityUnit.SquareMeterPerSecond, 4.2)] + [InlineData("en-US", "4.2 St", KinematicViscosityUnit.Stokes, 4.2)] + [InlineData("ru-RU", "4,2 сСт", KinematicViscosityUnit.Centistokes, 4.2)] + [InlineData("ru-RU", "4,2 дСт", KinematicViscosityUnit.Decistokes, 4.2)] + [InlineData("ru-RU", "4,2 кСт", KinematicViscosityUnit.Kilostokes, 4.2)] + [InlineData("ru-RU", "4,2 мкСт", KinematicViscosityUnit.Microstokes, 4.2)] + [InlineData("ru-RU", "4,2 мСт", KinematicViscosityUnit.Millistokes, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(KinematicViscosity.TryParse("1 cSt", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Centistokes, CentistokesTolerance); - Assert.Equal(KinematicViscosityUnit.Centistokes, parsed.Unit); - } - - { - Assert.True(KinematicViscosity.TryParse("1 сСт", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Centistokes, CentistokesTolerance); - Assert.Equal(KinematicViscosityUnit.Centistokes, parsed.Unit); - } - - { - Assert.True(KinematicViscosity.TryParse("1 dSt", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Decistokes, DecistokesTolerance); - Assert.Equal(KinematicViscosityUnit.Decistokes, parsed.Unit); - } - - { - Assert.True(KinematicViscosity.TryParse("1 дСт", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Decistokes, DecistokesTolerance); - Assert.Equal(KinematicViscosityUnit.Decistokes, parsed.Unit); - } - - { - Assert.True(KinematicViscosity.TryParse("1 kSt", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilostokes, KilostokesTolerance); - Assert.Equal(KinematicViscosityUnit.Kilostokes, parsed.Unit); - } - - { - Assert.True(KinematicViscosity.TryParse("1 кСт", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilostokes, KilostokesTolerance); - Assert.Equal(KinematicViscosityUnit.Kilostokes, parsed.Unit); - } - - { - Assert.True(KinematicViscosity.TryParse("1 µSt", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microstokes, MicrostokesTolerance); - Assert.Equal(KinematicViscosityUnit.Microstokes, parsed.Unit); - } - - { - Assert.True(KinematicViscosity.TryParse("1 мкСт", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microstokes, MicrostokesTolerance); - Assert.Equal(KinematicViscosityUnit.Microstokes, parsed.Unit); - } - - { - Assert.True(KinematicViscosity.TryParse("1 mSt", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Millistokes, MillistokesTolerance); - Assert.Equal(KinematicViscosityUnit.Millistokes, parsed.Unit); - } - - { - Assert.True(KinematicViscosity.TryParse("1 мСт", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Millistokes, MillistokesTolerance); - Assert.Equal(KinematicViscosityUnit.Millistokes, parsed.Unit); - } - - { - Assert.True(KinematicViscosity.TryParse("1 nSt", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanostokes, NanostokesTolerance); - Assert.Equal(KinematicViscosityUnit.Nanostokes, parsed.Unit); - } - - { - Assert.True(KinematicViscosity.TryParse("1 нСт", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanostokes, NanostokesTolerance); - Assert.Equal(KinematicViscosityUnit.Nanostokes, parsed.Unit); - } - - { - Assert.True(KinematicViscosity.TryParse("1 ft²/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareFeetPerSecond, SquareFeetPerSecondTolerance); - Assert.Equal(KinematicViscosityUnit.SquareFootPerSecond, parsed.Unit); - } - - { - Assert.True(KinematicViscosity.TryParse("1 m²/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareMetersPerSecond, SquareMetersPerSecondTolerance); - Assert.Equal(KinematicViscosityUnit.SquareMeterPerSecond, parsed.Unit); - } - - { - Assert.True(KinematicViscosity.TryParse("1 м²/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareMetersPerSecond, SquareMetersPerSecondTolerance); - Assert.Equal(KinematicViscosityUnit.SquareMeterPerSecond, parsed.Unit); - } - - { - Assert.True(KinematicViscosity.TryParse("1 St", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Stokes, StokesTolerance); - Assert.Equal(KinematicViscosityUnit.Stokes, parsed.Unit); - } - - { - Assert.True(KinematicViscosity.TryParse("1 Ст", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Stokes, StokesTolerance); - Assert.Equal(KinematicViscosityUnit.Stokes, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(KinematicViscosity.TryParse(quantityString, out KinematicViscosity parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -748,6 +587,43 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Kinema Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", KinematicViscosityUnit.Centistokes, "cSt")] + [InlineData("en-US", KinematicViscosityUnit.Decistokes, "dSt")] + [InlineData("en-US", KinematicViscosityUnit.Kilostokes, "kSt")] + [InlineData("en-US", KinematicViscosityUnit.Microstokes, "µSt")] + [InlineData("en-US", KinematicViscosityUnit.Millistokes, "mSt")] + [InlineData("en-US", KinematicViscosityUnit.Nanostokes, "nSt")] + [InlineData("en-US", KinematicViscosityUnit.SquareFootPerSecond, "ft²/s")] + [InlineData("en-US", KinematicViscosityUnit.SquareMeterPerSecond, "m²/s")] + [InlineData("en-US", KinematicViscosityUnit.Stokes, "St")] + [InlineData("ru-RU", KinematicViscosityUnit.Centistokes, "сСт")] + [InlineData("ru-RU", KinematicViscosityUnit.Decistokes, "дСт")] + [InlineData("ru-RU", KinematicViscosityUnit.Kilostokes, "кСт")] + [InlineData("ru-RU", KinematicViscosityUnit.Microstokes, "мкСт")] + [InlineData("ru-RU", KinematicViscosityUnit.Millistokes, "мСт")] + [InlineData("ru-RU", KinematicViscosityUnit.Nanostokes, "нСт")] + [InlineData("ru-RU", KinematicViscosityUnit.SquareMeterPerSecond, "м²/с")] + [InlineData("ru-RU", KinematicViscosityUnit.Stokes, "Ст")] + public void GetAbbreviationForCulture(string culture, KinematicViscosityUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = KinematicViscosity.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(KinematicViscosity.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = KinematicViscosity.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(KinematicViscosityUnit unit) @@ -778,6 +654,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); }); } @@ -801,40 +678,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] @@ -880,8 +759,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); @@ -919,34 +796,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = KinematicViscosity.FromSquareMetersPerSecond(1); - Assert.True(v.Equals(KinematicViscosity.FromSquareMetersPerSecond(1), SquareMetersPerSecondTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(KinematicViscosity.Zero, SquareMetersPerSecondTolerance, ComparisonType.Relative)); - Assert.True(KinematicViscosity.FromSquareMetersPerSecond(100).Equals(KinematicViscosity.FromSquareMetersPerSecond(120), 0.3, ComparisonType.Relative)); - Assert.False(KinematicViscosity.FromSquareMetersPerSecond(100).Equals(KinematicViscosity.FromSquareMetersPerSecond(120), 0.1, ComparisonType.Relative)); + KinematicViscosity squaremeterpersecond = KinematicViscosity.FromSquareMetersPerSecond(1); + Assert.False(squaremeterpersecond.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = KinematicViscosity.FromSquareMetersPerSecond(1); - Assert.Throws(() => v.Equals(KinematicViscosity.FromSquareMetersPerSecond(1), -1, ComparisonType.Relative)); + KinematicViscosity squaremeterpersecond = KinematicViscosity.FromSquareMetersPerSecond(1); + Assert.False(squaremeterpersecond.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - KinematicViscosity squaremeterpersecond = KinematicViscosity.FromSquareMetersPerSecond(1); - Assert.False(squaremeterpersecond.Equals(new object())); + var quantity = KinematicViscosity.FromSquareMetersPerSecond(firstValue); + var otherQuantity = KinematicViscosity.FromSquareMetersPerSecond(secondValue); + KinematicViscosity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - KinematicViscosity squaremeterpersecond = KinematicViscosity.FromSquareMetersPerSecond(1); - Assert.False(squaremeterpersecond.Equals(null)); + var quantity = KinematicViscosity.FromSquareMetersPerSecond(1); + var negativeTolerance = KinematicViscosity.FromSquareMetersPerSecond(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -965,6 +851,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() { @@ -1039,158 +937,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(KinematicViscosity))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(KinematicViscosityUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal(KinematicViscosity.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal(KinematicViscosity.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal(new {KinematicViscosity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 640291dff1..c01bb1db02 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LeakRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LeakRateTestsBase.g.cs @@ -104,7 +104,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new LeakRate(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -117,15 +117,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void LeakRate_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + LeakRateUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new LeakRate(1, LeakRateUnit.PascalCubicMeterPerSecond); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(LeakRate.Zero, quantityInfo.Zero); Assert.Equal("LeakRate", quantityInfo.Name); + Assert.Equal(LeakRate.Zero, quantityInfo.Zero); + Assert.Equal(LeakRate.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(LeakRate.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void LeakRateInfo_CreateWithCustomUnitInfos() + { + LeakRateUnit[] expectedUnits = [LeakRateUnit.PascalCubicMeterPerSecond]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -141,15 +159,15 @@ public void PascalCubicMeterPerSecondToLeakRateUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = LeakRate.From(1, LeakRateUnit.MillibarLiterPerSecond); - AssertEx.EqualTolerance(1, quantity00.MillibarLitersPerSecond, MillibarLitersPerSecondTolerance); + Assert.Equal(1, quantity00.MillibarLitersPerSecond); Assert.Equal(LeakRateUnit.MillibarLiterPerSecond, quantity00.Unit); var quantity01 = LeakRate.From(1, LeakRateUnit.PascalCubicMeterPerSecond); - AssertEx.EqualTolerance(1, quantity01.PascalCubicMetersPerSecond, PascalCubicMetersPerSecondTolerance); + Assert.Equal(1, quantity01.PascalCubicMetersPerSecond); Assert.Equal(LeakRateUnit.PascalCubicMeterPerSecond, quantity01.Unit); var quantity02 = LeakRate.From(1, LeakRateUnit.TorrLiterPerSecond); - AssertEx.EqualTolerance(1, quantity02.TorrLitersPerSecond, TorrLitersPerSecondTolerance); + Assert.Equal(1, quantity02.TorrLitersPerSecond); Assert.Equal(LeakRateUnit.TorrLiterPerSecond, quantity02.Unit); } @@ -287,53 +305,28 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [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, decimal expectedValue) { - try - { - var parsed = LeakRate.Parse("1 mbar·l/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillibarLitersPerSecond, MillibarLitersPerSecondTolerance); - Assert.Equal(LeakRateUnit.MillibarLiterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LeakRate.Parse("1 Pa·m³/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PascalCubicMetersPerSecond, PascalCubicMetersPerSecondTolerance); - Assert.Equal(LeakRateUnit.PascalCubicMeterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LeakRate.Parse("1 Torr·l/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TorrLitersPerSecond, TorrLitersPerSecondTolerance); - Assert.Equal(LeakRateUnit.TorrLiterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = LeakRate.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [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, decimal expectedValue) { - { - Assert.True(LeakRate.TryParse("1 mbar·l/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillibarLitersPerSecond, MillibarLitersPerSecondTolerance); - Assert.Equal(LeakRateUnit.MillibarLiterPerSecond, parsed.Unit); - } - - { - Assert.True(LeakRate.TryParse("1 Pa·m³/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PascalCubicMetersPerSecond, PascalCubicMetersPerSecondTolerance); - Assert.Equal(LeakRateUnit.PascalCubicMeterPerSecond, parsed.Unit); - } - - { - Assert.True(LeakRate.TryParse("1 Torr·l/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TorrLitersPerSecond, TorrLitersPerSecondTolerance); - Assert.Equal(LeakRateUnit.TorrLiterPerSecond, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(LeakRate.TryParse(quantityString, out LeakRate parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -426,6 +419,29 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, LeakRa Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", LeakRateUnit.MillibarLiterPerSecond, "mbar·l/s")] + [InlineData("en-US", LeakRateUnit.PascalCubicMeterPerSecond, "Pa·m³/s")] + [InlineData("en-US", LeakRateUnit.TorrLiterPerSecond, "Torr·l/s")] + public void GetAbbreviationForCulture(string culture, LeakRateUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = LeakRate.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(LeakRate.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = LeakRate.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(LeakRateUnit unit) @@ -456,6 +472,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); }); } @@ -479,34 +496,36 @@ 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.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.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] @@ -552,8 +571,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.MillibarLiterPerSecond, false)] // Different value and unit. - [InlineData(1, LeakRateUnit.PascalCubicMeterPerSecond, 1, LeakRateUnit.MillibarLiterPerSecond, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, LeakRateUnit unitA, double valueB, LeakRateUnit unitB, bool expectEqual) { var a = new LeakRate(valueA, unitA); @@ -591,34 +608,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = LeakRate.FromPascalCubicMetersPerSecond(1); - Assert.True(v.Equals(LeakRate.FromPascalCubicMetersPerSecond(1), PascalCubicMetersPerSecondTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(LeakRate.Zero, PascalCubicMetersPerSecondTolerance, ComparisonType.Relative)); - Assert.True(LeakRate.FromPascalCubicMetersPerSecond(100).Equals(LeakRate.FromPascalCubicMetersPerSecond(120), 0.3, ComparisonType.Relative)); - Assert.False(LeakRate.FromPascalCubicMetersPerSecond(100).Equals(LeakRate.FromPascalCubicMetersPerSecond(120), 0.1, ComparisonType.Relative)); + LeakRate pascalcubicmeterpersecond = LeakRate.FromPascalCubicMetersPerSecond(1); + Assert.False(pascalcubicmeterpersecond.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = LeakRate.FromPascalCubicMetersPerSecond(1); - Assert.Throws(() => v.Equals(LeakRate.FromPascalCubicMetersPerSecond(1), -1, ComparisonType.Relative)); + LeakRate pascalcubicmeterpersecond = LeakRate.FromPascalCubicMetersPerSecond(1); + Assert.False(pascalcubicmeterpersecond.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - LeakRate pascalcubicmeterpersecond = LeakRate.FromPascalCubicMetersPerSecond(1); - Assert.False(pascalcubicmeterpersecond.Equals(new object())); + var quantity = LeakRate.FromPascalCubicMetersPerSecond(firstValue); + var otherQuantity = LeakRate.FromPascalCubicMetersPerSecond(secondValue); + LeakRate maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - LeakRate pascalcubicmeterpersecond = LeakRate.FromPascalCubicMetersPerSecond(1); - Assert.False(pascalcubicmeterpersecond.Equals(null)); + var quantity = LeakRate.FromPascalCubicMetersPerSecond(1); + var negativeTolerance = LeakRate.FromPascalCubicMetersPerSecond(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -637,6 +663,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() { @@ -699,158 +737,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = LeakRate.FromPascalCubicMetersPerSecond(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = LeakRate.FromPascalCubicMetersPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = LeakRate.FromPascalCubicMetersPerSecond(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = LeakRate.FromPascalCubicMetersPerSecond(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = LeakRate.FromPascalCubicMetersPerSecond(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = LeakRate.FromPascalCubicMetersPerSecond(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = LeakRate.FromPascalCubicMetersPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = LeakRate.FromPascalCubicMetersPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = LeakRate.FromPascalCubicMetersPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = LeakRate.FromPascalCubicMetersPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = LeakRate.FromPascalCubicMetersPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = LeakRate.FromPascalCubicMetersPerSecond(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = LeakRate.FromPascalCubicMetersPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = LeakRate.FromPascalCubicMetersPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = LeakRate.FromPascalCubicMetersPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = LeakRate.FromPascalCubicMetersPerSecond(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(LeakRate))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = LeakRate.FromPascalCubicMetersPerSecond(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(LeakRateUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = LeakRate.FromPascalCubicMetersPerSecond(1.0); - Assert.Equal(LeakRate.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = LeakRate.FromPascalCubicMetersPerSecond(1.0); - Assert.Equal(LeakRate.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = LeakRate.FromPascalCubicMetersPerSecond(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = LeakRate.FromPascalCubicMetersPerSecond(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = LeakRate.FromPascalCubicMetersPerSecond(1.0); - Assert.Equal(new {LeakRate.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 df6277822c..6ca5e3ee57 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LengthTestsBase.g.cs @@ -260,7 +260,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Length(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -273,15 +273,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Length_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + LengthUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Length(1, LengthUnit.Meter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Length.Zero, quantityInfo.Zero); Assert.Equal("Length", quantityInfo.Name); + Assert.Equal(Length.Zero, quantityInfo.Zero); + Assert.Equal(Length.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Length.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void LengthInfo_CreateWithCustomUnitInfos() + { + LengthUnit[] expectedUnits = [LengthUnit.Meter]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -336,171 +354,171 @@ public void MeterToLengthUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Length.From(1, LengthUnit.Angstrom); - AssertEx.EqualTolerance(1, quantity00.Angstroms, AngstromsTolerance); + Assert.Equal(1, quantity00.Angstroms); Assert.Equal(LengthUnit.Angstrom, quantity00.Unit); var quantity01 = Length.From(1, LengthUnit.AstronomicalUnit); - AssertEx.EqualTolerance(1, quantity01.AstronomicalUnits, AstronomicalUnitsTolerance); + Assert.Equal(1, quantity01.AstronomicalUnits); Assert.Equal(LengthUnit.AstronomicalUnit, quantity01.Unit); var quantity02 = Length.From(1, LengthUnit.Centimeter); - AssertEx.EqualTolerance(1, quantity02.Centimeters, CentimetersTolerance); + Assert.Equal(1, quantity02.Centimeters); Assert.Equal(LengthUnit.Centimeter, quantity02.Unit); var quantity03 = Length.From(1, LengthUnit.Chain); - AssertEx.EqualTolerance(1, quantity03.Chains, ChainsTolerance); + Assert.Equal(1, quantity03.Chains); Assert.Equal(LengthUnit.Chain, quantity03.Unit); var quantity04 = Length.From(1, LengthUnit.DataMile); - AssertEx.EqualTolerance(1, quantity04.DataMiles, DataMilesTolerance); + Assert.Equal(1, quantity04.DataMiles); Assert.Equal(LengthUnit.DataMile, quantity04.Unit); var quantity05 = Length.From(1, LengthUnit.Decameter); - AssertEx.EqualTolerance(1, quantity05.Decameters, DecametersTolerance); + Assert.Equal(1, quantity05.Decameters); Assert.Equal(LengthUnit.Decameter, quantity05.Unit); var quantity06 = Length.From(1, LengthUnit.Decimeter); - AssertEx.EqualTolerance(1, quantity06.Decimeters, DecimetersTolerance); + Assert.Equal(1, quantity06.Decimeters); Assert.Equal(LengthUnit.Decimeter, quantity06.Unit); var quantity07 = Length.From(1, LengthUnit.DtpPica); - AssertEx.EqualTolerance(1, quantity07.DtpPicas, DtpPicasTolerance); + Assert.Equal(1, quantity07.DtpPicas); Assert.Equal(LengthUnit.DtpPica, quantity07.Unit); var quantity08 = Length.From(1, LengthUnit.DtpPoint); - AssertEx.EqualTolerance(1, quantity08.DtpPoints, DtpPointsTolerance); + Assert.Equal(1, quantity08.DtpPoints); Assert.Equal(LengthUnit.DtpPoint, quantity08.Unit); var quantity09 = Length.From(1, LengthUnit.Fathom); - AssertEx.EqualTolerance(1, quantity09.Fathoms, FathomsTolerance); + Assert.Equal(1, quantity09.Fathoms); Assert.Equal(LengthUnit.Fathom, quantity09.Unit); var quantity10 = Length.From(1, LengthUnit.Femtometer); - AssertEx.EqualTolerance(1, quantity10.Femtometers, FemtometersTolerance); + Assert.Equal(1, quantity10.Femtometers); Assert.Equal(LengthUnit.Femtometer, quantity10.Unit); var quantity11 = Length.From(1, LengthUnit.Foot); - AssertEx.EqualTolerance(1, quantity11.Feet, FeetTolerance); + Assert.Equal(1, quantity11.Feet); Assert.Equal(LengthUnit.Foot, quantity11.Unit); var quantity12 = Length.From(1, LengthUnit.Gigameter); - AssertEx.EqualTolerance(1, quantity12.Gigameters, GigametersTolerance); + Assert.Equal(1, quantity12.Gigameters); Assert.Equal(LengthUnit.Gigameter, quantity12.Unit); var quantity13 = Length.From(1, LengthUnit.Hand); - AssertEx.EqualTolerance(1, quantity13.Hands, HandsTolerance); + Assert.Equal(1, quantity13.Hands); Assert.Equal(LengthUnit.Hand, quantity13.Unit); var quantity14 = Length.From(1, LengthUnit.Hectometer); - AssertEx.EqualTolerance(1, quantity14.Hectometers, HectometersTolerance); + Assert.Equal(1, quantity14.Hectometers); Assert.Equal(LengthUnit.Hectometer, quantity14.Unit); var quantity15 = Length.From(1, LengthUnit.Inch); - AssertEx.EqualTolerance(1, quantity15.Inches, InchesTolerance); + Assert.Equal(1, quantity15.Inches); Assert.Equal(LengthUnit.Inch, quantity15.Unit); var quantity16 = Length.From(1, LengthUnit.Kilofoot); - AssertEx.EqualTolerance(1, quantity16.Kilofeet, KilofeetTolerance); + Assert.Equal(1, quantity16.Kilofeet); Assert.Equal(LengthUnit.Kilofoot, quantity16.Unit); var quantity17 = Length.From(1, LengthUnit.KilolightYear); - AssertEx.EqualTolerance(1, quantity17.KilolightYears, KilolightYearsTolerance); + Assert.Equal(1, quantity17.KilolightYears); Assert.Equal(LengthUnit.KilolightYear, quantity17.Unit); var quantity18 = Length.From(1, LengthUnit.Kilometer); - AssertEx.EqualTolerance(1, quantity18.Kilometers, KilometersTolerance); + Assert.Equal(1, quantity18.Kilometers); Assert.Equal(LengthUnit.Kilometer, quantity18.Unit); var quantity19 = Length.From(1, LengthUnit.Kiloparsec); - AssertEx.EqualTolerance(1, quantity19.Kiloparsecs, KiloparsecsTolerance); + Assert.Equal(1, quantity19.Kiloparsecs); Assert.Equal(LengthUnit.Kiloparsec, quantity19.Unit); var quantity20 = Length.From(1, LengthUnit.Kiloyard); - AssertEx.EqualTolerance(1, quantity20.Kiloyards, KiloyardsTolerance); + Assert.Equal(1, quantity20.Kiloyards); Assert.Equal(LengthUnit.Kiloyard, quantity20.Unit); var quantity21 = Length.From(1, LengthUnit.LightYear); - AssertEx.EqualTolerance(1, quantity21.LightYears, LightYearsTolerance); + Assert.Equal(1, quantity21.LightYears); Assert.Equal(LengthUnit.LightYear, quantity21.Unit); var quantity22 = Length.From(1, LengthUnit.MegalightYear); - AssertEx.EqualTolerance(1, quantity22.MegalightYears, MegalightYearsTolerance); + Assert.Equal(1, quantity22.MegalightYears); Assert.Equal(LengthUnit.MegalightYear, quantity22.Unit); var quantity23 = Length.From(1, LengthUnit.Megameter); - AssertEx.EqualTolerance(1, quantity23.Megameters, MegametersTolerance); + Assert.Equal(1, quantity23.Megameters); Assert.Equal(LengthUnit.Megameter, quantity23.Unit); var quantity24 = Length.From(1, LengthUnit.Megaparsec); - AssertEx.EqualTolerance(1, quantity24.Megaparsecs, MegaparsecsTolerance); + Assert.Equal(1, quantity24.Megaparsecs); Assert.Equal(LengthUnit.Megaparsec, quantity24.Unit); var quantity25 = Length.From(1, LengthUnit.Meter); - AssertEx.EqualTolerance(1, quantity25.Meters, MetersTolerance); + Assert.Equal(1, quantity25.Meters); Assert.Equal(LengthUnit.Meter, quantity25.Unit); var quantity26 = Length.From(1, LengthUnit.Microinch); - AssertEx.EqualTolerance(1, quantity26.Microinches, MicroinchesTolerance); + Assert.Equal(1, quantity26.Microinches); Assert.Equal(LengthUnit.Microinch, quantity26.Unit); var quantity27 = Length.From(1, LengthUnit.Micrometer); - AssertEx.EqualTolerance(1, quantity27.Micrometers, MicrometersTolerance); + Assert.Equal(1, quantity27.Micrometers); Assert.Equal(LengthUnit.Micrometer, quantity27.Unit); var quantity28 = Length.From(1, LengthUnit.Mil); - AssertEx.EqualTolerance(1, quantity28.Mils, MilsTolerance); + Assert.Equal(1, quantity28.Mils); Assert.Equal(LengthUnit.Mil, quantity28.Unit); var quantity29 = Length.From(1, LengthUnit.Mile); - AssertEx.EqualTolerance(1, quantity29.Miles, MilesTolerance); + Assert.Equal(1, quantity29.Miles); Assert.Equal(LengthUnit.Mile, quantity29.Unit); var quantity30 = Length.From(1, LengthUnit.Millimeter); - AssertEx.EqualTolerance(1, quantity30.Millimeters, MillimetersTolerance); + Assert.Equal(1, quantity30.Millimeters); Assert.Equal(LengthUnit.Millimeter, quantity30.Unit); var quantity31 = Length.From(1, LengthUnit.Nanometer); - AssertEx.EqualTolerance(1, quantity31.Nanometers, NanometersTolerance); + Assert.Equal(1, quantity31.Nanometers); Assert.Equal(LengthUnit.Nanometer, quantity31.Unit); var quantity32 = Length.From(1, LengthUnit.NauticalMile); - AssertEx.EqualTolerance(1, quantity32.NauticalMiles, NauticalMilesTolerance); + Assert.Equal(1, quantity32.NauticalMiles); Assert.Equal(LengthUnit.NauticalMile, quantity32.Unit); var quantity33 = Length.From(1, LengthUnit.Parsec); - AssertEx.EqualTolerance(1, quantity33.Parsecs, ParsecsTolerance); + Assert.Equal(1, quantity33.Parsecs); Assert.Equal(LengthUnit.Parsec, quantity33.Unit); var quantity34 = Length.From(1, LengthUnit.Picometer); - AssertEx.EqualTolerance(1, quantity34.Picometers, PicometersTolerance); + Assert.Equal(1, quantity34.Picometers); Assert.Equal(LengthUnit.Picometer, quantity34.Unit); var quantity35 = Length.From(1, LengthUnit.PrinterPica); - AssertEx.EqualTolerance(1, quantity35.PrinterPicas, PrinterPicasTolerance); + Assert.Equal(1, quantity35.PrinterPicas); Assert.Equal(LengthUnit.PrinterPica, quantity35.Unit); var quantity36 = Length.From(1, LengthUnit.PrinterPoint); - AssertEx.EqualTolerance(1, quantity36.PrinterPoints, PrinterPointsTolerance); + Assert.Equal(1, quantity36.PrinterPoints); Assert.Equal(LengthUnit.PrinterPoint, quantity36.Unit); var quantity37 = Length.From(1, LengthUnit.Shackle); - AssertEx.EqualTolerance(1, quantity37.Shackles, ShacklesTolerance); + Assert.Equal(1, quantity37.Shackles); Assert.Equal(LengthUnit.Shackle, quantity37.Unit); var quantity38 = Length.From(1, LengthUnit.SolarRadius); - AssertEx.EqualTolerance(1, quantity38.SolarRadiuses, SolarRadiusesTolerance); + Assert.Equal(1, quantity38.SolarRadiuses); Assert.Equal(LengthUnit.SolarRadius, quantity38.Unit); var quantity39 = Length.From(1, LengthUnit.Twip); - AssertEx.EqualTolerance(1, quantity39.Twips, TwipsTolerance); + Assert.Equal(1, quantity39.Twips); Assert.Equal(LengthUnit.Twip, quantity39.Unit); var quantity40 = Length.From(1, LengthUnit.UsSurveyFoot); - AssertEx.EqualTolerance(1, quantity40.UsSurveyFeet, UsSurveyFeetTolerance); + Assert.Equal(1, quantity40.UsSurveyFeet); Assert.Equal(LengthUnit.UsSurveyFoot, quantity40.Unit); var quantity41 = Length.From(1, LengthUnit.Yard); - AssertEx.EqualTolerance(1, quantity41.Yards, YardsTolerance); + Assert.Equal(1, quantity41.Yards); Assert.Equal(LengthUnit.Yard, quantity41.Unit); } @@ -586,1245 +604,309 @@ public virtual void As_UnitSystem_SI_ReturnsQuantityInSIUnits() var convertedValue = quantity.As(UnitSystem.SI); - Assert.Equal(expectedValue, convertedValue); - } - - [Fact] - public void As_UnitSystem_ThrowsArgumentNullExceptionIfNull() - { - var quantity = new Length(value: 1, unit: Length.BaseUnit); - UnitSystem nullUnitSystem = null!; - Assert.Throws(() => quantity.As(nullUnitSystem)); - } - - [Fact] - public void As_UnitSystem_ThrowsArgumentExceptionIfNotSupported() - { - var quantity = new Length(value: 1, unit: Length.BaseUnit); - var unsupportedUnitSystem = new UnitSystem(UnsupportedBaseUnits); - Assert.Throws(() => quantity.As(unsupportedUnitSystem)); - } - - [Fact] - public virtual void ToUnit_UnitSystem_SI_ReturnsQuantityInSIUnits() - { - var quantity = new Length(value: 1, unit: Length.BaseUnit); - var expectedUnit = Length.Info.GetDefaultUnit(UnitSystem.SI); - var expectedValue = quantity.As(expectedUnit); - - Assert.Multiple(() => - { - Length quantityToConvert = quantity; - - Length convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); - - Assert.Equal(expectedUnit, convertedQuantity.Unit); - Assert.Equal(expectedValue, convertedQuantity.Value); - }, () => - { - IQuantity quantityToConvert = quantity; - - IQuantity convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); - - Assert.Equal(expectedUnit, convertedQuantity.Unit); - Assert.Equal(expectedValue, convertedQuantity.Value); - }, () => - { - IQuantity quantityToConvert = quantity; - - IQuantity convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); - - Assert.Equal(expectedUnit, convertedQuantity.Unit); - Assert.Equal(expectedValue, convertedQuantity.Value); - }); - } - - [Fact] - public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() - { - UnitSystem nullUnitSystem = null!; - Assert.Multiple(() => - { - var quantity = new Length(value: 1, unit: Length.BaseUnit); - Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); - }, () => - { - IQuantity quantity = new Length(value: 1, unit: Length.BaseUnit); - Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); - }, () => - { - IQuantity quantity = new Length(value: 1, unit: Length.BaseUnit); - Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); - }); - } - - [Fact] - public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() - { - var unsupportedUnitSystem = new UnitSystem(UnsupportedBaseUnits); - Assert.Multiple(() => - { - var quantity = new Length(value: 1, unit: Length.BaseUnit); - Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); - }, () => - { - IQuantity quantity = new Length(value: 1, unit: Length.BaseUnit); - Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); - }, () => - { - IQuantity quantity = new Length(value: 1, unit: Length.BaseUnit); - Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); - }); - } - - [Fact] - public void Parse() - { - try - { - var parsed = Length.Parse("1 Å", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Angstroms, AngstromsTolerance); - Assert.Equal(LengthUnit.Angstrom, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 A", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Angstroms, AngstromsTolerance); - Assert.Equal(LengthUnit.Angstrom, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 au", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.AstronomicalUnits, AstronomicalUnitsTolerance); - Assert.Equal(LengthUnit.AstronomicalUnit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 ua", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.AstronomicalUnits, AstronomicalUnitsTolerance); - Assert.Equal(LengthUnit.AstronomicalUnit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Centimeters, CentimetersTolerance); - Assert.Equal(LengthUnit.Centimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 см", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Centimeters, CentimetersTolerance); - Assert.Equal(LengthUnit.Centimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 厘米", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Centimeters, CentimetersTolerance); - Assert.Equal(LengthUnit.Centimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 ch", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Chains, ChainsTolerance); - Assert.Equal(LengthUnit.Chain, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 DM", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DataMiles, DataMilesTolerance); - Assert.Equal(LengthUnit.DataMile, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 dam", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Decameters, DecametersTolerance); - Assert.Equal(LengthUnit.Decameter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 дам", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Decameters, DecametersTolerance); - Assert.Equal(LengthUnit.Decameter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 十米", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Decameters, DecametersTolerance); - Assert.Equal(LengthUnit.Decameter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 dm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Decimeters, DecimetersTolerance); - Assert.Equal(LengthUnit.Decimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 дм", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Decimeters, DecimetersTolerance); - Assert.Equal(LengthUnit.Decimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 分米", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Decimeters, DecimetersTolerance); - Assert.Equal(LengthUnit.Decimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 pica", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DtpPicas, DtpPicasTolerance); - Assert.Equal(LengthUnit.DtpPica, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 pt", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DtpPoints, DtpPointsTolerance); - Assert.Equal(LengthUnit.DtpPoint, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 fathom", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Fathoms, FathomsTolerance); - Assert.Equal(LengthUnit.Fathom, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 fm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Femtometers, FemtometersTolerance); - Assert.Equal(LengthUnit.Femtometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 фм", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Femtometers, FemtometersTolerance); - Assert.Equal(LengthUnit.Femtometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 飞米", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Femtometers, FemtometersTolerance); - Assert.Equal(LengthUnit.Femtometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Feet, FeetTolerance); - Assert.Equal(LengthUnit.Foot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 '", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Feet, FeetTolerance); - Assert.Equal(LengthUnit.Foot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 ′", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Feet, FeetTolerance); - Assert.Equal(LengthUnit.Foot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 фут", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Feet, FeetTolerance); - Assert.Equal(LengthUnit.Foot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 英尺", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Feet, FeetTolerance); - Assert.Equal(LengthUnit.Foot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 Gm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Gigameters, GigametersTolerance); - Assert.Equal(LengthUnit.Gigameter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 Гм", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Gigameters, GigametersTolerance); - Assert.Equal(LengthUnit.Gigameter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 吉米", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Gigameters, GigametersTolerance); - Assert.Equal(LengthUnit.Gigameter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Hands, HandsTolerance); - Assert.Equal(LengthUnit.Hand, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 hh", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Hands, HandsTolerance); - Assert.Equal(LengthUnit.Hand, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 hm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Hectometers, HectometersTolerance); - Assert.Equal(LengthUnit.Hectometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 гм", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Hectometers, HectometersTolerance); - Assert.Equal(LengthUnit.Hectometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 百米", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Hectometers, HectometersTolerance); - Assert.Equal(LengthUnit.Hectometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 in", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Inches, InchesTolerance); - Assert.Equal(LengthUnit.Inch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 \"", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Inches, InchesTolerance); - Assert.Equal(LengthUnit.Inch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 ″", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Inches, InchesTolerance); - Assert.Equal(LengthUnit.Inch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 дюйм", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Inches, InchesTolerance); - Assert.Equal(LengthUnit.Inch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 英寸", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Inches, InchesTolerance); - Assert.Equal(LengthUnit.Inch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 kft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilofeet, KilofeetTolerance); - Assert.Equal(LengthUnit.Kilofoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 k'", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilofeet, KilofeetTolerance); - Assert.Equal(LengthUnit.Kilofoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 k′", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilofeet, KilofeetTolerance); - Assert.Equal(LengthUnit.Kilofoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 кфут", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Kilofeet, KilofeetTolerance); - Assert.Equal(LengthUnit.Kilofoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 千英尺", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Kilofeet, KilofeetTolerance); - Assert.Equal(LengthUnit.Kilofoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 kly", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilolightYears, KilolightYearsTolerance); - Assert.Equal(LengthUnit.KilolightYear, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 km", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilometers, KilometersTolerance); - Assert.Equal(LengthUnit.Kilometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 км", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Kilometers, KilometersTolerance); - Assert.Equal(LengthUnit.Kilometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 千米", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Kilometers, KilometersTolerance); - Assert.Equal(LengthUnit.Kilometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 kpc", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kiloparsecs, KiloparsecsTolerance); - Assert.Equal(LengthUnit.Kiloparsec, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 kyd", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kiloyards, KiloyardsTolerance); - Assert.Equal(LengthUnit.Kiloyard, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 кярд", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Kiloyards, KiloyardsTolerance); - Assert.Equal(LengthUnit.Kiloyard, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 千码", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Kiloyards, KiloyardsTolerance); - Assert.Equal(LengthUnit.Kiloyard, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 ly", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.LightYears, LightYearsTolerance); - Assert.Equal(LengthUnit.LightYear, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 Mly", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegalightYears, MegalightYearsTolerance); - Assert.Equal(LengthUnit.MegalightYear, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 Mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megameters, MegametersTolerance); - Assert.Equal(LengthUnit.Megameter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 Мм", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Megameters, MegametersTolerance); - Assert.Equal(LengthUnit.Megameter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 兆米", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Megameters, MegametersTolerance); - Assert.Equal(LengthUnit.Megameter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 Mpc", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megaparsecs, MegaparsecsTolerance); - Assert.Equal(LengthUnit.Megaparsec, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Meters, MetersTolerance); - Assert.Equal(LengthUnit.Meter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 м", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Meters, MetersTolerance); - Assert.Equal(LengthUnit.Meter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 米", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Meters, MetersTolerance); - Assert.Equal(LengthUnit.Meter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 µin", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microinches, MicroinchesTolerance); - Assert.Equal(LengthUnit.Microinch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 микродюйм", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Microinches, MicroinchesTolerance); - Assert.Equal(LengthUnit.Microinch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 微英寸", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Microinches, MicroinchesTolerance); - Assert.Equal(LengthUnit.Microinch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 µm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Micrometers, MicrometersTolerance); - Assert.Equal(LengthUnit.Micrometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 мкм", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Micrometers, MicrometersTolerance); - Assert.Equal(LengthUnit.Micrometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 微米", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Micrometers, MicrometersTolerance); - Assert.Equal(LengthUnit.Micrometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 mil", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Mils, MilsTolerance); - Assert.Equal(LengthUnit.Mil, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 мил", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Mils, MilsTolerance); - Assert.Equal(LengthUnit.Mil, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 密耳", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Mils, MilsTolerance); - Assert.Equal(LengthUnit.Mil, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 mi", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Miles, MilesTolerance); - Assert.Equal(LengthUnit.Mile, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 миля", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Miles, MilesTolerance); - Assert.Equal(LengthUnit.Mile, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 英里", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Miles, MilesTolerance); - Assert.Equal(LengthUnit.Mile, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millimeters, MillimetersTolerance); - Assert.Equal(LengthUnit.Millimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 мм", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Millimeters, MillimetersTolerance); - Assert.Equal(LengthUnit.Millimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 毫米", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Millimeters, MillimetersTolerance); - Assert.Equal(LengthUnit.Millimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 nm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanometers, NanometersTolerance); - Assert.Equal(LengthUnit.Nanometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 нм", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Nanometers, NanometersTolerance); - Assert.Equal(LengthUnit.Nanometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 纳米", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Nanometers, NanometersTolerance); - Assert.Equal(LengthUnit.Nanometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 NM", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NauticalMiles, NauticalMilesTolerance); - Assert.Equal(LengthUnit.NauticalMile, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 nmi", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NauticalMiles, NauticalMilesTolerance); - Assert.Equal(LengthUnit.NauticalMile, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 мил", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.NauticalMiles, NauticalMilesTolerance); - Assert.Equal(LengthUnit.NauticalMile, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 纳米", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.NauticalMiles, NauticalMilesTolerance); - Assert.Equal(LengthUnit.NauticalMile, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 pc", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Parsecs, ParsecsTolerance); - Assert.Equal(LengthUnit.Parsec, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 pm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Picometers, PicometersTolerance); - Assert.Equal(LengthUnit.Picometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 пм", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Picometers, PicometersTolerance); - Assert.Equal(LengthUnit.Picometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 皮米", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Picometers, PicometersTolerance); - Assert.Equal(LengthUnit.Picometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 pica", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PrinterPicas, PrinterPicasTolerance); - Assert.Equal(LengthUnit.PrinterPica, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 pt", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PrinterPoints, PrinterPointsTolerance); - Assert.Equal(LengthUnit.PrinterPoint, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 shackle", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Shackles, ShacklesTolerance); - Assert.Equal(LengthUnit.Shackle, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 R⊙", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SolarRadiuses, SolarRadiusesTolerance); - Assert.Equal(LengthUnit.SolarRadius, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 twip", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Twips, TwipsTolerance); - Assert.Equal(LengthUnit.Twip, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 ftUS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.UsSurveyFeet, UsSurveyFeetTolerance); - Assert.Equal(LengthUnit.UsSurveyFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 yd", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Yards, YardsTolerance); - Assert.Equal(LengthUnit.Yard, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 ярд", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Yards, YardsTolerance); - Assert.Equal(LengthUnit.Yard, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Length.Parse("1 码", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Yards, YardsTolerance); - Assert.Equal(LengthUnit.Yard, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - } - - [Fact] - public void TryParse() - { - { - Assert.True(Length.TryParse("1 Å", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Angstroms, AngstromsTolerance); - Assert.Equal(LengthUnit.Angstrom, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 A", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Angstroms, AngstromsTolerance); - Assert.Equal(LengthUnit.Angstrom, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 au", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.AstronomicalUnits, AstronomicalUnitsTolerance); - Assert.Equal(LengthUnit.AstronomicalUnit, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 ua", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.AstronomicalUnits, AstronomicalUnitsTolerance); - Assert.Equal(LengthUnit.AstronomicalUnit, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Centimeters, CentimetersTolerance); - Assert.Equal(LengthUnit.Centimeter, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 см", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Centimeters, CentimetersTolerance); - Assert.Equal(LengthUnit.Centimeter, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 厘米", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Centimeters, CentimetersTolerance); - Assert.Equal(LengthUnit.Centimeter, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 ch", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Chains, ChainsTolerance); - Assert.Equal(LengthUnit.Chain, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 dam", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Decameters, DecametersTolerance); - Assert.Equal(LengthUnit.Decameter, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 дам", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Decameters, DecametersTolerance); - Assert.Equal(LengthUnit.Decameter, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 十米", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Decameters, DecametersTolerance); - Assert.Equal(LengthUnit.Decameter, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 дм", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Decimeters, DecimetersTolerance); - Assert.Equal(LengthUnit.Decimeter, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 分米", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Decimeters, DecimetersTolerance); - Assert.Equal(LengthUnit.Decimeter, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 fathom", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Fathoms, FathomsTolerance); - Assert.Equal(LengthUnit.Fathom, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 fm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Femtometers, FemtometersTolerance); - Assert.Equal(LengthUnit.Femtometer, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 фм", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Femtometers, FemtometersTolerance); - Assert.Equal(LengthUnit.Femtometer, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 飞米", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Femtometers, FemtometersTolerance); - Assert.Equal(LengthUnit.Femtometer, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Feet, FeetTolerance); - Assert.Equal(LengthUnit.Foot, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 '", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Feet, FeetTolerance); - Assert.Equal(LengthUnit.Foot, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 ′", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Feet, FeetTolerance); - Assert.Equal(LengthUnit.Foot, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 фут", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Feet, FeetTolerance); - Assert.Equal(LengthUnit.Foot, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 英尺", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Feet, FeetTolerance); - Assert.Equal(LengthUnit.Foot, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 Gm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gigameters, GigametersTolerance); - Assert.Equal(LengthUnit.Gigameter, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 吉米", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gigameters, GigametersTolerance); - Assert.Equal(LengthUnit.Gigameter, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Hands, HandsTolerance); - Assert.Equal(LengthUnit.Hand, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 hh", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Hands, HandsTolerance); - Assert.Equal(LengthUnit.Hand, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 hm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Hectometers, HectometersTolerance); - Assert.Equal(LengthUnit.Hectometer, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 百米", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Hectometers, HectometersTolerance); - Assert.Equal(LengthUnit.Hectometer, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 in", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Inches, InchesTolerance); - Assert.Equal(LengthUnit.Inch, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 \"", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Inches, InchesTolerance); - Assert.Equal(LengthUnit.Inch, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 ″", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Inches, InchesTolerance); - Assert.Equal(LengthUnit.Inch, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 дюйм", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Inches, InchesTolerance); - Assert.Equal(LengthUnit.Inch, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 英寸", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Inches, InchesTolerance); - Assert.Equal(LengthUnit.Inch, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 kft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilofeet, KilofeetTolerance); - Assert.Equal(LengthUnit.Kilofoot, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 k'", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilofeet, KilofeetTolerance); - Assert.Equal(LengthUnit.Kilofoot, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 k′", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilofeet, KilofeetTolerance); - Assert.Equal(LengthUnit.Kilofoot, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 кфут", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilofeet, KilofeetTolerance); - Assert.Equal(LengthUnit.Kilofoot, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 千英尺", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilofeet, KilofeetTolerance); - Assert.Equal(LengthUnit.Kilofoot, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 kly", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilolightYears, KilolightYearsTolerance); - Assert.Equal(LengthUnit.KilolightYear, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 km", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilometers, KilometersTolerance); - Assert.Equal(LengthUnit.Kilometer, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 км", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilometers, KilometersTolerance); - Assert.Equal(LengthUnit.Kilometer, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 千米", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilometers, KilometersTolerance); - Assert.Equal(LengthUnit.Kilometer, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 kpc", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kiloparsecs, KiloparsecsTolerance); - Assert.Equal(LengthUnit.Kiloparsec, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 kyd", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kiloyards, KiloyardsTolerance); - Assert.Equal(LengthUnit.Kiloyard, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 кярд", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kiloyards, KiloyardsTolerance); - Assert.Equal(LengthUnit.Kiloyard, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 千码", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kiloyards, KiloyardsTolerance); - Assert.Equal(LengthUnit.Kiloyard, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 ly", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.LightYears, LightYearsTolerance); - Assert.Equal(LengthUnit.LightYear, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 Mly", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegalightYears, MegalightYearsTolerance); - Assert.Equal(LengthUnit.MegalightYear, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 兆米", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Megameters, MegametersTolerance); - Assert.Equal(LengthUnit.Megameter, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 Mpc", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Megaparsecs, MegaparsecsTolerance); - Assert.Equal(LengthUnit.Megaparsec, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Meters, MetersTolerance); - Assert.Equal(LengthUnit.Meter, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 м", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Meters, MetersTolerance); - Assert.Equal(LengthUnit.Meter, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 米", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Meters, MetersTolerance); - Assert.Equal(LengthUnit.Meter, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 µin", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microinches, MicroinchesTolerance); - Assert.Equal(LengthUnit.Microinch, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 микродюйм", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microinches, MicroinchesTolerance); - Assert.Equal(LengthUnit.Microinch, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 微英寸", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microinches, MicroinchesTolerance); - Assert.Equal(LengthUnit.Microinch, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 µm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Micrometers, MicrometersTolerance); - Assert.Equal(LengthUnit.Micrometer, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 мкм", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Micrometers, MicrometersTolerance); - Assert.Equal(LengthUnit.Micrometer, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 微米", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Micrometers, MicrometersTolerance); - Assert.Equal(LengthUnit.Micrometer, parsed.Unit); - } - - { - Assert.True(Length.TryParse("1 mil", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Mils, MilsTolerance); - Assert.Equal(LengthUnit.Mil, parsed.Unit); - } + Assert.Equal(expectedValue, convertedValue); + } - { - Assert.True(Length.TryParse("1 密耳", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Mils, MilsTolerance); - Assert.Equal(LengthUnit.Mil, parsed.Unit); - } + [Fact] + public void As_UnitSystem_ThrowsArgumentNullExceptionIfNull() + { + var quantity = new Length(value: 1, unit: Length.BaseUnit); + UnitSystem nullUnitSystem = null!; + Assert.Throws(() => quantity.As(nullUnitSystem)); + } - { - Assert.True(Length.TryParse("1 mi", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Miles, MilesTolerance); - Assert.Equal(LengthUnit.Mile, parsed.Unit); - } + [Fact] + public void As_UnitSystem_ThrowsArgumentExceptionIfNotSupported() + { + var quantity = new Length(value: 1, unit: Length.BaseUnit); + var unsupportedUnitSystem = new UnitSystem(UnsupportedBaseUnits); + Assert.Throws(() => quantity.As(unsupportedUnitSystem)); + } - { - Assert.True(Length.TryParse("1 миля", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Miles, MilesTolerance); - Assert.Equal(LengthUnit.Mile, parsed.Unit); - } + [Fact] + public virtual void ToUnit_UnitSystem_SI_ReturnsQuantityInSIUnits() + { + var quantity = new Length(value: 1, unit: Length.BaseUnit); + var expectedUnit = Length.Info.GetDefaultUnit(UnitSystem.SI); + var expectedValue = quantity.As(expectedUnit); + Assert.Multiple(() => { - Assert.True(Length.TryParse("1 英里", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Miles, MilesTolerance); - Assert.Equal(LengthUnit.Mile, parsed.Unit); - } + Length quantityToConvert = quantity; - { - Assert.True(Length.TryParse("1 毫米", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Millimeters, MillimetersTolerance); - Assert.Equal(LengthUnit.Millimeter, parsed.Unit); - } + Length convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); + Assert.Equal(expectedUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }, () => { - Assert.True(Length.TryParse("1 нм", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanometers, NanometersTolerance); - Assert.Equal(LengthUnit.Nanometer, parsed.Unit); - } + IQuantity quantityToConvert = quantity; - { - Assert.True(Length.TryParse("1 nmi", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NauticalMiles, NauticalMilesTolerance); - Assert.Equal(LengthUnit.NauticalMile, parsed.Unit); - } + IQuantity convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); + Assert.Equal(expectedUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }, () => { - Assert.True(Length.TryParse("1 pc", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Parsecs, ParsecsTolerance); - Assert.Equal(LengthUnit.Parsec, parsed.Unit); - } + IQuantity quantityToConvert = quantity; - { - Assert.True(Length.TryParse("1 pm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Picometers, PicometersTolerance); - Assert.Equal(LengthUnit.Picometer, parsed.Unit); - } + IQuantity convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); - { - Assert.True(Length.TryParse("1 пм", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Picometers, PicometersTolerance); - Assert.Equal(LengthUnit.Picometer, parsed.Unit); - } + Assert.Equal(expectedUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }); + } + [Fact] + public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() + { + UnitSystem nullUnitSystem = null!; + Assert.Multiple(() => { - Assert.True(Length.TryParse("1 皮米", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Picometers, PicometersTolerance); - Assert.Equal(LengthUnit.Picometer, parsed.Unit); - } - + var quantity = new Length(value: 1, unit: Length.BaseUnit); + Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); + }, () => { - Assert.True(Length.TryParse("1 shackle", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Shackles, ShacklesTolerance); - Assert.Equal(LengthUnit.Shackle, parsed.Unit); - } - + IQuantity quantity = new Length(value: 1, unit: Length.BaseUnit); + Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); + }, () => { - Assert.True(Length.TryParse("1 R⊙", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SolarRadiuses, SolarRadiusesTolerance); - Assert.Equal(LengthUnit.SolarRadius, parsed.Unit); - } + IQuantity quantity = new Length(value: 1, unit: Length.BaseUnit); + Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); + }); + } + [Fact] + public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() + { + var unsupportedUnitSystem = new UnitSystem(UnsupportedBaseUnits); + Assert.Multiple(() => { - Assert.True(Length.TryParse("1 twip", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Twips, TwipsTolerance); - Assert.Equal(LengthUnit.Twip, parsed.Unit); - } - + var quantity = new Length(value: 1, unit: Length.BaseUnit); + Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); + }, () => { - Assert.True(Length.TryParse("1 ftUS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UsSurveyFeet, UsSurveyFeetTolerance); - Assert.Equal(LengthUnit.UsSurveyFoot, parsed.Unit); - } - + IQuantity quantity = new Length(value: 1, unit: Length.BaseUnit); + Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); + }, () => { - Assert.True(Length.TryParse("1 yd", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Yards, YardsTolerance); - Assert.Equal(LengthUnit.Yard, parsed.Unit); - } + IQuantity quantity = new Length(value: 1, unit: Length.BaseUnit); + Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); + }); + } - { - Assert.True(Length.TryParse("1 ярд", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Yards, YardsTolerance); - Assert.Equal(LengthUnit.Yard, parsed.Unit); - } + [Theory] + [InlineData("en-US", "4.2 Å", LengthUnit.Angstrom, 4.2)] + [InlineData("en-US", "4.2 A", LengthUnit.Angstrom, 4.2)] + [InlineData("en-US", "4.2 au", LengthUnit.AstronomicalUnit, 4.2)] + [InlineData("en-US", "4.2 ua", LengthUnit.AstronomicalUnit, 4.2)] + [InlineData("en-US", "4.2 cm", LengthUnit.Centimeter, 4.2)] + [InlineData("en-US", "4.2 ch", LengthUnit.Chain, 4.2)] + [InlineData("en-US", "4.2 DM", LengthUnit.DataMile, 4.2)] + [InlineData("en-US", "4.2 dam", LengthUnit.Decameter, 4.2)] + [InlineData("en-US", "4.2 dm", LengthUnit.Decimeter, 4.2)] + [InlineData("en-US", "4.2 fathom", LengthUnit.Fathom, 4.2)] + [InlineData("en-US", "4.2 fm", LengthUnit.Femtometer, 4.2)] + [InlineData("en-US", "4.2 ft", LengthUnit.Foot, 4.2)] + [InlineData("en-US", "4.2 '", LengthUnit.Foot, 4.2)] + [InlineData("en-US", "4.2 ′", LengthUnit.Foot, 4.2)] + [InlineData("en-US", "4.2 Gm", LengthUnit.Gigameter, 4.2)] + [InlineData("en-US", "4.2 h", LengthUnit.Hand, 4.2)] + [InlineData("en-US", "4.2 hh", LengthUnit.Hand, 4.2)] + [InlineData("en-US", "4.2 hm", LengthUnit.Hectometer, 4.2)] + [InlineData("en-US", "4.2 in", LengthUnit.Inch, 4.2)] + [InlineData("en-US", "4.2 \"", LengthUnit.Inch, 4.2)] + [InlineData("en-US", "4.2 ″", LengthUnit.Inch, 4.2)] + [InlineData("en-US", "4.2 kft", LengthUnit.Kilofoot, 4.2)] + [InlineData("en-US", "4.2 k'", LengthUnit.Kilofoot, 4.2)] + [InlineData("en-US", "4.2 k′", LengthUnit.Kilofoot, 4.2)] + [InlineData("en-US", "4.2 kly", LengthUnit.KilolightYear, 4.2)] + [InlineData("en-US", "4.2 km", LengthUnit.Kilometer, 4.2)] + [InlineData("en-US", "4.2 kpc", LengthUnit.Kiloparsec, 4.2)] + [InlineData("en-US", "4.2 kyd", LengthUnit.Kiloyard, 4.2)] + [InlineData("en-US", "4.2 ly", LengthUnit.LightYear, 4.2)] + [InlineData("en-US", "4.2 Mly", LengthUnit.MegalightYear, 4.2)] + [InlineData("en-US", "4.2 Mm", LengthUnit.Megameter, 4.2)] + [InlineData("en-US", "4.2 Mpc", LengthUnit.Megaparsec, 4.2)] + [InlineData("en-US", "4.2 m", LengthUnit.Meter, 4.2)] + [InlineData("en-US", "4.2 µin", LengthUnit.Microinch, 4.2)] + [InlineData("en-US", "4.2 µm", LengthUnit.Micrometer, 4.2)] + [InlineData("en-US", "4.2 mil", LengthUnit.Mil, 4.2)] + [InlineData("en-US", "4.2 mi", LengthUnit.Mile, 4.2)] + [InlineData("en-US", "4.2 mm", LengthUnit.Millimeter, 4.2)] + [InlineData("en-US", "4.2 nm", LengthUnit.Nanometer, 4.2)] + [InlineData("en-US", "4.2 NM", LengthUnit.NauticalMile, 4.2)] + [InlineData("en-US", "4.2 nmi", LengthUnit.NauticalMile, 4.2)] + [InlineData("en-US", "4.2 pc", LengthUnit.Parsec, 4.2)] + [InlineData("en-US", "4.2 pm", LengthUnit.Picometer, 4.2)] + [InlineData("en-US", "4.2 shackle", LengthUnit.Shackle, 4.2)] + [InlineData("en-US", "4.2 R⊙", LengthUnit.SolarRadius, 4.2)] + [InlineData("en-US", "4.2 twip", LengthUnit.Twip, 4.2)] + [InlineData("en-US", "4.2 ftUS", LengthUnit.UsSurveyFoot, 4.2)] + [InlineData("en-US", "4.2 yd", LengthUnit.Yard, 4.2)] + [InlineData("ru-RU", "4,2 см", LengthUnit.Centimeter, 4.2)] + [InlineData("ru-RU", "4,2 дам", LengthUnit.Decameter, 4.2)] + [InlineData("ru-RU", "4,2 дм", LengthUnit.Decimeter, 4.2)] + [InlineData("ru-RU", "4,2 фм", LengthUnit.Femtometer, 4.2)] + [InlineData("ru-RU", "4,2 фут", LengthUnit.Foot, 4.2)] + [InlineData("ru-RU", "4,2 Гм", LengthUnit.Gigameter, 4.2)] + [InlineData("ru-RU", "4,2 гм", LengthUnit.Hectometer, 4.2)] + [InlineData("ru-RU", "4,2 дюйм", LengthUnit.Inch, 4.2)] + [InlineData("ru-RU", "4,2 кфут", LengthUnit.Kilofoot, 4.2)] + [InlineData("ru-RU", "4,2 км", LengthUnit.Kilometer, 4.2)] + [InlineData("ru-RU", "4,2 кярд", LengthUnit.Kiloyard, 4.2)] + [InlineData("ru-RU", "4,2 Мм", LengthUnit.Megameter, 4.2)] + [InlineData("ru-RU", "4,2 м", LengthUnit.Meter, 4.2)] + [InlineData("ru-RU", "4,2 микродюйм", LengthUnit.Microinch, 4.2)] + [InlineData("ru-RU", "4,2 мкм", LengthUnit.Micrometer, 4.2)] + [InlineData("ru-RU", "4,2 миля", LengthUnit.Mile, 4.2)] + [InlineData("ru-RU", "4,2 мм", LengthUnit.Millimeter, 4.2)] + [InlineData("ru-RU", "4,2 нм", LengthUnit.Nanometer, 4.2)] + [InlineData("ru-RU", "4,2 пм", LengthUnit.Picometer, 4.2)] + [InlineData("ru-RU", "4,2 ярд", LengthUnit.Yard, 4.2)] + [InlineData("zh-CN", "4.2 厘米", LengthUnit.Centimeter, 4.2)] + [InlineData("zh-CN", "4.2 十米", LengthUnit.Decameter, 4.2)] + [InlineData("zh-CN", "4.2 分米", LengthUnit.Decimeter, 4.2)] + [InlineData("zh-CN", "4.2 飞米", LengthUnit.Femtometer, 4.2)] + [InlineData("zh-CN", "4.2 英尺", LengthUnit.Foot, 4.2)] + [InlineData("zh-CN", "4.2 吉米", LengthUnit.Gigameter, 4.2)] + [InlineData("zh-CN", "4.2 百米", LengthUnit.Hectometer, 4.2)] + [InlineData("zh-CN", "4.2 英寸", LengthUnit.Inch, 4.2)] + [InlineData("zh-CN", "4.2 千英尺", LengthUnit.Kilofoot, 4.2)] + [InlineData("zh-CN", "4.2 千米", LengthUnit.Kilometer, 4.2)] + [InlineData("zh-CN", "4.2 千码", LengthUnit.Kiloyard, 4.2)] + [InlineData("zh-CN", "4.2 兆米", LengthUnit.Megameter, 4.2)] + [InlineData("zh-CN", "4.2 米", LengthUnit.Meter, 4.2)] + [InlineData("zh-CN", "4.2 微英寸", LengthUnit.Microinch, 4.2)] + [InlineData("zh-CN", "4.2 微米", LengthUnit.Micrometer, 4.2)] + [InlineData("zh-CN", "4.2 密耳", LengthUnit.Mil, 4.2)] + [InlineData("zh-CN", "4.2 英里", LengthUnit.Mile, 4.2)] + [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, decimal expectedValue) + { + using var _ = new CultureScope(culture); + var parsed = Length.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); + } - { - Assert.True(Length.TryParse("1 码", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Yards, YardsTolerance); - Assert.Equal(LengthUnit.Yard, parsed.Unit); - } + [Theory] + [InlineData("en-US", "1 pica")] // [DtpPica, PrinterPica] + [InlineData("en-US", "1 pt")] // [DtpPoint, PrinterPoint] + [InlineData("ru-RU", "1 мил")] // [Mil, NauticalMile] + [InlineData("zh-CN", "1 纳米")] // [Nanometer, NauticalMile] + public void ParseWithAmbiguousAbbreviation(string culture, string quantityString) + { + Assert.Throws(() => Length.Parse(quantityString, CultureInfo.GetCultureInfo(culture))); + } + + [Theory] + [InlineData("en-US", "4.2 Å", LengthUnit.Angstrom, 4.2)] + [InlineData("en-US", "4.2 A", LengthUnit.Angstrom, 4.2)] + [InlineData("en-US", "4.2 au", LengthUnit.AstronomicalUnit, 4.2)] + [InlineData("en-US", "4.2 ua", LengthUnit.AstronomicalUnit, 4.2)] + [InlineData("en-US", "4.2 cm", LengthUnit.Centimeter, 4.2)] + [InlineData("en-US", "4.2 ch", LengthUnit.Chain, 4.2)] + [InlineData("en-US", "4.2 DM", LengthUnit.DataMile, 4.2)] + [InlineData("en-US", "4.2 dam", LengthUnit.Decameter, 4.2)] + [InlineData("en-US", "4.2 dm", LengthUnit.Decimeter, 4.2)] + [InlineData("en-US", "4.2 fathom", LengthUnit.Fathom, 4.2)] + [InlineData("en-US", "4.2 fm", LengthUnit.Femtometer, 4.2)] + [InlineData("en-US", "4.2 ft", LengthUnit.Foot, 4.2)] + [InlineData("en-US", "4.2 '", LengthUnit.Foot, 4.2)] + [InlineData("en-US", "4.2 ′", LengthUnit.Foot, 4.2)] + [InlineData("en-US", "4.2 Gm", LengthUnit.Gigameter, 4.2)] + [InlineData("en-US", "4.2 h", LengthUnit.Hand, 4.2)] + [InlineData("en-US", "4.2 hh", LengthUnit.Hand, 4.2)] + [InlineData("en-US", "4.2 hm", LengthUnit.Hectometer, 4.2)] + [InlineData("en-US", "4.2 in", LengthUnit.Inch, 4.2)] + [InlineData("en-US", "4.2 \"", LengthUnit.Inch, 4.2)] + [InlineData("en-US", "4.2 ″", LengthUnit.Inch, 4.2)] + [InlineData("en-US", "4.2 kft", LengthUnit.Kilofoot, 4.2)] + [InlineData("en-US", "4.2 k'", LengthUnit.Kilofoot, 4.2)] + [InlineData("en-US", "4.2 k′", LengthUnit.Kilofoot, 4.2)] + [InlineData("en-US", "4.2 kly", LengthUnit.KilolightYear, 4.2)] + [InlineData("en-US", "4.2 km", LengthUnit.Kilometer, 4.2)] + [InlineData("en-US", "4.2 kpc", LengthUnit.Kiloparsec, 4.2)] + [InlineData("en-US", "4.2 kyd", LengthUnit.Kiloyard, 4.2)] + [InlineData("en-US", "4.2 ly", LengthUnit.LightYear, 4.2)] + [InlineData("en-US", "4.2 Mly", LengthUnit.MegalightYear, 4.2)] + [InlineData("en-US", "4.2 Mm", LengthUnit.Megameter, 4.2)] + [InlineData("en-US", "4.2 Mpc", LengthUnit.Megaparsec, 4.2)] + [InlineData("en-US", "4.2 m", LengthUnit.Meter, 4.2)] + [InlineData("en-US", "4.2 µin", LengthUnit.Microinch, 4.2)] + [InlineData("en-US", "4.2 µm", LengthUnit.Micrometer, 4.2)] + [InlineData("en-US", "4.2 mil", LengthUnit.Mil, 4.2)] + [InlineData("en-US", "4.2 mi", LengthUnit.Mile, 4.2)] + [InlineData("en-US", "4.2 mm", LengthUnit.Millimeter, 4.2)] + [InlineData("en-US", "4.2 nm", LengthUnit.Nanometer, 4.2)] + [InlineData("en-US", "4.2 NM", LengthUnit.NauticalMile, 4.2)] + [InlineData("en-US", "4.2 nmi", LengthUnit.NauticalMile, 4.2)] + [InlineData("en-US", "4.2 pc", LengthUnit.Parsec, 4.2)] + [InlineData("en-US", "4.2 pm", LengthUnit.Picometer, 4.2)] + [InlineData("en-US", "4.2 shackle", LengthUnit.Shackle, 4.2)] + [InlineData("en-US", "4.2 R⊙", LengthUnit.SolarRadius, 4.2)] + [InlineData("en-US", "4.2 twip", LengthUnit.Twip, 4.2)] + [InlineData("en-US", "4.2 ftUS", LengthUnit.UsSurveyFoot, 4.2)] + [InlineData("en-US", "4.2 yd", LengthUnit.Yard, 4.2)] + [InlineData("ru-RU", "4,2 см", LengthUnit.Centimeter, 4.2)] + [InlineData("ru-RU", "4,2 дам", LengthUnit.Decameter, 4.2)] + [InlineData("ru-RU", "4,2 дм", LengthUnit.Decimeter, 4.2)] + [InlineData("ru-RU", "4,2 фм", LengthUnit.Femtometer, 4.2)] + [InlineData("ru-RU", "4,2 фут", LengthUnit.Foot, 4.2)] + [InlineData("ru-RU", "4,2 Гм", LengthUnit.Gigameter, 4.2)] + [InlineData("ru-RU", "4,2 гм", LengthUnit.Hectometer, 4.2)] + [InlineData("ru-RU", "4,2 дюйм", LengthUnit.Inch, 4.2)] + [InlineData("ru-RU", "4,2 кфут", LengthUnit.Kilofoot, 4.2)] + [InlineData("ru-RU", "4,2 км", LengthUnit.Kilometer, 4.2)] + [InlineData("ru-RU", "4,2 кярд", LengthUnit.Kiloyard, 4.2)] + [InlineData("ru-RU", "4,2 Мм", LengthUnit.Megameter, 4.2)] + [InlineData("ru-RU", "4,2 м", LengthUnit.Meter, 4.2)] + [InlineData("ru-RU", "4,2 микродюйм", LengthUnit.Microinch, 4.2)] + [InlineData("ru-RU", "4,2 мкм", LengthUnit.Micrometer, 4.2)] + [InlineData("ru-RU", "4,2 миля", LengthUnit.Mile, 4.2)] + [InlineData("ru-RU", "4,2 мм", LengthUnit.Millimeter, 4.2)] + [InlineData("ru-RU", "4,2 нм", LengthUnit.Nanometer, 4.2)] + [InlineData("ru-RU", "4,2 пм", LengthUnit.Picometer, 4.2)] + [InlineData("ru-RU", "4,2 ярд", LengthUnit.Yard, 4.2)] + [InlineData("zh-CN", "4.2 厘米", LengthUnit.Centimeter, 4.2)] + [InlineData("zh-CN", "4.2 十米", LengthUnit.Decameter, 4.2)] + [InlineData("zh-CN", "4.2 分米", LengthUnit.Decimeter, 4.2)] + [InlineData("zh-CN", "4.2 飞米", LengthUnit.Femtometer, 4.2)] + [InlineData("zh-CN", "4.2 英尺", LengthUnit.Foot, 4.2)] + [InlineData("zh-CN", "4.2 吉米", LengthUnit.Gigameter, 4.2)] + [InlineData("zh-CN", "4.2 百米", LengthUnit.Hectometer, 4.2)] + [InlineData("zh-CN", "4.2 英寸", LengthUnit.Inch, 4.2)] + [InlineData("zh-CN", "4.2 千英尺", LengthUnit.Kilofoot, 4.2)] + [InlineData("zh-CN", "4.2 千米", LengthUnit.Kilometer, 4.2)] + [InlineData("zh-CN", "4.2 千码", LengthUnit.Kiloyard, 4.2)] + [InlineData("zh-CN", "4.2 兆米", LengthUnit.Megameter, 4.2)] + [InlineData("zh-CN", "4.2 米", LengthUnit.Meter, 4.2)] + [InlineData("zh-CN", "4.2 微英寸", LengthUnit.Microinch, 4.2)] + [InlineData("zh-CN", "4.2 微米", LengthUnit.Micrometer, 4.2)] + [InlineData("zh-CN", "4.2 密耳", LengthUnit.Mil, 4.2)] + [InlineData("zh-CN", "4.2 英里", LengthUnit.Mile, 4.2)] + [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, decimal expectedValue) + { + using var _ = new CultureScope(culture); + Assert.True(Length.TryParse(quantityString, out Length parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); + } + [Theory] + [InlineData("en-US", "1 pica")] // [DtpPica, PrinterPica] + [InlineData("en-US", "1 pt")] // [DtpPoint, PrinterPoint] + [InlineData("ru-RU", "1 мил")] // [Mil, NauticalMile] + [InlineData("zh-CN", "1 纳米")] // [Nanometer, NauticalMile] + public void TryParseWithAmbiguousAbbreviation(string culture, string quantityString) + { + Assert.False(Length.TryParse(quantityString, CultureInfo.GetCultureInfo(culture), out _)); } [Theory] @@ -2457,6 +1539,112 @@ public void TryParseUnitWithAmbiguousAbbreviation(string culture, string abbrevi Assert.False(Length.TryParseUnit(abbreviation, CultureInfo.GetCultureInfo(culture), out _)); } + [Theory] + [InlineData("en-US", LengthUnit.Angstrom, "Å")] + [InlineData("en-US", LengthUnit.AstronomicalUnit, "au")] + [InlineData("en-US", LengthUnit.Centimeter, "cm")] + [InlineData("en-US", LengthUnit.Chain, "ch")] + [InlineData("en-US", LengthUnit.DataMile, "DM")] + [InlineData("en-US", LengthUnit.Decameter, "dam")] + [InlineData("en-US", LengthUnit.Decimeter, "dm")] + [InlineData("en-US", LengthUnit.DtpPica, "pica")] + [InlineData("en-US", LengthUnit.DtpPoint, "pt")] + [InlineData("en-US", LengthUnit.Fathom, "fathom")] + [InlineData("en-US", LengthUnit.Femtometer, "fm")] + [InlineData("en-US", LengthUnit.Foot, "ft")] + [InlineData("en-US", LengthUnit.Gigameter, "Gm")] + [InlineData("en-US", LengthUnit.Hand, "h")] + [InlineData("en-US", LengthUnit.Hectometer, "hm")] + [InlineData("en-US", LengthUnit.Inch, "in")] + [InlineData("en-US", LengthUnit.Kilofoot, "kft")] + [InlineData("en-US", LengthUnit.KilolightYear, "kly")] + [InlineData("en-US", LengthUnit.Kilometer, "km")] + [InlineData("en-US", LengthUnit.Kiloparsec, "kpc")] + [InlineData("en-US", LengthUnit.Kiloyard, "kyd")] + [InlineData("en-US", LengthUnit.LightYear, "ly")] + [InlineData("en-US", LengthUnit.MegalightYear, "Mly")] + [InlineData("en-US", LengthUnit.Megameter, "Mm")] + [InlineData("en-US", LengthUnit.Megaparsec, "Mpc")] + [InlineData("en-US", LengthUnit.Meter, "m")] + [InlineData("en-US", LengthUnit.Microinch, "µin")] + [InlineData("en-US", LengthUnit.Micrometer, "µm")] + [InlineData("en-US", LengthUnit.Mil, "mil")] + [InlineData("en-US", LengthUnit.Mile, "mi")] + [InlineData("en-US", LengthUnit.Millimeter, "mm")] + [InlineData("en-US", LengthUnit.Nanometer, "nm")] + [InlineData("en-US", LengthUnit.NauticalMile, "NM")] + [InlineData("en-US", LengthUnit.Parsec, "pc")] + [InlineData("en-US", LengthUnit.Picometer, "pm")] + [InlineData("en-US", LengthUnit.PrinterPica, "pica")] + [InlineData("en-US", LengthUnit.PrinterPoint, "pt")] + [InlineData("en-US", LengthUnit.Shackle, "shackle")] + [InlineData("en-US", LengthUnit.SolarRadius, "R⊙")] + [InlineData("en-US", LengthUnit.Twip, "twip")] + [InlineData("en-US", LengthUnit.UsSurveyFoot, "ftUS")] + [InlineData("en-US", LengthUnit.Yard, "yd")] + [InlineData("ru-RU", LengthUnit.Centimeter, "см")] + [InlineData("ru-RU", LengthUnit.Decameter, "дам")] + [InlineData("ru-RU", LengthUnit.Decimeter, "дм")] + [InlineData("ru-RU", LengthUnit.Femtometer, "фм")] + [InlineData("ru-RU", LengthUnit.Foot, "фут")] + [InlineData("ru-RU", LengthUnit.Gigameter, "Гм")] + [InlineData("ru-RU", LengthUnit.Hectometer, "гм")] + [InlineData("ru-RU", LengthUnit.Inch, "дюйм")] + [InlineData("ru-RU", LengthUnit.Kilofoot, "кфут")] + [InlineData("ru-RU", LengthUnit.Kilometer, "км")] + [InlineData("ru-RU", LengthUnit.Kiloyard, "кярд")] + [InlineData("ru-RU", LengthUnit.Megameter, "Мм")] + [InlineData("ru-RU", LengthUnit.Meter, "м")] + [InlineData("ru-RU", LengthUnit.Microinch, "микродюйм")] + [InlineData("ru-RU", LengthUnit.Micrometer, "мкм")] + [InlineData("ru-RU", LengthUnit.Mil, "мил")] + [InlineData("ru-RU", LengthUnit.Mile, "миля")] + [InlineData("ru-RU", LengthUnit.Millimeter, "мм")] + [InlineData("ru-RU", LengthUnit.Nanometer, "нм")] + [InlineData("ru-RU", LengthUnit.NauticalMile, "мил")] + [InlineData("ru-RU", LengthUnit.Picometer, "пм")] + [InlineData("ru-RU", LengthUnit.Yard, "ярд")] + [InlineData("zh-CN", LengthUnit.Centimeter, "厘米")] + [InlineData("zh-CN", LengthUnit.Decameter, "十米")] + [InlineData("zh-CN", LengthUnit.Decimeter, "分米")] + [InlineData("zh-CN", LengthUnit.Femtometer, "飞米")] + [InlineData("zh-CN", LengthUnit.Foot, "英尺")] + [InlineData("zh-CN", LengthUnit.Gigameter, "吉米")] + [InlineData("zh-CN", LengthUnit.Hectometer, "百米")] + [InlineData("zh-CN", LengthUnit.Inch, "英寸")] + [InlineData("zh-CN", LengthUnit.Kilofoot, "千英尺")] + [InlineData("zh-CN", LengthUnit.Kilometer, "千米")] + [InlineData("zh-CN", LengthUnit.Kiloyard, "千码")] + [InlineData("zh-CN", LengthUnit.Megameter, "兆米")] + [InlineData("zh-CN", LengthUnit.Meter, "米")] + [InlineData("zh-CN", LengthUnit.Microinch, "微英寸")] + [InlineData("zh-CN", LengthUnit.Micrometer, "微米")] + [InlineData("zh-CN", LengthUnit.Mil, "密耳")] + [InlineData("zh-CN", LengthUnit.Mile, "英里")] + [InlineData("zh-CN", LengthUnit.Millimeter, "毫米")] + [InlineData("zh-CN", LengthUnit.Nanometer, "纳米")] + [InlineData("zh-CN", LengthUnit.NauticalMile, "纳米")] + [InlineData("zh-CN", LengthUnit.Picometer, "皮米")] + [InlineData("zh-CN", LengthUnit.Yard, "码")] + public void GetAbbreviationForCulture(string culture, LengthUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Length.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Length.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Length.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(LengthUnit unit) @@ -2487,6 +1675,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); }); } @@ -2510,73 +1699,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] @@ -2622,8 +1813,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); @@ -2660,23 +1849,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = Length.FromMeters(1); - Assert.True(v.Equals(Length.FromMeters(1), MetersTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Length.Zero, MetersTolerance, ComparisonType.Relative)); - Assert.True(Length.FromMeters(100).Equals(Length.FromMeters(120), 0.3, ComparisonType.Relative)); - Assert.False(Length.FromMeters(100).Equals(Length.FromMeters(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = Length.FromMeters(1); - Assert.Throws(() => v.Equals(Length.FromMeters(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -2691,6 +1863,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(meter.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = Length.FromMeters(1); + var negativeTolerance = Length.FromMeters(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -2707,6 +1905,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() { @@ -2847,158 +2057,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Length.FromMeters(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Length.FromMeters(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Length.FromMeters(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Length.FromMeters(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Length.FromMeters(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Length.FromMeters(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Length.FromMeters(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Length.FromMeters(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Length.FromMeters(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Length.FromMeters(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Length.FromMeters(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Length.FromMeters(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Length.FromMeters(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Length.FromMeters(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Length.FromMeters(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Length.FromMeters(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Length))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Length.FromMeters(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(LengthUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Length.FromMeters(1.0); - Assert.Equal(Length.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Length.FromMeters(1.0); - Assert.Equal(Length.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Length.FromMeters(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Length.FromMeters(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Length.FromMeters(1.0); - Assert.Equal(new {Length.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 94d2ecfeee..d982231b93 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LevelTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LevelTestsBase.g.cs @@ -92,15 +92,33 @@ public void Ctor_WithNaNValue_DoNotThrowsArgumentException() [Fact] public void Level_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + LevelUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Level(1, LevelUnit.Decibel); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Level.Zero, quantityInfo.Zero); Assert.Equal("Level", quantityInfo.Name); + Assert.Equal(Level.Zero, quantityInfo.Zero); + Assert.Equal(Level.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Level.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void LevelInfo_CreateWithCustomUnitInfos() + { + LevelUnit[] expectedUnits = [LevelUnit.Decibel]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -115,11 +133,11 @@ public void DecibelToLevelUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Level.From(1, LevelUnit.Decibel); - AssertEx.EqualTolerance(1, quantity00.Decibels, DecibelsTolerance); + Assert.Equal(1, quantity00.Decibels); Assert.Equal(LevelUnit.Decibel, quantity00.Unit); var quantity01 = Level.From(1, LevelUnit.Neper); - AssertEx.EqualTolerance(1, quantity01.Nepers, NepersTolerance); + Assert.Equal(1, quantity01.Nepers); Assert.Equal(LevelUnit.Neper, quantity01.Unit); } @@ -217,40 +235,26 @@ public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() }); } - [Fact] - public void Parse() + [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, decimal expectedValue) { - try - { - var parsed = Level.Parse("1 dB", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Decibels, DecibelsTolerance); - Assert.Equal(LevelUnit.Decibel, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Level.Parse("1 Np", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nepers, NepersTolerance); - Assert.Equal(LevelUnit.Neper, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Level.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [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, decimal expectedValue) { - { - Assert.True(Level.TryParse("1 dB", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Decibels, DecibelsTolerance); - Assert.Equal(LevelUnit.Decibel, parsed.Unit); - } - - { - Assert.True(Level.TryParse("1 Np", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nepers, NepersTolerance); - Assert.Equal(LevelUnit.Neper, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Level.TryParse(quantityString, out Level parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -335,6 +339,28 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, LevelU Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", LevelUnit.Decibel, "dB")] + [InlineData("en-US", LevelUnit.Neper, "Np")] + public void GetAbbreviationForCulture(string culture, LevelUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Level.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Level.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Level.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(LevelUnit unit) @@ -365,6 +391,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); }); } @@ -388,33 +415,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(); @@ -464,8 +493,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); @@ -503,34 +530,45 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = Level.FromDecibels(1); - Assert.True(v.Equals(Level.FromDecibels(1), DecibelsTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Level.Zero, DecibelsTolerance, ComparisonType.Relative)); - Assert.True(Level.FromDecibels(100).Equals(Level.FromDecibels(120), 0.3, ComparisonType.Relative)); - Assert.False(Level.FromDecibels(100).Equals(Level.FromDecibels(120), 0.1, ComparisonType.Relative)); + Level decibel = Level.FromDecibels(1); + Assert.False(decibel.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = Level.FromDecibels(1); - Assert.Throws(() => v.Equals(Level.FromDecibels(1), -1, ComparisonType.Relative)); + Level decibel = Level.FromDecibels(1); + Assert.False(decibel.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - Level decibel = Level.FromDecibels(1); - Assert.False(decibel.Equals(new object())); + var quantity = Level.FromDecibels(firstValue); + var otherQuantity = Level.FromDecibels(secondValue); + Level maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + // note: it's currently not possible to test this due to the rounding error from (quantity - otherQuantity) + // Assert.True(quantity.Equals(otherQuantity, maxTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_DoesNotThrowArgumentOutOfRangeException() { - Level decibel = Level.FromDecibels(1); - Assert.False(decibel.Equals(null)); + // note: unlike with vector quantities- a small tolerance maybe positive in one unit and negative in another + var quantity = Level.FromDecibels(1); + var negativeTolerance = Level.FromDecibels(-1); + Assert.True(quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -549,6 +587,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() { @@ -609,158 +659,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Level.FromDecibels(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Level.FromDecibels(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Level.FromDecibels(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Level.FromDecibels(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Level.FromDecibels(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Level.FromDecibels(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Level.FromDecibels(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Level.FromDecibels(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Level.FromDecibels(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Level.FromDecibels(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Level.FromDecibels(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Level.FromDecibels(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Level.FromDecibels(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Level.FromDecibels(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Level.FromDecibels(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Level.FromDecibels(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Level))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Level.FromDecibels(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(LevelUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Level.FromDecibels(1.0); - Assert.Equal(Level.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Level.FromDecibels(1.0); - Assert.Equal(Level.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Level.FromDecibels(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Level.FromDecibels(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Level.FromDecibels(1.0); - Assert.Equal(new {Level.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 7828e2377a..652348e7b8 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LinearDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LinearDensityTestsBase.g.cs @@ -164,7 +164,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new LinearDensity(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -177,15 +177,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void LinearDensity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + LinearDensityUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new LinearDensity(1, LinearDensityUnit.KilogramPerMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(LinearDensity.Zero, quantityInfo.Zero); Assert.Equal("LinearDensity", quantityInfo.Name); + Assert.Equal(LinearDensity.Zero, quantityInfo.Zero); + Assert.Equal(LinearDensity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(LinearDensity.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void LinearDensityInfo_CreateWithCustomUnitInfos() + { + LinearDensityUnit[] expectedUnits = [LinearDensityUnit.KilogramPerMeter]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -216,75 +234,75 @@ public void KilogramPerMeterToLinearDensityUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = LinearDensity.From(1, LinearDensityUnit.GramPerCentimeter); - AssertEx.EqualTolerance(1, quantity00.GramsPerCentimeter, GramsPerCentimeterTolerance); + Assert.Equal(1, quantity00.GramsPerCentimeter); Assert.Equal(LinearDensityUnit.GramPerCentimeter, quantity00.Unit); var quantity01 = LinearDensity.From(1, LinearDensityUnit.GramPerFoot); - AssertEx.EqualTolerance(1, quantity01.GramsPerFoot, GramsPerFootTolerance); + Assert.Equal(1, quantity01.GramsPerFoot); Assert.Equal(LinearDensityUnit.GramPerFoot, quantity01.Unit); var quantity02 = LinearDensity.From(1, LinearDensityUnit.GramPerMeter); - AssertEx.EqualTolerance(1, quantity02.GramsPerMeter, GramsPerMeterTolerance); + Assert.Equal(1, quantity02.GramsPerMeter); Assert.Equal(LinearDensityUnit.GramPerMeter, quantity02.Unit); var quantity03 = LinearDensity.From(1, LinearDensityUnit.GramPerMillimeter); - AssertEx.EqualTolerance(1, quantity03.GramsPerMillimeter, GramsPerMillimeterTolerance); + Assert.Equal(1, quantity03.GramsPerMillimeter); Assert.Equal(LinearDensityUnit.GramPerMillimeter, quantity03.Unit); var quantity04 = LinearDensity.From(1, LinearDensityUnit.KilogramPerCentimeter); - AssertEx.EqualTolerance(1, quantity04.KilogramsPerCentimeter, KilogramsPerCentimeterTolerance); + Assert.Equal(1, quantity04.KilogramsPerCentimeter); Assert.Equal(LinearDensityUnit.KilogramPerCentimeter, quantity04.Unit); var quantity05 = LinearDensity.From(1, LinearDensityUnit.KilogramPerFoot); - AssertEx.EqualTolerance(1, quantity05.KilogramsPerFoot, KilogramsPerFootTolerance); + Assert.Equal(1, quantity05.KilogramsPerFoot); Assert.Equal(LinearDensityUnit.KilogramPerFoot, quantity05.Unit); var quantity06 = LinearDensity.From(1, LinearDensityUnit.KilogramPerMeter); - AssertEx.EqualTolerance(1, quantity06.KilogramsPerMeter, KilogramsPerMeterTolerance); + Assert.Equal(1, quantity06.KilogramsPerMeter); Assert.Equal(LinearDensityUnit.KilogramPerMeter, quantity06.Unit); var quantity07 = LinearDensity.From(1, LinearDensityUnit.KilogramPerMillimeter); - AssertEx.EqualTolerance(1, quantity07.KilogramsPerMillimeter, KilogramsPerMillimeterTolerance); + Assert.Equal(1, quantity07.KilogramsPerMillimeter); Assert.Equal(LinearDensityUnit.KilogramPerMillimeter, quantity07.Unit); var quantity08 = LinearDensity.From(1, LinearDensityUnit.MicrogramPerCentimeter); - AssertEx.EqualTolerance(1, quantity08.MicrogramsPerCentimeter, MicrogramsPerCentimeterTolerance); + Assert.Equal(1, quantity08.MicrogramsPerCentimeter); Assert.Equal(LinearDensityUnit.MicrogramPerCentimeter, quantity08.Unit); var quantity09 = LinearDensity.From(1, LinearDensityUnit.MicrogramPerFoot); - AssertEx.EqualTolerance(1, quantity09.MicrogramsPerFoot, MicrogramsPerFootTolerance); + Assert.Equal(1, quantity09.MicrogramsPerFoot); Assert.Equal(LinearDensityUnit.MicrogramPerFoot, quantity09.Unit); var quantity10 = LinearDensity.From(1, LinearDensityUnit.MicrogramPerMeter); - AssertEx.EqualTolerance(1, quantity10.MicrogramsPerMeter, MicrogramsPerMeterTolerance); + Assert.Equal(1, quantity10.MicrogramsPerMeter); Assert.Equal(LinearDensityUnit.MicrogramPerMeter, quantity10.Unit); var quantity11 = LinearDensity.From(1, LinearDensityUnit.MicrogramPerMillimeter); - AssertEx.EqualTolerance(1, quantity11.MicrogramsPerMillimeter, MicrogramsPerMillimeterTolerance); + Assert.Equal(1, quantity11.MicrogramsPerMillimeter); Assert.Equal(LinearDensityUnit.MicrogramPerMillimeter, quantity11.Unit); var quantity12 = LinearDensity.From(1, LinearDensityUnit.MilligramPerCentimeter); - AssertEx.EqualTolerance(1, quantity12.MilligramsPerCentimeter, MilligramsPerCentimeterTolerance); + Assert.Equal(1, quantity12.MilligramsPerCentimeter); Assert.Equal(LinearDensityUnit.MilligramPerCentimeter, quantity12.Unit); var quantity13 = LinearDensity.From(1, LinearDensityUnit.MilligramPerFoot); - AssertEx.EqualTolerance(1, quantity13.MilligramsPerFoot, MilligramsPerFootTolerance); + Assert.Equal(1, quantity13.MilligramsPerFoot); Assert.Equal(LinearDensityUnit.MilligramPerFoot, quantity13.Unit); var quantity14 = LinearDensity.From(1, LinearDensityUnit.MilligramPerMeter); - AssertEx.EqualTolerance(1, quantity14.MilligramsPerMeter, MilligramsPerMeterTolerance); + Assert.Equal(1, quantity14.MilligramsPerMeter); Assert.Equal(LinearDensityUnit.MilligramPerMeter, quantity14.Unit); var quantity15 = LinearDensity.From(1, LinearDensityUnit.MilligramPerMillimeter); - AssertEx.EqualTolerance(1, quantity15.MilligramsPerMillimeter, MilligramsPerMillimeterTolerance); + Assert.Equal(1, quantity15.MilligramsPerMillimeter); Assert.Equal(LinearDensityUnit.MilligramPerMillimeter, quantity15.Unit); var quantity16 = LinearDensity.From(1, LinearDensityUnit.PoundPerFoot); - AssertEx.EqualTolerance(1, quantity16.PoundsPerFoot, PoundsPerFootTolerance); + Assert.Equal(1, quantity16.PoundsPerFoot); Assert.Equal(LinearDensityUnit.PoundPerFoot, quantity16.Unit); var quantity17 = LinearDensity.From(1, LinearDensityUnit.PoundPerInch); - AssertEx.EqualTolerance(1, quantity17.PoundsPerInch, PoundsPerInchTolerance); + Assert.Equal(1, quantity17.PoundsPerInch); Assert.Equal(LinearDensityUnit.PoundPerInch, quantity17.Unit); } @@ -437,248 +455,58 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 g/cm", LinearDensityUnit.GramPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 g/ft", LinearDensityUnit.GramPerFoot, 4.2)] + [InlineData("en-US", "4.2 g/m", LinearDensityUnit.GramPerMeter, 4.2)] + [InlineData("en-US", "4.2 g/mm", LinearDensityUnit.GramPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 kg/cm", LinearDensityUnit.KilogramPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 kg/ft", LinearDensityUnit.KilogramPerFoot, 4.2)] + [InlineData("en-US", "4.2 kg/m", LinearDensityUnit.KilogramPerMeter, 4.2)] + [InlineData("en-US", "4.2 kg/mm", LinearDensityUnit.KilogramPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 µg/cm", LinearDensityUnit.MicrogramPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 µg/ft", LinearDensityUnit.MicrogramPerFoot, 4.2)] + [InlineData("en-US", "4.2 µg/m", LinearDensityUnit.MicrogramPerMeter, 4.2)] + [InlineData("en-US", "4.2 µg/mm", LinearDensityUnit.MicrogramPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 mg/cm", LinearDensityUnit.MilligramPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 mg/ft", LinearDensityUnit.MilligramPerFoot, 4.2)] + [InlineData("en-US", "4.2 mg/m", LinearDensityUnit.MilligramPerMeter, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = LinearDensity.Parse("1 g/cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerCentimeter, GramsPerCentimeterTolerance); - Assert.Equal(LinearDensityUnit.GramPerCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearDensity.Parse("1 g/ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerFoot, GramsPerFootTolerance); - Assert.Equal(LinearDensityUnit.GramPerFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearDensity.Parse("1 g/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerMeter, GramsPerMeterTolerance); - Assert.Equal(LinearDensityUnit.GramPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearDensity.Parse("1 g/mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerMillimeter, GramsPerMillimeterTolerance); - Assert.Equal(LinearDensityUnit.GramPerMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearDensity.Parse("1 kg/cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerCentimeter, KilogramsPerCentimeterTolerance); - Assert.Equal(LinearDensityUnit.KilogramPerCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearDensity.Parse("1 kg/ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerFoot, KilogramsPerFootTolerance); - Assert.Equal(LinearDensityUnit.KilogramPerFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearDensity.Parse("1 kg/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerMeter, KilogramsPerMeterTolerance); - Assert.Equal(LinearDensityUnit.KilogramPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearDensity.Parse("1 kg/mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerMillimeter, KilogramsPerMillimeterTolerance); - Assert.Equal(LinearDensityUnit.KilogramPerMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearDensity.Parse("1 µg/cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerCentimeter, MicrogramsPerCentimeterTolerance); - Assert.Equal(LinearDensityUnit.MicrogramPerCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearDensity.Parse("1 µg/ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerFoot, MicrogramsPerFootTolerance); - Assert.Equal(LinearDensityUnit.MicrogramPerFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearDensity.Parse("1 µg/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerMeter, MicrogramsPerMeterTolerance); - Assert.Equal(LinearDensityUnit.MicrogramPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearDensity.Parse("1 µg/mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerMillimeter, MicrogramsPerMillimeterTolerance); - Assert.Equal(LinearDensityUnit.MicrogramPerMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearDensity.Parse("1 mg/cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligramsPerCentimeter, MilligramsPerCentimeterTolerance); - Assert.Equal(LinearDensityUnit.MilligramPerCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearDensity.Parse("1 mg/ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligramsPerFoot, MilligramsPerFootTolerance); - Assert.Equal(LinearDensityUnit.MilligramPerFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearDensity.Parse("1 mg/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligramsPerMeter, MilligramsPerMeterTolerance); - Assert.Equal(LinearDensityUnit.MilligramPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearDensity.Parse("1 mg/mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligramsPerMillimeter, MilligramsPerMillimeterTolerance); - Assert.Equal(LinearDensityUnit.MilligramPerMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearDensity.Parse("1 lb/ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerFoot, PoundsPerFootTolerance); - Assert.Equal(LinearDensityUnit.PoundPerFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearDensity.Parse("1 lb/in", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerInch, PoundsPerInchTolerance); - Assert.Equal(LinearDensityUnit.PoundPerInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = LinearDensity.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 g/cm", LinearDensityUnit.GramPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 g/ft", LinearDensityUnit.GramPerFoot, 4.2)] + [InlineData("en-US", "4.2 g/m", LinearDensityUnit.GramPerMeter, 4.2)] + [InlineData("en-US", "4.2 g/mm", LinearDensityUnit.GramPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 kg/cm", LinearDensityUnit.KilogramPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 kg/ft", LinearDensityUnit.KilogramPerFoot, 4.2)] + [InlineData("en-US", "4.2 kg/m", LinearDensityUnit.KilogramPerMeter, 4.2)] + [InlineData("en-US", "4.2 kg/mm", LinearDensityUnit.KilogramPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 µg/cm", LinearDensityUnit.MicrogramPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 µg/ft", LinearDensityUnit.MicrogramPerFoot, 4.2)] + [InlineData("en-US", "4.2 µg/m", LinearDensityUnit.MicrogramPerMeter, 4.2)] + [InlineData("en-US", "4.2 µg/mm", LinearDensityUnit.MicrogramPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 mg/cm", LinearDensityUnit.MilligramPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 mg/ft", LinearDensityUnit.MilligramPerFoot, 4.2)] + [InlineData("en-US", "4.2 mg/m", LinearDensityUnit.MilligramPerMeter, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(LinearDensity.TryParse("1 g/cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerCentimeter, GramsPerCentimeterTolerance); - Assert.Equal(LinearDensityUnit.GramPerCentimeter, parsed.Unit); - } - - { - Assert.True(LinearDensity.TryParse("1 g/ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerFoot, GramsPerFootTolerance); - Assert.Equal(LinearDensityUnit.GramPerFoot, parsed.Unit); - } - - { - Assert.True(LinearDensity.TryParse("1 g/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerMeter, GramsPerMeterTolerance); - Assert.Equal(LinearDensityUnit.GramPerMeter, parsed.Unit); - } - - { - Assert.True(LinearDensity.TryParse("1 g/mm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerMillimeter, GramsPerMillimeterTolerance); - Assert.Equal(LinearDensityUnit.GramPerMillimeter, parsed.Unit); - } - - { - Assert.True(LinearDensity.TryParse("1 kg/cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerCentimeter, KilogramsPerCentimeterTolerance); - Assert.Equal(LinearDensityUnit.KilogramPerCentimeter, parsed.Unit); - } - - { - Assert.True(LinearDensity.TryParse("1 kg/ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerFoot, KilogramsPerFootTolerance); - Assert.Equal(LinearDensityUnit.KilogramPerFoot, parsed.Unit); - } - - { - Assert.True(LinearDensity.TryParse("1 kg/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerMeter, KilogramsPerMeterTolerance); - Assert.Equal(LinearDensityUnit.KilogramPerMeter, parsed.Unit); - } - - { - Assert.True(LinearDensity.TryParse("1 kg/mm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerMillimeter, KilogramsPerMillimeterTolerance); - Assert.Equal(LinearDensityUnit.KilogramPerMillimeter, parsed.Unit); - } - - { - Assert.True(LinearDensity.TryParse("1 µg/cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerCentimeter, MicrogramsPerCentimeterTolerance); - Assert.Equal(LinearDensityUnit.MicrogramPerCentimeter, parsed.Unit); - } - - { - Assert.True(LinearDensity.TryParse("1 µg/ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerFoot, MicrogramsPerFootTolerance); - Assert.Equal(LinearDensityUnit.MicrogramPerFoot, parsed.Unit); - } - - { - Assert.True(LinearDensity.TryParse("1 µg/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerMeter, MicrogramsPerMeterTolerance); - Assert.Equal(LinearDensityUnit.MicrogramPerMeter, parsed.Unit); - } - - { - Assert.True(LinearDensity.TryParse("1 µg/mm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerMillimeter, MicrogramsPerMillimeterTolerance); - Assert.Equal(LinearDensityUnit.MicrogramPerMillimeter, parsed.Unit); - } - - { - Assert.True(LinearDensity.TryParse("1 mg/cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligramsPerCentimeter, MilligramsPerCentimeterTolerance); - Assert.Equal(LinearDensityUnit.MilligramPerCentimeter, parsed.Unit); - } - - { - Assert.True(LinearDensity.TryParse("1 mg/ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligramsPerFoot, MilligramsPerFootTolerance); - Assert.Equal(LinearDensityUnit.MilligramPerFoot, parsed.Unit); - } - - { - Assert.True(LinearDensity.TryParse("1 mg/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligramsPerMeter, MilligramsPerMeterTolerance); - Assert.Equal(LinearDensityUnit.MilligramPerMeter, parsed.Unit); - } - - { - Assert.True(LinearDensity.TryParse("1 mg/mm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligramsPerMillimeter, MilligramsPerMillimeterTolerance); - Assert.Equal(LinearDensityUnit.MilligramPerMillimeter, parsed.Unit); - } - - { - Assert.True(LinearDensity.TryParse("1 lb/ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerFoot, PoundsPerFootTolerance); - Assert.Equal(LinearDensityUnit.PoundPerFoot, parsed.Unit); - } - - { - Assert.True(LinearDensity.TryParse("1 lb/in", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerInch, PoundsPerInchTolerance); - Assert.Equal(LinearDensityUnit.PoundPerInch, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(LinearDensity.TryParse(quantityString, out LinearDensity parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -891,6 +719,44 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Linear Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", LinearDensityUnit.GramPerCentimeter, "g/cm")] + [InlineData("en-US", LinearDensityUnit.GramPerFoot, "g/ft")] + [InlineData("en-US", LinearDensityUnit.GramPerMeter, "g/m")] + [InlineData("en-US", LinearDensityUnit.GramPerMillimeter, "g/mm")] + [InlineData("en-US", LinearDensityUnit.KilogramPerCentimeter, "kg/cm")] + [InlineData("en-US", LinearDensityUnit.KilogramPerFoot, "kg/ft")] + [InlineData("en-US", LinearDensityUnit.KilogramPerMeter, "kg/m")] + [InlineData("en-US", LinearDensityUnit.KilogramPerMillimeter, "kg/mm")] + [InlineData("en-US", LinearDensityUnit.MicrogramPerCentimeter, "µg/cm")] + [InlineData("en-US", LinearDensityUnit.MicrogramPerFoot, "µg/ft")] + [InlineData("en-US", LinearDensityUnit.MicrogramPerMeter, "µg/m")] + [InlineData("en-US", LinearDensityUnit.MicrogramPerMillimeter, "µg/mm")] + [InlineData("en-US", LinearDensityUnit.MilligramPerCentimeter, "mg/cm")] + [InlineData("en-US", LinearDensityUnit.MilligramPerFoot, "mg/ft")] + [InlineData("en-US", LinearDensityUnit.MilligramPerMeter, "mg/m")] + [InlineData("en-US", LinearDensityUnit.MilligramPerMillimeter, "mg/mm")] + [InlineData("en-US", LinearDensityUnit.PoundPerFoot, "lb/ft")] + [InlineData("en-US", LinearDensityUnit.PoundPerInch, "lb/in")] + public void GetAbbreviationForCulture(string culture, LinearDensityUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = LinearDensity.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(LinearDensity.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = LinearDensity.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(LinearDensityUnit unit) @@ -921,6 +787,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); }); } @@ -944,49 +811,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] @@ -1032,8 +901,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); @@ -1070,23 +937,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = LinearDensity.FromKilogramsPerMeter(1); - Assert.True(v.Equals(LinearDensity.FromKilogramsPerMeter(1), KilogramsPerMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(LinearDensity.Zero, KilogramsPerMeterTolerance, ComparisonType.Relative)); - Assert.True(LinearDensity.FromKilogramsPerMeter(100).Equals(LinearDensity.FromKilogramsPerMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(LinearDensity.FromKilogramsPerMeter(100).Equals(LinearDensity.FromKilogramsPerMeter(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = LinearDensity.FromKilogramsPerMeter(1); - Assert.Throws(() => v.Equals(LinearDensity.FromKilogramsPerMeter(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1101,6 +951,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(kilogrampermeter.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = LinearDensity.FromKilogramsPerMeter(1); + var negativeTolerance = LinearDensity.FromKilogramsPerMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1117,6 +993,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() { @@ -1209,158 +1097,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(LinearDensity))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(LinearDensityUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal(LinearDensity.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal(LinearDensity.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal(new {LinearDensity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 6dad1a592f..130454700b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LinearPowerDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LinearPowerDensityTestsBase.g.cs @@ -192,7 +192,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new LinearPowerDensity(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -205,15 +205,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void LinearPowerDensity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + LinearPowerDensityUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new LinearPowerDensity(1, LinearPowerDensityUnit.WattPerMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(LinearPowerDensity.Zero, quantityInfo.Zero); Assert.Equal("LinearPowerDensity", quantityInfo.Name); + Assert.Equal(LinearPowerDensity.Zero, quantityInfo.Zero); + Assert.Equal(LinearPowerDensity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(LinearPowerDensity.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void LinearPowerDensityInfo_CreateWithCustomUnitInfos() + { + LinearPowerDensityUnit[] expectedUnits = [LinearPowerDensityUnit.WattPerMeter]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -251,103 +269,103 @@ public void WattPerMeterToLinearPowerDensityUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = LinearPowerDensity.From(1, LinearPowerDensityUnit.GigawattPerCentimeter); - AssertEx.EqualTolerance(1, quantity00.GigawattsPerCentimeter, GigawattsPerCentimeterTolerance); + Assert.Equal(1, quantity00.GigawattsPerCentimeter); Assert.Equal(LinearPowerDensityUnit.GigawattPerCentimeter, quantity00.Unit); var quantity01 = LinearPowerDensity.From(1, LinearPowerDensityUnit.GigawattPerFoot); - AssertEx.EqualTolerance(1, quantity01.GigawattsPerFoot, GigawattsPerFootTolerance); + Assert.Equal(1, quantity01.GigawattsPerFoot); Assert.Equal(LinearPowerDensityUnit.GigawattPerFoot, quantity01.Unit); var quantity02 = LinearPowerDensity.From(1, LinearPowerDensityUnit.GigawattPerInch); - AssertEx.EqualTolerance(1, quantity02.GigawattsPerInch, GigawattsPerInchTolerance); + Assert.Equal(1, quantity02.GigawattsPerInch); Assert.Equal(LinearPowerDensityUnit.GigawattPerInch, quantity02.Unit); var quantity03 = LinearPowerDensity.From(1, LinearPowerDensityUnit.GigawattPerMeter); - AssertEx.EqualTolerance(1, quantity03.GigawattsPerMeter, GigawattsPerMeterTolerance); + Assert.Equal(1, quantity03.GigawattsPerMeter); Assert.Equal(LinearPowerDensityUnit.GigawattPerMeter, quantity03.Unit); var quantity04 = LinearPowerDensity.From(1, LinearPowerDensityUnit.GigawattPerMillimeter); - AssertEx.EqualTolerance(1, quantity04.GigawattsPerMillimeter, GigawattsPerMillimeterTolerance); + Assert.Equal(1, quantity04.GigawattsPerMillimeter); Assert.Equal(LinearPowerDensityUnit.GigawattPerMillimeter, quantity04.Unit); var quantity05 = LinearPowerDensity.From(1, LinearPowerDensityUnit.KilowattPerCentimeter); - AssertEx.EqualTolerance(1, quantity05.KilowattsPerCentimeter, KilowattsPerCentimeterTolerance); + Assert.Equal(1, quantity05.KilowattsPerCentimeter); Assert.Equal(LinearPowerDensityUnit.KilowattPerCentimeter, quantity05.Unit); var quantity06 = LinearPowerDensity.From(1, LinearPowerDensityUnit.KilowattPerFoot); - AssertEx.EqualTolerance(1, quantity06.KilowattsPerFoot, KilowattsPerFootTolerance); + Assert.Equal(1, quantity06.KilowattsPerFoot); Assert.Equal(LinearPowerDensityUnit.KilowattPerFoot, quantity06.Unit); var quantity07 = LinearPowerDensity.From(1, LinearPowerDensityUnit.KilowattPerInch); - AssertEx.EqualTolerance(1, quantity07.KilowattsPerInch, KilowattsPerInchTolerance); + Assert.Equal(1, quantity07.KilowattsPerInch); Assert.Equal(LinearPowerDensityUnit.KilowattPerInch, quantity07.Unit); var quantity08 = LinearPowerDensity.From(1, LinearPowerDensityUnit.KilowattPerMeter); - AssertEx.EqualTolerance(1, quantity08.KilowattsPerMeter, KilowattsPerMeterTolerance); + Assert.Equal(1, quantity08.KilowattsPerMeter); Assert.Equal(LinearPowerDensityUnit.KilowattPerMeter, quantity08.Unit); var quantity09 = LinearPowerDensity.From(1, LinearPowerDensityUnit.KilowattPerMillimeter); - AssertEx.EqualTolerance(1, quantity09.KilowattsPerMillimeter, KilowattsPerMillimeterTolerance); + Assert.Equal(1, quantity09.KilowattsPerMillimeter); Assert.Equal(LinearPowerDensityUnit.KilowattPerMillimeter, quantity09.Unit); var quantity10 = LinearPowerDensity.From(1, LinearPowerDensityUnit.MegawattPerCentimeter); - AssertEx.EqualTolerance(1, quantity10.MegawattsPerCentimeter, MegawattsPerCentimeterTolerance); + Assert.Equal(1, quantity10.MegawattsPerCentimeter); Assert.Equal(LinearPowerDensityUnit.MegawattPerCentimeter, quantity10.Unit); var quantity11 = LinearPowerDensity.From(1, LinearPowerDensityUnit.MegawattPerFoot); - AssertEx.EqualTolerance(1, quantity11.MegawattsPerFoot, MegawattsPerFootTolerance); + Assert.Equal(1, quantity11.MegawattsPerFoot); Assert.Equal(LinearPowerDensityUnit.MegawattPerFoot, quantity11.Unit); var quantity12 = LinearPowerDensity.From(1, LinearPowerDensityUnit.MegawattPerInch); - AssertEx.EqualTolerance(1, quantity12.MegawattsPerInch, MegawattsPerInchTolerance); + Assert.Equal(1, quantity12.MegawattsPerInch); Assert.Equal(LinearPowerDensityUnit.MegawattPerInch, quantity12.Unit); var quantity13 = LinearPowerDensity.From(1, LinearPowerDensityUnit.MegawattPerMeter); - AssertEx.EqualTolerance(1, quantity13.MegawattsPerMeter, MegawattsPerMeterTolerance); + Assert.Equal(1, quantity13.MegawattsPerMeter); Assert.Equal(LinearPowerDensityUnit.MegawattPerMeter, quantity13.Unit); var quantity14 = LinearPowerDensity.From(1, LinearPowerDensityUnit.MegawattPerMillimeter); - AssertEx.EqualTolerance(1, quantity14.MegawattsPerMillimeter, MegawattsPerMillimeterTolerance); + Assert.Equal(1, quantity14.MegawattsPerMillimeter); Assert.Equal(LinearPowerDensityUnit.MegawattPerMillimeter, quantity14.Unit); var quantity15 = LinearPowerDensity.From(1, LinearPowerDensityUnit.MilliwattPerCentimeter); - AssertEx.EqualTolerance(1, quantity15.MilliwattsPerCentimeter, MilliwattsPerCentimeterTolerance); + Assert.Equal(1, quantity15.MilliwattsPerCentimeter); Assert.Equal(LinearPowerDensityUnit.MilliwattPerCentimeter, quantity15.Unit); var quantity16 = LinearPowerDensity.From(1, LinearPowerDensityUnit.MilliwattPerFoot); - AssertEx.EqualTolerance(1, quantity16.MilliwattsPerFoot, MilliwattsPerFootTolerance); + Assert.Equal(1, quantity16.MilliwattsPerFoot); Assert.Equal(LinearPowerDensityUnit.MilliwattPerFoot, quantity16.Unit); var quantity17 = LinearPowerDensity.From(1, LinearPowerDensityUnit.MilliwattPerInch); - AssertEx.EqualTolerance(1, quantity17.MilliwattsPerInch, MilliwattsPerInchTolerance); + Assert.Equal(1, quantity17.MilliwattsPerInch); Assert.Equal(LinearPowerDensityUnit.MilliwattPerInch, quantity17.Unit); var quantity18 = LinearPowerDensity.From(1, LinearPowerDensityUnit.MilliwattPerMeter); - AssertEx.EqualTolerance(1, quantity18.MilliwattsPerMeter, MilliwattsPerMeterTolerance); + Assert.Equal(1, quantity18.MilliwattsPerMeter); Assert.Equal(LinearPowerDensityUnit.MilliwattPerMeter, quantity18.Unit); var quantity19 = LinearPowerDensity.From(1, LinearPowerDensityUnit.MilliwattPerMillimeter); - AssertEx.EqualTolerance(1, quantity19.MilliwattsPerMillimeter, MilliwattsPerMillimeterTolerance); + Assert.Equal(1, quantity19.MilliwattsPerMillimeter); Assert.Equal(LinearPowerDensityUnit.MilliwattPerMillimeter, quantity19.Unit); var quantity20 = LinearPowerDensity.From(1, LinearPowerDensityUnit.WattPerCentimeter); - AssertEx.EqualTolerance(1, quantity20.WattsPerCentimeter, WattsPerCentimeterTolerance); + Assert.Equal(1, quantity20.WattsPerCentimeter); Assert.Equal(LinearPowerDensityUnit.WattPerCentimeter, quantity20.Unit); var quantity21 = LinearPowerDensity.From(1, LinearPowerDensityUnit.WattPerFoot); - AssertEx.EqualTolerance(1, quantity21.WattsPerFoot, WattsPerFootTolerance); + Assert.Equal(1, quantity21.WattsPerFoot); Assert.Equal(LinearPowerDensityUnit.WattPerFoot, quantity21.Unit); var quantity22 = LinearPowerDensity.From(1, LinearPowerDensityUnit.WattPerInch); - AssertEx.EqualTolerance(1, quantity22.WattsPerInch, WattsPerInchTolerance); + Assert.Equal(1, quantity22.WattsPerInch); Assert.Equal(LinearPowerDensityUnit.WattPerInch, quantity22.Unit); var quantity23 = LinearPowerDensity.From(1, LinearPowerDensityUnit.WattPerMeter); - AssertEx.EqualTolerance(1, quantity23.WattsPerMeter, WattsPerMeterTolerance); + Assert.Equal(1, quantity23.WattsPerMeter); Assert.Equal(LinearPowerDensityUnit.WattPerMeter, quantity23.Unit); var quantity24 = LinearPowerDensity.From(1, LinearPowerDensityUnit.WattPerMillimeter); - AssertEx.EqualTolerance(1, quantity24.WattsPerMillimeter, WattsPerMillimeterTolerance); + Assert.Equal(1, quantity24.WattsPerMillimeter); Assert.Equal(LinearPowerDensityUnit.WattPerMillimeter, quantity24.Unit); } @@ -507,279 +525,72 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 GW/cm", LinearPowerDensityUnit.GigawattPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 GW/ft", LinearPowerDensityUnit.GigawattPerFoot, 4.2)] + [InlineData("en-US", "4.2 GW/in", LinearPowerDensityUnit.GigawattPerInch, 4.2)] + [InlineData("en-US", "4.2 GW/m", LinearPowerDensityUnit.GigawattPerMeter, 4.2)] + [InlineData("en-US", "4.2 GW/mm", LinearPowerDensityUnit.GigawattPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 kW/cm", LinearPowerDensityUnit.KilowattPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 kW/ft", LinearPowerDensityUnit.KilowattPerFoot, 4.2)] + [InlineData("en-US", "4.2 kW/in", LinearPowerDensityUnit.KilowattPerInch, 4.2)] + [InlineData("en-US", "4.2 kW/m", LinearPowerDensityUnit.KilowattPerMeter, 4.2)] + [InlineData("en-US", "4.2 kW/mm", LinearPowerDensityUnit.KilowattPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 MW/cm", LinearPowerDensityUnit.MegawattPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 MW/ft", LinearPowerDensityUnit.MegawattPerFoot, 4.2)] + [InlineData("en-US", "4.2 MW/in", LinearPowerDensityUnit.MegawattPerInch, 4.2)] + [InlineData("en-US", "4.2 MW/m", LinearPowerDensityUnit.MegawattPerMeter, 4.2)] + [InlineData("en-US", "4.2 MW/mm", LinearPowerDensityUnit.MegawattPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 mW/cm", LinearPowerDensityUnit.MilliwattPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 mW/ft", LinearPowerDensityUnit.MilliwattPerFoot, 4.2)] + [InlineData("en-US", "4.2 mW/in", LinearPowerDensityUnit.MilliwattPerInch, 4.2)] + [InlineData("en-US", "4.2 mW/m", LinearPowerDensityUnit.MilliwattPerMeter, 4.2)] + [InlineData("en-US", "4.2 mW/mm", LinearPowerDensityUnit.MilliwattPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 W/cm", LinearPowerDensityUnit.WattPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 W/ft", LinearPowerDensityUnit.WattPerFoot, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = LinearPowerDensity.Parse("1 GW/cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GigawattsPerCentimeter, GigawattsPerCentimeterTolerance); - Assert.Equal(LinearPowerDensityUnit.GigawattPerCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearPowerDensity.Parse("1 GW/ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GigawattsPerFoot, GigawattsPerFootTolerance); - Assert.Equal(LinearPowerDensityUnit.GigawattPerFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearPowerDensity.Parse("1 GW/in", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GigawattsPerInch, GigawattsPerInchTolerance); - Assert.Equal(LinearPowerDensityUnit.GigawattPerInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearPowerDensity.Parse("1 GW/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GigawattsPerMeter, GigawattsPerMeterTolerance); - Assert.Equal(LinearPowerDensityUnit.GigawattPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearPowerDensity.Parse("1 GW/mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GigawattsPerMillimeter, GigawattsPerMillimeterTolerance); - Assert.Equal(LinearPowerDensityUnit.GigawattPerMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearPowerDensity.Parse("1 kW/cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilowattsPerCentimeter, KilowattsPerCentimeterTolerance); - Assert.Equal(LinearPowerDensityUnit.KilowattPerCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearPowerDensity.Parse("1 kW/ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilowattsPerFoot, KilowattsPerFootTolerance); - Assert.Equal(LinearPowerDensityUnit.KilowattPerFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearPowerDensity.Parse("1 kW/in", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilowattsPerInch, KilowattsPerInchTolerance); - Assert.Equal(LinearPowerDensityUnit.KilowattPerInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearPowerDensity.Parse("1 kW/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilowattsPerMeter, KilowattsPerMeterTolerance); - Assert.Equal(LinearPowerDensityUnit.KilowattPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearPowerDensity.Parse("1 kW/mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilowattsPerMillimeter, KilowattsPerMillimeterTolerance); - Assert.Equal(LinearPowerDensityUnit.KilowattPerMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearPowerDensity.Parse("1 MW/cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegawattsPerCentimeter, MegawattsPerCentimeterTolerance); - Assert.Equal(LinearPowerDensityUnit.MegawattPerCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearPowerDensity.Parse("1 MW/ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegawattsPerFoot, MegawattsPerFootTolerance); - Assert.Equal(LinearPowerDensityUnit.MegawattPerFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearPowerDensity.Parse("1 MW/in", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegawattsPerInch, MegawattsPerInchTolerance); - Assert.Equal(LinearPowerDensityUnit.MegawattPerInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearPowerDensity.Parse("1 MW/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegawattsPerMeter, MegawattsPerMeterTolerance); - Assert.Equal(LinearPowerDensityUnit.MegawattPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearPowerDensity.Parse("1 MW/mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegawattsPerMillimeter, MegawattsPerMillimeterTolerance); - Assert.Equal(LinearPowerDensityUnit.MegawattPerMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearPowerDensity.Parse("1 mW/cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilliwattsPerCentimeter, MilliwattsPerCentimeterTolerance); - Assert.Equal(LinearPowerDensityUnit.MilliwattPerCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearPowerDensity.Parse("1 mW/ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilliwattsPerFoot, MilliwattsPerFootTolerance); - Assert.Equal(LinearPowerDensityUnit.MilliwattPerFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearPowerDensity.Parse("1 mW/in", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilliwattsPerInch, MilliwattsPerInchTolerance); - Assert.Equal(LinearPowerDensityUnit.MilliwattPerInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearPowerDensity.Parse("1 mW/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilliwattsPerMeter, MilliwattsPerMeterTolerance); - Assert.Equal(LinearPowerDensityUnit.MilliwattPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearPowerDensity.Parse("1 mW/mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilliwattsPerMillimeter, MilliwattsPerMillimeterTolerance); - Assert.Equal(LinearPowerDensityUnit.MilliwattPerMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearPowerDensity.Parse("1 W/cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WattsPerCentimeter, WattsPerCentimeterTolerance); - Assert.Equal(LinearPowerDensityUnit.WattPerCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearPowerDensity.Parse("1 W/ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WattsPerFoot, WattsPerFootTolerance); - Assert.Equal(LinearPowerDensityUnit.WattPerFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearPowerDensity.Parse("1 W/in", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WattsPerInch, WattsPerInchTolerance); - Assert.Equal(LinearPowerDensityUnit.WattPerInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearPowerDensity.Parse("1 W/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WattsPerMeter, WattsPerMeterTolerance); - Assert.Equal(LinearPowerDensityUnit.WattPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = LinearPowerDensity.Parse("1 W/mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WattsPerMillimeter, WattsPerMillimeterTolerance); - Assert.Equal(LinearPowerDensityUnit.WattPerMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = LinearPowerDensity.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 GW/cm", LinearPowerDensityUnit.GigawattPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 GW/ft", LinearPowerDensityUnit.GigawattPerFoot, 4.2)] + [InlineData("en-US", "4.2 GW/in", LinearPowerDensityUnit.GigawattPerInch, 4.2)] + [InlineData("en-US", "4.2 GW/m", LinearPowerDensityUnit.GigawattPerMeter, 4.2)] + [InlineData("en-US", "4.2 GW/mm", LinearPowerDensityUnit.GigawattPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 kW/cm", LinearPowerDensityUnit.KilowattPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 kW/ft", LinearPowerDensityUnit.KilowattPerFoot, 4.2)] + [InlineData("en-US", "4.2 kW/in", LinearPowerDensityUnit.KilowattPerInch, 4.2)] + [InlineData("en-US", "4.2 kW/m", LinearPowerDensityUnit.KilowattPerMeter, 4.2)] + [InlineData("en-US", "4.2 kW/mm", LinearPowerDensityUnit.KilowattPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 MW/cm", LinearPowerDensityUnit.MegawattPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 MW/ft", LinearPowerDensityUnit.MegawattPerFoot, 4.2)] + [InlineData("en-US", "4.2 MW/in", LinearPowerDensityUnit.MegawattPerInch, 4.2)] + [InlineData("en-US", "4.2 MW/m", LinearPowerDensityUnit.MegawattPerMeter, 4.2)] + [InlineData("en-US", "4.2 MW/mm", LinearPowerDensityUnit.MegawattPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 mW/cm", LinearPowerDensityUnit.MilliwattPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 mW/ft", LinearPowerDensityUnit.MilliwattPerFoot, 4.2)] + [InlineData("en-US", "4.2 mW/in", LinearPowerDensityUnit.MilliwattPerInch, 4.2)] + [InlineData("en-US", "4.2 mW/m", LinearPowerDensityUnit.MilliwattPerMeter, 4.2)] + [InlineData("en-US", "4.2 mW/mm", LinearPowerDensityUnit.MilliwattPerMillimeter, 4.2)] + [InlineData("en-US", "4.2 W/cm", LinearPowerDensityUnit.WattPerCentimeter, 4.2)] + [InlineData("en-US", "4.2 W/ft", LinearPowerDensityUnit.WattPerFoot, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(LinearPowerDensity.TryParse("1 GW/cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigawattsPerCentimeter, GigawattsPerCentimeterTolerance); - Assert.Equal(LinearPowerDensityUnit.GigawattPerCentimeter, parsed.Unit); - } - - { - Assert.True(LinearPowerDensity.TryParse("1 GW/ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigawattsPerFoot, GigawattsPerFootTolerance); - Assert.Equal(LinearPowerDensityUnit.GigawattPerFoot, parsed.Unit); - } - - { - Assert.True(LinearPowerDensity.TryParse("1 GW/in", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigawattsPerInch, GigawattsPerInchTolerance); - Assert.Equal(LinearPowerDensityUnit.GigawattPerInch, parsed.Unit); - } - - { - Assert.True(LinearPowerDensity.TryParse("1 GW/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigawattsPerMeter, GigawattsPerMeterTolerance); - Assert.Equal(LinearPowerDensityUnit.GigawattPerMeter, parsed.Unit); - } - - { - Assert.True(LinearPowerDensity.TryParse("1 GW/mm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigawattsPerMillimeter, GigawattsPerMillimeterTolerance); - Assert.Equal(LinearPowerDensityUnit.GigawattPerMillimeter, parsed.Unit); - } - - { - Assert.True(LinearPowerDensity.TryParse("1 kW/cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilowattsPerCentimeter, KilowattsPerCentimeterTolerance); - Assert.Equal(LinearPowerDensityUnit.KilowattPerCentimeter, parsed.Unit); - } - - { - Assert.True(LinearPowerDensity.TryParse("1 kW/ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilowattsPerFoot, KilowattsPerFootTolerance); - Assert.Equal(LinearPowerDensityUnit.KilowattPerFoot, parsed.Unit); - } - - { - Assert.True(LinearPowerDensity.TryParse("1 kW/in", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilowattsPerInch, KilowattsPerInchTolerance); - Assert.Equal(LinearPowerDensityUnit.KilowattPerInch, parsed.Unit); - } - - { - Assert.True(LinearPowerDensity.TryParse("1 kW/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilowattsPerMeter, KilowattsPerMeterTolerance); - Assert.Equal(LinearPowerDensityUnit.KilowattPerMeter, parsed.Unit); - } - - { - Assert.True(LinearPowerDensity.TryParse("1 kW/mm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilowattsPerMillimeter, KilowattsPerMillimeterTolerance); - Assert.Equal(LinearPowerDensityUnit.KilowattPerMillimeter, parsed.Unit); - } - - { - Assert.True(LinearPowerDensity.TryParse("1 W/cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattsPerCentimeter, WattsPerCentimeterTolerance); - Assert.Equal(LinearPowerDensityUnit.WattPerCentimeter, parsed.Unit); - } - - { - Assert.True(LinearPowerDensity.TryParse("1 W/ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattsPerFoot, WattsPerFootTolerance); - Assert.Equal(LinearPowerDensityUnit.WattPerFoot, parsed.Unit); - } - - { - Assert.True(LinearPowerDensity.TryParse("1 W/in", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattsPerInch, WattsPerInchTolerance); - Assert.Equal(LinearPowerDensityUnit.WattPerInch, parsed.Unit); - } - - { - Assert.True(LinearPowerDensity.TryParse("1 W/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattsPerMeter, WattsPerMeterTolerance); - Assert.Equal(LinearPowerDensityUnit.WattPerMeter, parsed.Unit); - } - - { - Assert.True(LinearPowerDensity.TryParse("1 W/mm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattsPerMillimeter, WattsPerMillimeterTolerance); - Assert.Equal(LinearPowerDensityUnit.WattPerMillimeter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(LinearPowerDensity.TryParse(quantityString, out LinearPowerDensity parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -1048,6 +859,51 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Linear Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", LinearPowerDensityUnit.GigawattPerCentimeter, "GW/cm")] + [InlineData("en-US", LinearPowerDensityUnit.GigawattPerFoot, "GW/ft")] + [InlineData("en-US", LinearPowerDensityUnit.GigawattPerInch, "GW/in")] + [InlineData("en-US", LinearPowerDensityUnit.GigawattPerMeter, "GW/m")] + [InlineData("en-US", LinearPowerDensityUnit.GigawattPerMillimeter, "GW/mm")] + [InlineData("en-US", LinearPowerDensityUnit.KilowattPerCentimeter, "kW/cm")] + [InlineData("en-US", LinearPowerDensityUnit.KilowattPerFoot, "kW/ft")] + [InlineData("en-US", LinearPowerDensityUnit.KilowattPerInch, "kW/in")] + [InlineData("en-US", LinearPowerDensityUnit.KilowattPerMeter, "kW/m")] + [InlineData("en-US", LinearPowerDensityUnit.KilowattPerMillimeter, "kW/mm")] + [InlineData("en-US", LinearPowerDensityUnit.MegawattPerCentimeter, "MW/cm")] + [InlineData("en-US", LinearPowerDensityUnit.MegawattPerFoot, "MW/ft")] + [InlineData("en-US", LinearPowerDensityUnit.MegawattPerInch, "MW/in")] + [InlineData("en-US", LinearPowerDensityUnit.MegawattPerMeter, "MW/m")] + [InlineData("en-US", LinearPowerDensityUnit.MegawattPerMillimeter, "MW/mm")] + [InlineData("en-US", LinearPowerDensityUnit.MilliwattPerCentimeter, "mW/cm")] + [InlineData("en-US", LinearPowerDensityUnit.MilliwattPerFoot, "mW/ft")] + [InlineData("en-US", LinearPowerDensityUnit.MilliwattPerInch, "mW/in")] + [InlineData("en-US", LinearPowerDensityUnit.MilliwattPerMeter, "mW/m")] + [InlineData("en-US", LinearPowerDensityUnit.MilliwattPerMillimeter, "mW/mm")] + [InlineData("en-US", LinearPowerDensityUnit.WattPerCentimeter, "W/cm")] + [InlineData("en-US", LinearPowerDensityUnit.WattPerFoot, "W/ft")] + [InlineData("en-US", LinearPowerDensityUnit.WattPerInch, "W/in")] + [InlineData("en-US", LinearPowerDensityUnit.WattPerMeter, "W/m")] + [InlineData("en-US", LinearPowerDensityUnit.WattPerMillimeter, "W/mm")] + public void GetAbbreviationForCulture(string culture, LinearPowerDensityUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = LinearPowerDensity.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(LinearPowerDensity.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = LinearPowerDensity.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(LinearPowerDensityUnit unit) @@ -1078,6 +934,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); }); } @@ -1101,56 +958,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] @@ -1196,8 +1055,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); @@ -1234,23 +1091,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = LinearPowerDensity.FromWattsPerMeter(1); - Assert.True(v.Equals(LinearPowerDensity.FromWattsPerMeter(1), WattsPerMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(LinearPowerDensity.Zero, WattsPerMeterTolerance, ComparisonType.Relative)); - Assert.True(LinearPowerDensity.FromWattsPerMeter(100).Equals(LinearPowerDensity.FromWattsPerMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(LinearPowerDensity.FromWattsPerMeter(100).Equals(LinearPowerDensity.FromWattsPerMeter(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = LinearPowerDensity.FromWattsPerMeter(1); - Assert.Throws(() => v.Equals(LinearPowerDensity.FromWattsPerMeter(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1265,6 +1105,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(wattpermeter.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = LinearPowerDensity.FromWattsPerMeter(1); + var negativeTolerance = LinearPowerDensity.FromWattsPerMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1281,6 +1147,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() { @@ -1387,158 +1265,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(LinearPowerDensity))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(LinearPowerDensityUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal(LinearPowerDensity.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal(LinearPowerDensity.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal(new {LinearPowerDensity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 8fd16a933f..858f205e1a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminanceTestsBase.g.cs @@ -132,7 +132,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Luminance(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -145,15 +145,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Luminance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + LuminanceUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Luminance(1, LuminanceUnit.CandelaPerSquareMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Luminance.Zero, quantityInfo.Zero); Assert.Equal("Luminance", quantityInfo.Name); + Assert.Equal(Luminance.Zero, quantityInfo.Zero); + Assert.Equal(Luminance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Luminance.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -176,43 +194,43 @@ public void CandelaPerSquareMeterToLuminanceUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Luminance.From(1, LuminanceUnit.CandelaPerSquareFoot); - AssertEx.EqualTolerance(1, quantity00.CandelasPerSquareFoot, CandelasPerSquareFootTolerance); + Assert.Equal(1, quantity00.CandelasPerSquareFoot); Assert.Equal(LuminanceUnit.CandelaPerSquareFoot, quantity00.Unit); var quantity01 = Luminance.From(1, LuminanceUnit.CandelaPerSquareInch); - AssertEx.EqualTolerance(1, quantity01.CandelasPerSquareInch, CandelasPerSquareInchTolerance); + Assert.Equal(1, quantity01.CandelasPerSquareInch); Assert.Equal(LuminanceUnit.CandelaPerSquareInch, quantity01.Unit); var quantity02 = Luminance.From(1, LuminanceUnit.CandelaPerSquareMeter); - AssertEx.EqualTolerance(1, quantity02.CandelasPerSquareMeter, CandelasPerSquareMeterTolerance); + Assert.Equal(1, quantity02.CandelasPerSquareMeter); Assert.Equal(LuminanceUnit.CandelaPerSquareMeter, quantity02.Unit); var quantity03 = Luminance.From(1, LuminanceUnit.CenticandelaPerSquareMeter); - AssertEx.EqualTolerance(1, quantity03.CenticandelasPerSquareMeter, CenticandelasPerSquareMeterTolerance); + Assert.Equal(1, quantity03.CenticandelasPerSquareMeter); Assert.Equal(LuminanceUnit.CenticandelaPerSquareMeter, quantity03.Unit); var quantity04 = Luminance.From(1, LuminanceUnit.DecicandelaPerSquareMeter); - AssertEx.EqualTolerance(1, quantity04.DecicandelasPerSquareMeter, DecicandelasPerSquareMeterTolerance); + Assert.Equal(1, quantity04.DecicandelasPerSquareMeter); Assert.Equal(LuminanceUnit.DecicandelaPerSquareMeter, quantity04.Unit); var quantity05 = Luminance.From(1, LuminanceUnit.KilocandelaPerSquareMeter); - AssertEx.EqualTolerance(1, quantity05.KilocandelasPerSquareMeter, KilocandelasPerSquareMeterTolerance); + Assert.Equal(1, quantity05.KilocandelasPerSquareMeter); Assert.Equal(LuminanceUnit.KilocandelaPerSquareMeter, quantity05.Unit); var quantity06 = Luminance.From(1, LuminanceUnit.MicrocandelaPerSquareMeter); - AssertEx.EqualTolerance(1, quantity06.MicrocandelasPerSquareMeter, MicrocandelasPerSquareMeterTolerance); + Assert.Equal(1, quantity06.MicrocandelasPerSquareMeter); Assert.Equal(LuminanceUnit.MicrocandelaPerSquareMeter, quantity06.Unit); var quantity07 = Luminance.From(1, LuminanceUnit.MillicandelaPerSquareMeter); - AssertEx.EqualTolerance(1, quantity07.MillicandelasPerSquareMeter, MillicandelasPerSquareMeterTolerance); + Assert.Equal(1, quantity07.MillicandelasPerSquareMeter); Assert.Equal(LuminanceUnit.MillicandelaPerSquareMeter, quantity07.Unit); var quantity08 = Luminance.From(1, LuminanceUnit.NanocandelaPerSquareMeter); - AssertEx.EqualTolerance(1, quantity08.NanocandelasPerSquareMeter, NanocandelasPerSquareMeterTolerance); + Assert.Equal(1, quantity08.NanocandelasPerSquareMeter); Assert.Equal(LuminanceUnit.NanocandelaPerSquareMeter, quantity08.Unit); var quantity09 = Luminance.From(1, LuminanceUnit.Nit); - AssertEx.EqualTolerance(1, quantity09.Nits, NitsTolerance); + Assert.Equal(1, quantity09.Nits); Assert.Equal(LuminanceUnit.Nit, quantity09.Unit); } @@ -357,144 +375,42 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 Cd/ft²", LuminanceUnit.CandelaPerSquareFoot, 4.2)] + [InlineData("en-US", "4.2 Cd/in²", LuminanceUnit.CandelaPerSquareInch, 4.2)] + [InlineData("en-US", "4.2 Cd/m²", LuminanceUnit.CandelaPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 cCd/m²", LuminanceUnit.CenticandelaPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 dCd/m²", LuminanceUnit.DecicandelaPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 kCd/m²", LuminanceUnit.KilocandelaPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 µCd/m²", LuminanceUnit.MicrocandelaPerSquareMeter, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = Luminance.Parse("1 Cd/ft²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CandelasPerSquareFoot, CandelasPerSquareFootTolerance); - Assert.Equal(LuminanceUnit.CandelaPerSquareFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Luminance.Parse("1 Cd/in²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CandelasPerSquareInch, CandelasPerSquareInchTolerance); - Assert.Equal(LuminanceUnit.CandelaPerSquareInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Luminance.Parse("1 Cd/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CandelasPerSquareMeter, CandelasPerSquareMeterTolerance); - Assert.Equal(LuminanceUnit.CandelaPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Luminance.Parse("1 cCd/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CenticandelasPerSquareMeter, CenticandelasPerSquareMeterTolerance); - Assert.Equal(LuminanceUnit.CenticandelaPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Luminance.Parse("1 dCd/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecicandelasPerSquareMeter, DecicandelasPerSquareMeterTolerance); - Assert.Equal(LuminanceUnit.DecicandelaPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Luminance.Parse("1 kCd/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilocandelasPerSquareMeter, KilocandelasPerSquareMeterTolerance); - Assert.Equal(LuminanceUnit.KilocandelaPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Luminance.Parse("1 µCd/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrocandelasPerSquareMeter, MicrocandelasPerSquareMeterTolerance); - Assert.Equal(LuminanceUnit.MicrocandelaPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Luminance.Parse("1 mCd/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillicandelasPerSquareMeter, MillicandelasPerSquareMeterTolerance); - Assert.Equal(LuminanceUnit.MillicandelaPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Luminance.Parse("1 nCd/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanocandelasPerSquareMeter, NanocandelasPerSquareMeterTolerance); - Assert.Equal(LuminanceUnit.NanocandelaPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Luminance.Parse("1 nt", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nits, NitsTolerance); - Assert.Equal(LuminanceUnit.Nit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Luminance.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 Cd/ft²", LuminanceUnit.CandelaPerSquareFoot, 4.2)] + [InlineData("en-US", "4.2 Cd/in²", LuminanceUnit.CandelaPerSquareInch, 4.2)] + [InlineData("en-US", "4.2 Cd/m²", LuminanceUnit.CandelaPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 cCd/m²", LuminanceUnit.CenticandelaPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 dCd/m²", LuminanceUnit.DecicandelaPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 kCd/m²", LuminanceUnit.KilocandelaPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 µCd/m²", LuminanceUnit.MicrocandelaPerSquareMeter, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(Luminance.TryParse("1 Cd/ft²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CandelasPerSquareFoot, CandelasPerSquareFootTolerance); - Assert.Equal(LuminanceUnit.CandelaPerSquareFoot, parsed.Unit); - } - - { - Assert.True(Luminance.TryParse("1 Cd/in²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CandelasPerSquareInch, CandelasPerSquareInchTolerance); - Assert.Equal(LuminanceUnit.CandelaPerSquareInch, parsed.Unit); - } - - { - Assert.True(Luminance.TryParse("1 Cd/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CandelasPerSquareMeter, CandelasPerSquareMeterTolerance); - Assert.Equal(LuminanceUnit.CandelaPerSquareMeter, parsed.Unit); - } - - { - Assert.True(Luminance.TryParse("1 cCd/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CenticandelasPerSquareMeter, CenticandelasPerSquareMeterTolerance); - Assert.Equal(LuminanceUnit.CenticandelaPerSquareMeter, parsed.Unit); - } - - { - Assert.True(Luminance.TryParse("1 dCd/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecicandelasPerSquareMeter, DecicandelasPerSquareMeterTolerance); - Assert.Equal(LuminanceUnit.DecicandelaPerSquareMeter, parsed.Unit); - } - - { - Assert.True(Luminance.TryParse("1 kCd/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilocandelasPerSquareMeter, KilocandelasPerSquareMeterTolerance); - Assert.Equal(LuminanceUnit.KilocandelaPerSquareMeter, parsed.Unit); - } - - { - Assert.True(Luminance.TryParse("1 µCd/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrocandelasPerSquareMeter, MicrocandelasPerSquareMeterTolerance); - Assert.Equal(LuminanceUnit.MicrocandelaPerSquareMeter, parsed.Unit); - } - - { - Assert.True(Luminance.TryParse("1 mCd/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillicandelasPerSquareMeter, MillicandelasPerSquareMeterTolerance); - Assert.Equal(LuminanceUnit.MillicandelaPerSquareMeter, parsed.Unit); - } - - { - Assert.True(Luminance.TryParse("1 nCd/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanocandelasPerSquareMeter, NanocandelasPerSquareMeterTolerance); - Assert.Equal(LuminanceUnit.NanocandelaPerSquareMeter, parsed.Unit); - } - - { - Assert.True(Luminance.TryParse("1 nt", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nits, NitsTolerance); - Assert.Equal(LuminanceUnit.Nit, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Luminance.TryParse(quantityString, out Luminance parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -643,6 +559,36 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Lumina Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", LuminanceUnit.CandelaPerSquareFoot, "Cd/ft²")] + [InlineData("en-US", LuminanceUnit.CandelaPerSquareInch, "Cd/in²")] + [InlineData("en-US", LuminanceUnit.CandelaPerSquareMeter, "Cd/m²")] + [InlineData("en-US", LuminanceUnit.CenticandelaPerSquareMeter, "cCd/m²")] + [InlineData("en-US", LuminanceUnit.DecicandelaPerSquareMeter, "dCd/m²")] + [InlineData("en-US", LuminanceUnit.KilocandelaPerSquareMeter, "kCd/m²")] + [InlineData("en-US", LuminanceUnit.MicrocandelaPerSquareMeter, "µCd/m²")] + [InlineData("en-US", LuminanceUnit.MillicandelaPerSquareMeter, "mCd/m²")] + [InlineData("en-US", LuminanceUnit.NanocandelaPerSquareMeter, "nCd/m²")] + [InlineData("en-US", LuminanceUnit.Nit, "nt")] + public void GetAbbreviationForCulture(string culture, LuminanceUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Luminance.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Luminance.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Luminance.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(LuminanceUnit unit) @@ -673,6 +619,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); }); } @@ -696,41 +643,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] @@ -776,8 +725,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); @@ -815,34 +762,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = Luminance.FromCandelasPerSquareMeter(1); - Assert.True(v.Equals(Luminance.FromCandelasPerSquareMeter(1), CandelasPerSquareMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Luminance.Zero, CandelasPerSquareMeterTolerance, ComparisonType.Relative)); - Assert.True(Luminance.FromCandelasPerSquareMeter(100).Equals(Luminance.FromCandelasPerSquareMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(Luminance.FromCandelasPerSquareMeter(100).Equals(Luminance.FromCandelasPerSquareMeter(120), 0.1, ComparisonType.Relative)); + Luminance candelapersquaremeter = Luminance.FromCandelasPerSquareMeter(1); + Assert.False(candelapersquaremeter.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = Luminance.FromCandelasPerSquareMeter(1); - Assert.Throws(() => v.Equals(Luminance.FromCandelasPerSquareMeter(1), -1, ComparisonType.Relative)); + Luminance candelapersquaremeter = Luminance.FromCandelasPerSquareMeter(1); + Assert.False(candelapersquaremeter.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - Luminance candelapersquaremeter = Luminance.FromCandelasPerSquareMeter(1); - Assert.False(candelapersquaremeter.Equals(new object())); + var quantity = Luminance.FromCandelasPerSquareMeter(firstValue); + var otherQuantity = Luminance.FromCandelasPerSquareMeter(secondValue); + Luminance maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - Luminance candelapersquaremeter = Luminance.FromCandelasPerSquareMeter(1); - Assert.False(candelapersquaremeter.Equals(null)); + var quantity = Luminance.FromCandelasPerSquareMeter(1); + var negativeTolerance = Luminance.FromCandelasPerSquareMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -861,6 +817,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() { @@ -937,158 +905,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Luminance.FromCandelasPerSquareMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Luminance.FromCandelasPerSquareMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Luminance.FromCandelasPerSquareMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Luminance.FromCandelasPerSquareMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Luminance.FromCandelasPerSquareMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Luminance.FromCandelasPerSquareMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Luminance.FromCandelasPerSquareMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Luminance.FromCandelasPerSquareMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Luminance.FromCandelasPerSquareMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Luminance.FromCandelasPerSquareMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Luminance.FromCandelasPerSquareMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Luminance.FromCandelasPerSquareMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Luminance.FromCandelasPerSquareMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Luminance.FromCandelasPerSquareMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Luminance.FromCandelasPerSquareMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Luminance.FromCandelasPerSquareMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Luminance))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Luminance.FromCandelasPerSquareMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(LuminanceUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Luminance.FromCandelasPerSquareMeter(1.0); - Assert.Equal(Luminance.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Luminance.FromCandelasPerSquareMeter(1.0); - Assert.Equal(Luminance.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Luminance.FromCandelasPerSquareMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Luminance.FromCandelasPerSquareMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Luminance.FromCandelasPerSquareMeter(1.0); - Assert.Equal(new {Luminance.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 f0e329c2dc..fddfeaf773 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminosityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminosityTestsBase.g.cs @@ -148,7 +148,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Luminosity(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -161,15 +161,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Luminosity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + LuminosityUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Luminosity(1, LuminosityUnit.Watt); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Luminosity.Zero, quantityInfo.Zero); Assert.Equal("Luminosity", quantityInfo.Name); + Assert.Equal(Luminosity.Zero, quantityInfo.Zero); + Assert.Equal(Luminosity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Luminosity.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -196,59 +214,59 @@ public void WattToLuminosityUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Luminosity.From(1, LuminosityUnit.Decawatt); - AssertEx.EqualTolerance(1, quantity00.Decawatts, DecawattsTolerance); + Assert.Equal(1, quantity00.Decawatts); Assert.Equal(LuminosityUnit.Decawatt, quantity00.Unit); var quantity01 = Luminosity.From(1, LuminosityUnit.Deciwatt); - AssertEx.EqualTolerance(1, quantity01.Deciwatts, DeciwattsTolerance); + Assert.Equal(1, quantity01.Deciwatts); Assert.Equal(LuminosityUnit.Deciwatt, quantity01.Unit); var quantity02 = Luminosity.From(1, LuminosityUnit.Femtowatt); - AssertEx.EqualTolerance(1, quantity02.Femtowatts, FemtowattsTolerance); + Assert.Equal(1, quantity02.Femtowatts); Assert.Equal(LuminosityUnit.Femtowatt, quantity02.Unit); var quantity03 = Luminosity.From(1, LuminosityUnit.Gigawatt); - AssertEx.EqualTolerance(1, quantity03.Gigawatts, GigawattsTolerance); + Assert.Equal(1, quantity03.Gigawatts); Assert.Equal(LuminosityUnit.Gigawatt, quantity03.Unit); var quantity04 = Luminosity.From(1, LuminosityUnit.Kilowatt); - AssertEx.EqualTolerance(1, quantity04.Kilowatts, KilowattsTolerance); + Assert.Equal(1, quantity04.Kilowatts); Assert.Equal(LuminosityUnit.Kilowatt, quantity04.Unit); var quantity05 = Luminosity.From(1, LuminosityUnit.Megawatt); - AssertEx.EqualTolerance(1, quantity05.Megawatts, MegawattsTolerance); + Assert.Equal(1, quantity05.Megawatts); Assert.Equal(LuminosityUnit.Megawatt, quantity05.Unit); var quantity06 = Luminosity.From(1, LuminosityUnit.Microwatt); - AssertEx.EqualTolerance(1, quantity06.Microwatts, MicrowattsTolerance); + Assert.Equal(1, quantity06.Microwatts); Assert.Equal(LuminosityUnit.Microwatt, quantity06.Unit); var quantity07 = Luminosity.From(1, LuminosityUnit.Milliwatt); - AssertEx.EqualTolerance(1, quantity07.Milliwatts, MilliwattsTolerance); + Assert.Equal(1, quantity07.Milliwatts); Assert.Equal(LuminosityUnit.Milliwatt, quantity07.Unit); var quantity08 = Luminosity.From(1, LuminosityUnit.Nanowatt); - AssertEx.EqualTolerance(1, quantity08.Nanowatts, NanowattsTolerance); + Assert.Equal(1, quantity08.Nanowatts); Assert.Equal(LuminosityUnit.Nanowatt, quantity08.Unit); var quantity09 = Luminosity.From(1, LuminosityUnit.Petawatt); - AssertEx.EqualTolerance(1, quantity09.Petawatts, PetawattsTolerance); + Assert.Equal(1, quantity09.Petawatts); Assert.Equal(LuminosityUnit.Petawatt, quantity09.Unit); var quantity10 = Luminosity.From(1, LuminosityUnit.Picowatt); - AssertEx.EqualTolerance(1, quantity10.Picowatts, PicowattsTolerance); + Assert.Equal(1, quantity10.Picowatts); Assert.Equal(LuminosityUnit.Picowatt, quantity10.Unit); var quantity11 = Luminosity.From(1, LuminosityUnit.SolarLuminosity); - AssertEx.EqualTolerance(1, quantity11.SolarLuminosities, SolarLuminositiesTolerance); + Assert.Equal(1, quantity11.SolarLuminosities); Assert.Equal(LuminosityUnit.SolarLuminosity, quantity11.Unit); var quantity12 = Luminosity.From(1, LuminosityUnit.Terawatt); - AssertEx.EqualTolerance(1, quantity12.Terawatts, TerawattsTolerance); + Assert.Equal(1, quantity12.Terawatts); Assert.Equal(LuminosityUnit.Terawatt, quantity12.Unit); var quantity13 = Luminosity.From(1, LuminosityUnit.Watt); - AssertEx.EqualTolerance(1, quantity13.Watts, WattsTolerance); + Assert.Equal(1, quantity13.Watts); Assert.Equal(LuminosityUnit.Watt, quantity13.Unit); } @@ -397,172 +415,50 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 daW", LuminosityUnit.Decawatt, 4.2)] + [InlineData("en-US", "4.2 dW", LuminosityUnit.Deciwatt, 4.2)] + [InlineData("en-US", "4.2 fW", LuminosityUnit.Femtowatt, 4.2)] + [InlineData("en-US", "4.2 GW", LuminosityUnit.Gigawatt, 4.2)] + [InlineData("en-US", "4.2 kW", LuminosityUnit.Kilowatt, 4.2)] + [InlineData("en-US", "4.2 MW", LuminosityUnit.Megawatt, 4.2)] + [InlineData("en-US", "4.2 µW", LuminosityUnit.Microwatt, 4.2)] + [InlineData("en-US", "4.2 mW", LuminosityUnit.Milliwatt, 4.2)] + [InlineData("en-US", "4.2 nW", LuminosityUnit.Nanowatt, 4.2)] + [InlineData("en-US", "4.2 PW", LuminosityUnit.Petawatt, 4.2)] + [InlineData("en-US", "4.2 pW", LuminosityUnit.Picowatt, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = Luminosity.Parse("1 daW", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Decawatts, DecawattsTolerance); - Assert.Equal(LuminosityUnit.Decawatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Luminosity.Parse("1 dW", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Deciwatts, DeciwattsTolerance); - Assert.Equal(LuminosityUnit.Deciwatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Luminosity.Parse("1 fW", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Femtowatts, FemtowattsTolerance); - Assert.Equal(LuminosityUnit.Femtowatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Luminosity.Parse("1 GW", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Gigawatts, GigawattsTolerance); - Assert.Equal(LuminosityUnit.Gigawatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Luminosity.Parse("1 kW", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilowatts, KilowattsTolerance); - Assert.Equal(LuminosityUnit.Kilowatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Luminosity.Parse("1 MW", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megawatts, MegawattsTolerance); - Assert.Equal(LuminosityUnit.Megawatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Luminosity.Parse("1 µW", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microwatts, MicrowattsTolerance); - Assert.Equal(LuminosityUnit.Microwatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Luminosity.Parse("1 mW", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Milliwatts, MilliwattsTolerance); - Assert.Equal(LuminosityUnit.Milliwatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Luminosity.Parse("1 nW", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanowatts, NanowattsTolerance); - Assert.Equal(LuminosityUnit.Nanowatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Luminosity.Parse("1 PW", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Petawatts, PetawattsTolerance); - Assert.Equal(LuminosityUnit.Petawatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Luminosity.Parse("1 pW", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Picowatts, PicowattsTolerance); - Assert.Equal(LuminosityUnit.Picowatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Luminosity.Parse("1 L⊙", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SolarLuminosities, SolarLuminositiesTolerance); - Assert.Equal(LuminosityUnit.SolarLuminosity, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Luminosity.Parse("1 TW", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Terawatts, TerawattsTolerance); - Assert.Equal(LuminosityUnit.Terawatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Luminosity.Parse("1 W", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Watts, WattsTolerance); - Assert.Equal(LuminosityUnit.Watt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Luminosity.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 daW", LuminosityUnit.Decawatt, 4.2)] + [InlineData("en-US", "4.2 dW", LuminosityUnit.Deciwatt, 4.2)] + [InlineData("en-US", "4.2 fW", LuminosityUnit.Femtowatt, 4.2)] + [InlineData("en-US", "4.2 GW", LuminosityUnit.Gigawatt, 4.2)] + [InlineData("en-US", "4.2 kW", LuminosityUnit.Kilowatt, 4.2)] + [InlineData("en-US", "4.2 MW", LuminosityUnit.Megawatt, 4.2)] + [InlineData("en-US", "4.2 µW", LuminosityUnit.Microwatt, 4.2)] + [InlineData("en-US", "4.2 mW", LuminosityUnit.Milliwatt, 4.2)] + [InlineData("en-US", "4.2 nW", LuminosityUnit.Nanowatt, 4.2)] + [InlineData("en-US", "4.2 PW", LuminosityUnit.Petawatt, 4.2)] + [InlineData("en-US", "4.2 pW", LuminosityUnit.Picowatt, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(Luminosity.TryParse("1 daW", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Decawatts, DecawattsTolerance); - Assert.Equal(LuminosityUnit.Decawatt, parsed.Unit); - } - - { - Assert.True(Luminosity.TryParse("1 dW", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Deciwatts, DeciwattsTolerance); - Assert.Equal(LuminosityUnit.Deciwatt, parsed.Unit); - } - - { - Assert.True(Luminosity.TryParse("1 fW", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Femtowatts, FemtowattsTolerance); - Assert.Equal(LuminosityUnit.Femtowatt, parsed.Unit); - } - - { - Assert.True(Luminosity.TryParse("1 GW", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gigawatts, GigawattsTolerance); - Assert.Equal(LuminosityUnit.Gigawatt, parsed.Unit); - } - - { - Assert.True(Luminosity.TryParse("1 kW", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilowatts, KilowattsTolerance); - Assert.Equal(LuminosityUnit.Kilowatt, parsed.Unit); - } - - { - Assert.True(Luminosity.TryParse("1 µW", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microwatts, MicrowattsTolerance); - Assert.Equal(LuminosityUnit.Microwatt, parsed.Unit); - } - - { - Assert.True(Luminosity.TryParse("1 nW", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanowatts, NanowattsTolerance); - Assert.Equal(LuminosityUnit.Nanowatt, parsed.Unit); - } - - { - Assert.True(Luminosity.TryParse("1 L⊙", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SolarLuminosities, SolarLuminositiesTolerance); - Assert.Equal(LuminosityUnit.SolarLuminosity, parsed.Unit); - } - - { - Assert.True(Luminosity.TryParse("1 TW", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Terawatts, TerawattsTolerance); - Assert.Equal(LuminosityUnit.Terawatt, parsed.Unit); - } - - { - Assert.True(Luminosity.TryParse("1 W", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Watts, WattsTolerance); - Assert.Equal(LuminosityUnit.Watt, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Luminosity.TryParse(quantityString, out Luminosity parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -743,6 +639,40 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Lumino Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", LuminosityUnit.Decawatt, "daW")] + [InlineData("en-US", LuminosityUnit.Deciwatt, "dW")] + [InlineData("en-US", LuminosityUnit.Femtowatt, "fW")] + [InlineData("en-US", LuminosityUnit.Gigawatt, "GW")] + [InlineData("en-US", LuminosityUnit.Kilowatt, "kW")] + [InlineData("en-US", LuminosityUnit.Megawatt, "MW")] + [InlineData("en-US", LuminosityUnit.Microwatt, "µW")] + [InlineData("en-US", LuminosityUnit.Milliwatt, "mW")] + [InlineData("en-US", LuminosityUnit.Nanowatt, "nW")] + [InlineData("en-US", LuminosityUnit.Petawatt, "PW")] + [InlineData("en-US", LuminosityUnit.Picowatt, "pW")] + [InlineData("en-US", LuminosityUnit.SolarLuminosity, "L⊙")] + [InlineData("en-US", LuminosityUnit.Terawatt, "TW")] + [InlineData("en-US", LuminosityUnit.Watt, "W")] + public void GetAbbreviationForCulture(string culture, LuminosityUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Luminosity.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Luminosity.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Luminosity.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(LuminosityUnit unit) @@ -773,6 +703,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); }); } @@ -796,45 +727,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] @@ -880,8 +813,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); @@ -919,34 +850,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = Luminosity.FromWatts(1); - Assert.True(v.Equals(Luminosity.FromWatts(1), WattsTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Luminosity.Zero, WattsTolerance, ComparisonType.Relative)); - Assert.True(Luminosity.FromWatts(100).Equals(Luminosity.FromWatts(120), 0.3, ComparisonType.Relative)); - Assert.False(Luminosity.FromWatts(100).Equals(Luminosity.FromWatts(120), 0.1, ComparisonType.Relative)); + Luminosity watt = Luminosity.FromWatts(1); + Assert.False(watt.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = Luminosity.FromWatts(1); - Assert.Throws(() => v.Equals(Luminosity.FromWatts(1), -1, ComparisonType.Relative)); + Luminosity watt = Luminosity.FromWatts(1); + Assert.False(watt.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - Luminosity watt = Luminosity.FromWatts(1); - Assert.False(watt.Equals(new object())); + var quantity = Luminosity.FromWatts(firstValue); + var otherQuantity = Luminosity.FromWatts(secondValue); + Luminosity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - Luminosity watt = Luminosity.FromWatts(1); - Assert.False(watt.Equals(null)); + var quantity = Luminosity.FromWatts(1); + var negativeTolerance = Luminosity.FromWatts(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -965,6 +905,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() { @@ -1049,158 +1001,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Luminosity.FromWatts(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Luminosity.FromWatts(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Luminosity.FromWatts(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Luminosity.FromWatts(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Luminosity.FromWatts(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Luminosity.FromWatts(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Luminosity.FromWatts(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Luminosity.FromWatts(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Luminosity.FromWatts(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Luminosity.FromWatts(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Luminosity.FromWatts(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Luminosity.FromWatts(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Luminosity.FromWatts(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Luminosity.FromWatts(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Luminosity.FromWatts(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Luminosity.FromWatts(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Luminosity))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Luminosity.FromWatts(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(LuminosityUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Luminosity.FromWatts(1.0); - Assert.Equal(Luminosity.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Luminosity.FromWatts(1.0); - Assert.Equal(Luminosity.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Luminosity.FromWatts(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Luminosity.FromWatts(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Luminosity.FromWatts(1.0); - Assert.Equal(new {Luminosity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 160e4ebb2e..91e9b1d66e 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousFluxTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousFluxTestsBase.g.cs @@ -96,7 +96,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new LuminousFlux(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -109,15 +109,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void LuminousFlux_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + LuminousFluxUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new LuminousFlux(1, LuminousFluxUnit.Lumen); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(LuminousFlux.Zero, quantityInfo.Zero); Assert.Equal("LuminousFlux", quantityInfo.Name); + Assert.Equal(LuminousFlux.Zero, quantityInfo.Zero); + Assert.Equal(LuminousFlux.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(LuminousFlux.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -131,7 +149,7 @@ public void LumenToLuminousFluxUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = LuminousFlux.From(1, LuminousFluxUnit.Lumen); - AssertEx.EqualTolerance(1, quantity00.Lumens, LumensTolerance); + Assert.Equal(1, quantity00.Lumens); Assert.Equal(LuminousFluxUnit.Lumen, quantity00.Unit); } @@ -267,27 +285,24 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 lm", LuminousFluxUnit.Lumen, 4.2)] + public void Parse(string culture, string quantityString, LuminousFluxUnit expectedUnit, decimal expectedValue) { - try - { - var parsed = LuminousFlux.Parse("1 lm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Lumens, LumensTolerance); - Assert.Equal(LuminousFluxUnit.Lumen, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = LuminousFlux.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 lm", LuminousFluxUnit.Lumen, 4.2)] + public void TryParse(string culture, string quantityString, LuminousFluxUnit expectedUnit, decimal expectedValue) { - { - Assert.True(LuminousFlux.TryParse("1 lm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Lumens, LumensTolerance); - Assert.Equal(LuminousFluxUnit.Lumen, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(LuminousFlux.TryParse(quantityString, out LuminousFlux parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -364,6 +379,27 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Lumino Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", LuminousFluxUnit.Lumen, "lm")] + public void GetAbbreviationForCulture(string culture, LuminousFluxUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = LuminousFlux.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(LuminousFlux.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = LuminousFlux.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(LuminousFluxUnit unit) @@ -394,6 +430,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); }); } @@ -417,32 +454,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] @@ -488,7 +527,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); @@ -526,34 +564,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = LuminousFlux.FromLumens(1); - Assert.True(v.Equals(LuminousFlux.FromLumens(1), LumensTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(LuminousFlux.Zero, LumensTolerance, ComparisonType.Relative)); - Assert.True(LuminousFlux.FromLumens(100).Equals(LuminousFlux.FromLumens(120), 0.3, ComparisonType.Relative)); - Assert.False(LuminousFlux.FromLumens(100).Equals(LuminousFlux.FromLumens(120), 0.1, ComparisonType.Relative)); + LuminousFlux lumen = LuminousFlux.FromLumens(1); + Assert.False(lumen.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = LuminousFlux.FromLumens(1); - Assert.Throws(() => v.Equals(LuminousFlux.FromLumens(1), -1, ComparisonType.Relative)); + LuminousFlux lumen = LuminousFlux.FromLumens(1); + Assert.False(lumen.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - LuminousFlux lumen = LuminousFlux.FromLumens(1); - Assert.False(lumen.Equals(new object())); + var quantity = LuminousFlux.FromLumens(firstValue); + var otherQuantity = LuminousFlux.FromLumens(secondValue); + LuminousFlux maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - LuminousFlux lumen = LuminousFlux.FromLumens(1); - Assert.False(lumen.Equals(null)); + var quantity = LuminousFlux.FromLumens(1); + var negativeTolerance = LuminousFlux.FromLumens(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -572,6 +619,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() { @@ -630,158 +689,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(LuminousFlux))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(LuminousFluxUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal(LuminousFlux.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal(LuminousFlux.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal(new {LuminousFlux.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 8230107c03..2d1dd39f80 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousIntensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousIntensityTestsBase.g.cs @@ -96,7 +96,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new LuminousIntensity(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -109,15 +109,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void LuminousIntensity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + LuminousIntensityUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new LuminousIntensity(1, LuminousIntensityUnit.Candela); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(LuminousIntensity.Zero, quantityInfo.Zero); Assert.Equal("LuminousIntensity", quantityInfo.Name); + Assert.Equal(LuminousIntensity.Zero, quantityInfo.Zero); + Assert.Equal(LuminousIntensity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(LuminousIntensity.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -131,7 +149,7 @@ public void CandelaToLuminousIntensityUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = LuminousIntensity.From(1, LuminousIntensityUnit.Candela); - AssertEx.EqualTolerance(1, quantity00.Candela, CandelaTolerance); + Assert.Equal(1, quantity00.Candela); Assert.Equal(LuminousIntensityUnit.Candela, quantity00.Unit); } @@ -267,27 +285,24 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 cd", LuminousIntensityUnit.Candela, 4.2)] + public void Parse(string culture, string quantityString, LuminousIntensityUnit expectedUnit, decimal expectedValue) { - try - { - var parsed = LuminousIntensity.Parse("1 cd", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Candela, CandelaTolerance); - Assert.Equal(LuminousIntensityUnit.Candela, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = LuminousIntensity.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 cd", LuminousIntensityUnit.Candela, 4.2)] + public void TryParse(string culture, string quantityString, LuminousIntensityUnit expectedUnit, decimal expectedValue) { - { - Assert.True(LuminousIntensity.TryParse("1 cd", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Candela, CandelaTolerance); - Assert.Equal(LuminousIntensityUnit.Candela, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(LuminousIntensity.TryParse(quantityString, out LuminousIntensity parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -364,6 +379,27 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Lumino Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", LuminousIntensityUnit.Candela, "cd")] + public void GetAbbreviationForCulture(string culture, LuminousIntensityUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = LuminousIntensity.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(LuminousIntensity.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = LuminousIntensity.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(LuminousIntensityUnit unit) @@ -394,6 +430,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); }); } @@ -417,32 +454,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] @@ -488,7 +527,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); @@ -526,34 +564,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = LuminousIntensity.FromCandela(1); - Assert.True(v.Equals(LuminousIntensity.FromCandela(1), CandelaTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(LuminousIntensity.Zero, CandelaTolerance, ComparisonType.Relative)); - Assert.True(LuminousIntensity.FromCandela(100).Equals(LuminousIntensity.FromCandela(120), 0.3, ComparisonType.Relative)); - Assert.False(LuminousIntensity.FromCandela(100).Equals(LuminousIntensity.FromCandela(120), 0.1, ComparisonType.Relative)); + LuminousIntensity candela = LuminousIntensity.FromCandela(1); + Assert.False(candela.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = LuminousIntensity.FromCandela(1); - Assert.Throws(() => v.Equals(LuminousIntensity.FromCandela(1), -1, ComparisonType.Relative)); + LuminousIntensity candela = LuminousIntensity.FromCandela(1); + Assert.False(candela.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - LuminousIntensity candela = LuminousIntensity.FromCandela(1); - Assert.False(candela.Equals(new object())); + var quantity = LuminousIntensity.FromCandela(firstValue); + var otherQuantity = LuminousIntensity.FromCandela(secondValue); + LuminousIntensity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - LuminousIntensity candela = LuminousIntensity.FromCandela(1); - Assert.False(candela.Equals(null)); + var quantity = LuminousIntensity.FromCandela(1); + var negativeTolerance = LuminousIntensity.FromCandela(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -572,6 +619,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() { @@ -630,158 +689,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(LuminousIntensity))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(LuminousIntensityUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal(LuminousIntensity.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal(LuminousIntensity.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal(new {LuminousIntensity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 a4583b5848..76aac0f089 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFieldTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFieldTestsBase.g.cs @@ -116,7 +116,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new MagneticField(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -129,15 +129,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void MagneticField_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + MagneticFieldUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new MagneticField(1, MagneticFieldUnit.Tesla); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(MagneticField.Zero, quantityInfo.Zero); Assert.Equal("MagneticField", quantityInfo.Name); + Assert.Equal(MagneticField.Zero, quantityInfo.Zero); + Assert.Equal(MagneticField.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(MagneticField.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void MagneticFieldInfo_CreateWithCustomUnitInfos() + { + MagneticFieldUnit[] expectedUnits = [MagneticFieldUnit.Tesla]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -156,27 +174,27 @@ public void TeslaToMagneticFieldUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = MagneticField.From(1, MagneticFieldUnit.Gauss); - AssertEx.EqualTolerance(1, quantity00.Gausses, GaussesTolerance); + Assert.Equal(1, quantity00.Gausses); Assert.Equal(MagneticFieldUnit.Gauss, quantity00.Unit); var quantity01 = MagneticField.From(1, MagneticFieldUnit.Microtesla); - AssertEx.EqualTolerance(1, quantity01.Microteslas, MicroteslasTolerance); + Assert.Equal(1, quantity01.Microteslas); Assert.Equal(MagneticFieldUnit.Microtesla, quantity01.Unit); var quantity02 = MagneticField.From(1, MagneticFieldUnit.Milligauss); - AssertEx.EqualTolerance(1, quantity02.Milligausses, MilligaussesTolerance); + Assert.Equal(1, quantity02.Milligausses); Assert.Equal(MagneticFieldUnit.Milligauss, quantity02.Unit); var quantity03 = MagneticField.From(1, MagneticFieldUnit.Millitesla); - AssertEx.EqualTolerance(1, quantity03.Milliteslas, MilliteslasTolerance); + Assert.Equal(1, quantity03.Milliteslas); Assert.Equal(MagneticFieldUnit.Millitesla, quantity03.Unit); var quantity04 = MagneticField.From(1, MagneticFieldUnit.Nanotesla); - AssertEx.EqualTolerance(1, quantity04.Nanoteslas, NanoteslasTolerance); + Assert.Equal(1, quantity04.Nanoteslas); Assert.Equal(MagneticFieldUnit.Nanotesla, quantity04.Unit); var quantity05 = MagneticField.From(1, MagneticFieldUnit.Tesla); - AssertEx.EqualTolerance(1, quantity05.Teslas, TeslasTolerance); + Assert.Equal(1, quantity05.Teslas); Assert.Equal(MagneticFieldUnit.Tesla, quantity05.Unit); } @@ -317,92 +335,34 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 G", MagneticFieldUnit.Gauss, 4.2)] + [InlineData("en-US", "4.2 µT", MagneticFieldUnit.Microtesla, 4.2)] + [InlineData("en-US", "4.2 mG", MagneticFieldUnit.Milligauss, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = MagneticField.Parse("1 G", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Gausses, GaussesTolerance); - Assert.Equal(MagneticFieldUnit.Gauss, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MagneticField.Parse("1 µT", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microteslas, MicroteslasTolerance); - Assert.Equal(MagneticFieldUnit.Microtesla, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MagneticField.Parse("1 mG", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Milligausses, MilligaussesTolerance); - Assert.Equal(MagneticFieldUnit.Milligauss, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MagneticField.Parse("1 mT", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Milliteslas, MilliteslasTolerance); - Assert.Equal(MagneticFieldUnit.Millitesla, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MagneticField.Parse("1 nT", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanoteslas, NanoteslasTolerance); - Assert.Equal(MagneticFieldUnit.Nanotesla, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MagneticField.Parse("1 T", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Teslas, TeslasTolerance); - Assert.Equal(MagneticFieldUnit.Tesla, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = MagneticField.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 G", MagneticFieldUnit.Gauss, 4.2)] + [InlineData("en-US", "4.2 µT", MagneticFieldUnit.Microtesla, 4.2)] + [InlineData("en-US", "4.2 mG", MagneticFieldUnit.Milligauss, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(MagneticField.TryParse("1 G", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gausses, GaussesTolerance); - Assert.Equal(MagneticFieldUnit.Gauss, parsed.Unit); - } - - { - Assert.True(MagneticField.TryParse("1 µT", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microteslas, MicroteslasTolerance); - Assert.Equal(MagneticFieldUnit.Microtesla, parsed.Unit); - } - - { - Assert.True(MagneticField.TryParse("1 mG", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Milligausses, MilligaussesTolerance); - Assert.Equal(MagneticFieldUnit.Milligauss, parsed.Unit); - } - - { - Assert.True(MagneticField.TryParse("1 mT", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Milliteslas, MilliteslasTolerance); - Assert.Equal(MagneticFieldUnit.Millitesla, parsed.Unit); - } - - { - Assert.True(MagneticField.TryParse("1 nT", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanoteslas, NanoteslasTolerance); - Assert.Equal(MagneticFieldUnit.Nanotesla, parsed.Unit); - } - - { - Assert.True(MagneticField.TryParse("1 T", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Teslas, TeslasTolerance); - Assert.Equal(MagneticFieldUnit.Tesla, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(MagneticField.TryParse(quantityString, out MagneticField parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -519,6 +479,32 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Magnet Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", MagneticFieldUnit.Gauss, "G")] + [InlineData("en-US", MagneticFieldUnit.Microtesla, "µT")] + [InlineData("en-US", MagneticFieldUnit.Milligauss, "mG")] + [InlineData("en-US", MagneticFieldUnit.Millitesla, "mT")] + [InlineData("en-US", MagneticFieldUnit.Nanotesla, "nT")] + [InlineData("en-US", MagneticFieldUnit.Tesla, "T")] + public void GetAbbreviationForCulture(string culture, MagneticFieldUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = MagneticField.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(MagneticField.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = MagneticField.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(MagneticFieldUnit unit) @@ -549,6 +535,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); }); } @@ -572,37 +559,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] @@ -648,8 +637,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); @@ -687,34 +674,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = MagneticField.FromTeslas(1); - Assert.True(v.Equals(MagneticField.FromTeslas(1), TeslasTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(MagneticField.Zero, TeslasTolerance, ComparisonType.Relative)); - Assert.True(MagneticField.FromTeslas(100).Equals(MagneticField.FromTeslas(120), 0.3, ComparisonType.Relative)); - Assert.False(MagneticField.FromTeslas(100).Equals(MagneticField.FromTeslas(120), 0.1, ComparisonType.Relative)); + MagneticField tesla = MagneticField.FromTeslas(1); + Assert.False(tesla.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = MagneticField.FromTeslas(1); - Assert.Throws(() => v.Equals(MagneticField.FromTeslas(1), -1, ComparisonType.Relative)); + MagneticField tesla = MagneticField.FromTeslas(1); + Assert.False(tesla.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - MagneticField tesla = MagneticField.FromTeslas(1); - Assert.False(tesla.Equals(new object())); + var quantity = MagneticField.FromTeslas(firstValue); + var otherQuantity = MagneticField.FromTeslas(secondValue); + MagneticField maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - MagneticField tesla = MagneticField.FromTeslas(1); - Assert.False(tesla.Equals(null)); + var quantity = MagneticField.FromTeslas(1); + var negativeTolerance = MagneticField.FromTeslas(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -733,6 +729,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() { @@ -801,158 +809,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(MagneticField))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MagneticFieldUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal(MagneticField.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal(MagneticField.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal(new {MagneticField.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 4a7304697a..e1f6035251 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFluxTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFluxTestsBase.g.cs @@ -96,7 +96,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new MagneticFlux(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -109,15 +109,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void MagneticFlux_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + MagneticFluxUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new MagneticFlux(1, MagneticFluxUnit.Weber); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(MagneticFlux.Zero, quantityInfo.Zero); Assert.Equal("MagneticFlux", quantityInfo.Name); + Assert.Equal(MagneticFlux.Zero, quantityInfo.Zero); + Assert.Equal(MagneticFlux.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(MagneticFlux.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -131,7 +149,7 @@ public void WeberToMagneticFluxUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = MagneticFlux.From(1, MagneticFluxUnit.Weber); - AssertEx.EqualTolerance(1, quantity00.Webers, WebersTolerance); + Assert.Equal(1, quantity00.Webers); Assert.Equal(MagneticFluxUnit.Weber, quantity00.Unit); } @@ -267,27 +285,24 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 Wb", MagneticFluxUnit.Weber, 4.2)] + public void Parse(string culture, string quantityString, MagneticFluxUnit expectedUnit, decimal expectedValue) { - try - { - var parsed = MagneticFlux.Parse("1 Wb", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Webers, WebersTolerance); - Assert.Equal(MagneticFluxUnit.Weber, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = MagneticFlux.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 Wb", MagneticFluxUnit.Weber, 4.2)] + public void TryParse(string culture, string quantityString, MagneticFluxUnit expectedUnit, decimal expectedValue) { - { - Assert.True(MagneticFlux.TryParse("1 Wb", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Webers, WebersTolerance); - Assert.Equal(MagneticFluxUnit.Weber, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(MagneticFlux.TryParse(quantityString, out MagneticFlux parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -364,6 +379,27 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Magnet Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", MagneticFluxUnit.Weber, "Wb")] + public void GetAbbreviationForCulture(string culture, MagneticFluxUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = MagneticFlux.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(MagneticFlux.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = MagneticFlux.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(MagneticFluxUnit unit) @@ -394,6 +430,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); }); } @@ -417,32 +454,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] @@ -488,7 +527,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); @@ -526,34 +564,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = MagneticFlux.FromWebers(1); - Assert.True(v.Equals(MagneticFlux.FromWebers(1), WebersTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(MagneticFlux.Zero, WebersTolerance, ComparisonType.Relative)); - Assert.True(MagneticFlux.FromWebers(100).Equals(MagneticFlux.FromWebers(120), 0.3, ComparisonType.Relative)); - Assert.False(MagneticFlux.FromWebers(100).Equals(MagneticFlux.FromWebers(120), 0.1, ComparisonType.Relative)); + MagneticFlux weber = MagneticFlux.FromWebers(1); + Assert.False(weber.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = MagneticFlux.FromWebers(1); - Assert.Throws(() => v.Equals(MagneticFlux.FromWebers(1), -1, ComparisonType.Relative)); + MagneticFlux weber = MagneticFlux.FromWebers(1); + Assert.False(weber.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - MagneticFlux weber = MagneticFlux.FromWebers(1); - Assert.False(weber.Equals(new object())); + var quantity = MagneticFlux.FromWebers(firstValue); + var otherQuantity = MagneticFlux.FromWebers(secondValue); + MagneticFlux maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - MagneticFlux weber = MagneticFlux.FromWebers(1); - Assert.False(weber.Equals(null)); + var quantity = MagneticFlux.FromWebers(1); + var negativeTolerance = MagneticFlux.FromWebers(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -572,6 +619,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() { @@ -630,158 +689,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(MagneticFlux))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MagneticFluxUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal(MagneticFlux.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal(MagneticFlux.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal(new {MagneticFlux.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 5258a826ff..2654f8ca24 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MagnetizationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MagnetizationTestsBase.g.cs @@ -96,7 +96,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Magnetization(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -109,15 +109,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Magnetization_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + MagnetizationUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Magnetization(1, MagnetizationUnit.AmperePerMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Magnetization.Zero, quantityInfo.Zero); Assert.Equal("Magnetization", quantityInfo.Name); + Assert.Equal(Magnetization.Zero, quantityInfo.Zero); + Assert.Equal(Magnetization.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Magnetization.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -131,7 +149,7 @@ public void AmperePerMeterToMagnetizationUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Magnetization.From(1, MagnetizationUnit.AmperePerMeter); - AssertEx.EqualTolerance(1, quantity00.AmperesPerMeter, AmperesPerMeterTolerance); + Assert.Equal(1, quantity00.AmperesPerMeter); Assert.Equal(MagnetizationUnit.AmperePerMeter, quantity00.Unit); } @@ -267,27 +285,24 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 A/m", MagnetizationUnit.AmperePerMeter, 4.2)] + public void Parse(string culture, string quantityString, MagnetizationUnit expectedUnit, decimal expectedValue) { - try - { - var parsed = Magnetization.Parse("1 A/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.AmperesPerMeter, AmperesPerMeterTolerance); - Assert.Equal(MagnetizationUnit.AmperePerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Magnetization.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 A/m", MagnetizationUnit.AmperePerMeter, 4.2)] + public void TryParse(string culture, string quantityString, MagnetizationUnit expectedUnit, decimal expectedValue) { - { - Assert.True(Magnetization.TryParse("1 A/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.AmperesPerMeter, AmperesPerMeterTolerance); - Assert.Equal(MagnetizationUnit.AmperePerMeter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Magnetization.TryParse(quantityString, out Magnetization parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -364,6 +379,27 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Magnet Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", MagnetizationUnit.AmperePerMeter, "A/m")] + public void GetAbbreviationForCulture(string culture, MagnetizationUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Magnetization.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Magnetization.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Magnetization.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(MagnetizationUnit unit) @@ -394,6 +430,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); }); } @@ -417,32 +454,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] @@ -488,7 +527,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); @@ -526,34 +564,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = Magnetization.FromAmperesPerMeter(1); - Assert.True(v.Equals(Magnetization.FromAmperesPerMeter(1), AmperesPerMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Magnetization.Zero, AmperesPerMeterTolerance, ComparisonType.Relative)); - Assert.True(Magnetization.FromAmperesPerMeter(100).Equals(Magnetization.FromAmperesPerMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(Magnetization.FromAmperesPerMeter(100).Equals(Magnetization.FromAmperesPerMeter(120), 0.1, ComparisonType.Relative)); + Magnetization amperepermeter = Magnetization.FromAmperesPerMeter(1); + Assert.False(amperepermeter.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = Magnetization.FromAmperesPerMeter(1); - Assert.Throws(() => v.Equals(Magnetization.FromAmperesPerMeter(1), -1, ComparisonType.Relative)); + Magnetization amperepermeter = Magnetization.FromAmperesPerMeter(1); + Assert.False(amperepermeter.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - Magnetization amperepermeter = Magnetization.FromAmperesPerMeter(1); - Assert.False(amperepermeter.Equals(new object())); + var quantity = Magnetization.FromAmperesPerMeter(firstValue); + var otherQuantity = Magnetization.FromAmperesPerMeter(secondValue); + Magnetization maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - Magnetization amperepermeter = Magnetization.FromAmperesPerMeter(1); - Assert.False(amperepermeter.Equals(null)); + var quantity = Magnetization.FromAmperesPerMeter(1); + var negativeTolerance = Magnetization.FromAmperesPerMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -572,6 +619,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() { @@ -630,158 +689,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Magnetization))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MagnetizationUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal(Magnetization.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal(Magnetization.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal(new {Magnetization.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 9da05493c0..a39cc2f03b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassConcentrationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassConcentrationTestsBase.g.cs @@ -288,7 +288,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new MassConcentration(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -301,15 +301,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void MassConcentration_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + MassConcentrationUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new MassConcentration(1, MassConcentrationUnit.KilogramPerCubicMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(MassConcentration.Zero, quantityInfo.Zero); Assert.Equal("MassConcentration", quantityInfo.Name); + Assert.Equal(MassConcentration.Zero, quantityInfo.Zero); + Assert.Equal(MassConcentration.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(MassConcentration.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -371,199 +389,199 @@ public void KilogramPerCubicMeterToMassConcentrationUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = MassConcentration.From(1, MassConcentrationUnit.CentigramPerDeciliter); - AssertEx.EqualTolerance(1, quantity00.CentigramsPerDeciliter, CentigramsPerDeciliterTolerance); + Assert.Equal(1, quantity00.CentigramsPerDeciliter); Assert.Equal(MassConcentrationUnit.CentigramPerDeciliter, quantity00.Unit); var quantity01 = MassConcentration.From(1, MassConcentrationUnit.CentigramPerLiter); - AssertEx.EqualTolerance(1, quantity01.CentigramsPerLiter, CentigramsPerLiterTolerance); + Assert.Equal(1, quantity01.CentigramsPerLiter); Assert.Equal(MassConcentrationUnit.CentigramPerLiter, quantity01.Unit); var quantity02 = MassConcentration.From(1, MassConcentrationUnit.CentigramPerMicroliter); - AssertEx.EqualTolerance(1, quantity02.CentigramsPerMicroliter, CentigramsPerMicroliterTolerance); + Assert.Equal(1, quantity02.CentigramsPerMicroliter); Assert.Equal(MassConcentrationUnit.CentigramPerMicroliter, quantity02.Unit); var quantity03 = MassConcentration.From(1, MassConcentrationUnit.CentigramPerMilliliter); - AssertEx.EqualTolerance(1, quantity03.CentigramsPerMilliliter, CentigramsPerMilliliterTolerance); + Assert.Equal(1, quantity03.CentigramsPerMilliliter); Assert.Equal(MassConcentrationUnit.CentigramPerMilliliter, quantity03.Unit); var quantity04 = MassConcentration.From(1, MassConcentrationUnit.DecigramPerDeciliter); - AssertEx.EqualTolerance(1, quantity04.DecigramsPerDeciliter, DecigramsPerDeciliterTolerance); + Assert.Equal(1, quantity04.DecigramsPerDeciliter); Assert.Equal(MassConcentrationUnit.DecigramPerDeciliter, quantity04.Unit); var quantity05 = MassConcentration.From(1, MassConcentrationUnit.DecigramPerLiter); - AssertEx.EqualTolerance(1, quantity05.DecigramsPerLiter, DecigramsPerLiterTolerance); + Assert.Equal(1, quantity05.DecigramsPerLiter); Assert.Equal(MassConcentrationUnit.DecigramPerLiter, quantity05.Unit); var quantity06 = MassConcentration.From(1, MassConcentrationUnit.DecigramPerMicroliter); - AssertEx.EqualTolerance(1, quantity06.DecigramsPerMicroliter, DecigramsPerMicroliterTolerance); + Assert.Equal(1, quantity06.DecigramsPerMicroliter); Assert.Equal(MassConcentrationUnit.DecigramPerMicroliter, quantity06.Unit); var quantity07 = MassConcentration.From(1, MassConcentrationUnit.DecigramPerMilliliter); - AssertEx.EqualTolerance(1, quantity07.DecigramsPerMilliliter, DecigramsPerMilliliterTolerance); + Assert.Equal(1, quantity07.DecigramsPerMilliliter); Assert.Equal(MassConcentrationUnit.DecigramPerMilliliter, quantity07.Unit); var quantity08 = MassConcentration.From(1, MassConcentrationUnit.GramPerCubicCentimeter); - AssertEx.EqualTolerance(1, quantity08.GramsPerCubicCentimeter, GramsPerCubicCentimeterTolerance); + Assert.Equal(1, quantity08.GramsPerCubicCentimeter); Assert.Equal(MassConcentrationUnit.GramPerCubicCentimeter, quantity08.Unit); var quantity09 = MassConcentration.From(1, MassConcentrationUnit.GramPerCubicMeter); - AssertEx.EqualTolerance(1, quantity09.GramsPerCubicMeter, GramsPerCubicMeterTolerance); + Assert.Equal(1, quantity09.GramsPerCubicMeter); Assert.Equal(MassConcentrationUnit.GramPerCubicMeter, quantity09.Unit); var quantity10 = MassConcentration.From(1, MassConcentrationUnit.GramPerCubicMillimeter); - AssertEx.EqualTolerance(1, quantity10.GramsPerCubicMillimeter, GramsPerCubicMillimeterTolerance); + Assert.Equal(1, quantity10.GramsPerCubicMillimeter); Assert.Equal(MassConcentrationUnit.GramPerCubicMillimeter, quantity10.Unit); var quantity11 = MassConcentration.From(1, MassConcentrationUnit.GramPerDeciliter); - AssertEx.EqualTolerance(1, quantity11.GramsPerDeciliter, GramsPerDeciliterTolerance); + Assert.Equal(1, quantity11.GramsPerDeciliter); Assert.Equal(MassConcentrationUnit.GramPerDeciliter, quantity11.Unit); var quantity12 = MassConcentration.From(1, MassConcentrationUnit.GramPerLiter); - AssertEx.EqualTolerance(1, quantity12.GramsPerLiter, GramsPerLiterTolerance); + Assert.Equal(1, quantity12.GramsPerLiter); Assert.Equal(MassConcentrationUnit.GramPerLiter, quantity12.Unit); var quantity13 = MassConcentration.From(1, MassConcentrationUnit.GramPerMicroliter); - AssertEx.EqualTolerance(1, quantity13.GramsPerMicroliter, GramsPerMicroliterTolerance); + Assert.Equal(1, quantity13.GramsPerMicroliter); Assert.Equal(MassConcentrationUnit.GramPerMicroliter, quantity13.Unit); var quantity14 = MassConcentration.From(1, MassConcentrationUnit.GramPerMilliliter); - AssertEx.EqualTolerance(1, quantity14.GramsPerMilliliter, GramsPerMilliliterTolerance); + Assert.Equal(1, quantity14.GramsPerMilliliter); Assert.Equal(MassConcentrationUnit.GramPerMilliliter, quantity14.Unit); var quantity15 = MassConcentration.From(1, MassConcentrationUnit.KilogramPerCubicCentimeter); - AssertEx.EqualTolerance(1, quantity15.KilogramsPerCubicCentimeter, KilogramsPerCubicCentimeterTolerance); + Assert.Equal(1, quantity15.KilogramsPerCubicCentimeter); Assert.Equal(MassConcentrationUnit.KilogramPerCubicCentimeter, quantity15.Unit); var quantity16 = MassConcentration.From(1, MassConcentrationUnit.KilogramPerCubicMeter); - AssertEx.EqualTolerance(1, quantity16.KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); + Assert.Equal(1, quantity16.KilogramsPerCubicMeter); Assert.Equal(MassConcentrationUnit.KilogramPerCubicMeter, quantity16.Unit); var quantity17 = MassConcentration.From(1, MassConcentrationUnit.KilogramPerCubicMillimeter); - AssertEx.EqualTolerance(1, quantity17.KilogramsPerCubicMillimeter, KilogramsPerCubicMillimeterTolerance); + Assert.Equal(1, quantity17.KilogramsPerCubicMillimeter); Assert.Equal(MassConcentrationUnit.KilogramPerCubicMillimeter, quantity17.Unit); var quantity18 = MassConcentration.From(1, MassConcentrationUnit.KilogramPerLiter); - AssertEx.EqualTolerance(1, quantity18.KilogramsPerLiter, KilogramsPerLiterTolerance); + Assert.Equal(1, quantity18.KilogramsPerLiter); Assert.Equal(MassConcentrationUnit.KilogramPerLiter, quantity18.Unit); var quantity19 = MassConcentration.From(1, MassConcentrationUnit.KilopoundPerCubicFoot); - AssertEx.EqualTolerance(1, quantity19.KilopoundsPerCubicFoot, KilopoundsPerCubicFootTolerance); + Assert.Equal(1, quantity19.KilopoundsPerCubicFoot); Assert.Equal(MassConcentrationUnit.KilopoundPerCubicFoot, quantity19.Unit); var quantity20 = MassConcentration.From(1, MassConcentrationUnit.KilopoundPerCubicInch); - AssertEx.EqualTolerance(1, quantity20.KilopoundsPerCubicInch, KilopoundsPerCubicInchTolerance); + Assert.Equal(1, quantity20.KilopoundsPerCubicInch); Assert.Equal(MassConcentrationUnit.KilopoundPerCubicInch, quantity20.Unit); var quantity21 = MassConcentration.From(1, MassConcentrationUnit.MicrogramPerCubicMeter); - AssertEx.EqualTolerance(1, quantity21.MicrogramsPerCubicMeter, MicrogramsPerCubicMeterTolerance); + Assert.Equal(1, quantity21.MicrogramsPerCubicMeter); Assert.Equal(MassConcentrationUnit.MicrogramPerCubicMeter, quantity21.Unit); var quantity22 = MassConcentration.From(1, MassConcentrationUnit.MicrogramPerDeciliter); - AssertEx.EqualTolerance(1, quantity22.MicrogramsPerDeciliter, MicrogramsPerDeciliterTolerance); + Assert.Equal(1, quantity22.MicrogramsPerDeciliter); Assert.Equal(MassConcentrationUnit.MicrogramPerDeciliter, quantity22.Unit); var quantity23 = MassConcentration.From(1, MassConcentrationUnit.MicrogramPerLiter); - AssertEx.EqualTolerance(1, quantity23.MicrogramsPerLiter, MicrogramsPerLiterTolerance); + Assert.Equal(1, quantity23.MicrogramsPerLiter); Assert.Equal(MassConcentrationUnit.MicrogramPerLiter, quantity23.Unit); var quantity24 = MassConcentration.From(1, MassConcentrationUnit.MicrogramPerMicroliter); - AssertEx.EqualTolerance(1, quantity24.MicrogramsPerMicroliter, MicrogramsPerMicroliterTolerance); + Assert.Equal(1, quantity24.MicrogramsPerMicroliter); Assert.Equal(MassConcentrationUnit.MicrogramPerMicroliter, quantity24.Unit); var quantity25 = MassConcentration.From(1, MassConcentrationUnit.MicrogramPerMilliliter); - AssertEx.EqualTolerance(1, quantity25.MicrogramsPerMilliliter, MicrogramsPerMilliliterTolerance); + Assert.Equal(1, quantity25.MicrogramsPerMilliliter); Assert.Equal(MassConcentrationUnit.MicrogramPerMilliliter, quantity25.Unit); var quantity26 = MassConcentration.From(1, MassConcentrationUnit.MilligramPerCubicMeter); - AssertEx.EqualTolerance(1, quantity26.MilligramsPerCubicMeter, MilligramsPerCubicMeterTolerance); + Assert.Equal(1, quantity26.MilligramsPerCubicMeter); Assert.Equal(MassConcentrationUnit.MilligramPerCubicMeter, quantity26.Unit); var quantity27 = MassConcentration.From(1, MassConcentrationUnit.MilligramPerDeciliter); - AssertEx.EqualTolerance(1, quantity27.MilligramsPerDeciliter, MilligramsPerDeciliterTolerance); + Assert.Equal(1, quantity27.MilligramsPerDeciliter); Assert.Equal(MassConcentrationUnit.MilligramPerDeciliter, quantity27.Unit); var quantity28 = MassConcentration.From(1, MassConcentrationUnit.MilligramPerLiter); - AssertEx.EqualTolerance(1, quantity28.MilligramsPerLiter, MilligramsPerLiterTolerance); + Assert.Equal(1, quantity28.MilligramsPerLiter); Assert.Equal(MassConcentrationUnit.MilligramPerLiter, quantity28.Unit); var quantity29 = MassConcentration.From(1, MassConcentrationUnit.MilligramPerMicroliter); - AssertEx.EqualTolerance(1, quantity29.MilligramsPerMicroliter, MilligramsPerMicroliterTolerance); + Assert.Equal(1, quantity29.MilligramsPerMicroliter); Assert.Equal(MassConcentrationUnit.MilligramPerMicroliter, quantity29.Unit); var quantity30 = MassConcentration.From(1, MassConcentrationUnit.MilligramPerMilliliter); - AssertEx.EqualTolerance(1, quantity30.MilligramsPerMilliliter, MilligramsPerMilliliterTolerance); + Assert.Equal(1, quantity30.MilligramsPerMilliliter); Assert.Equal(MassConcentrationUnit.MilligramPerMilliliter, quantity30.Unit); var quantity31 = MassConcentration.From(1, MassConcentrationUnit.NanogramPerDeciliter); - AssertEx.EqualTolerance(1, quantity31.NanogramsPerDeciliter, NanogramsPerDeciliterTolerance); + Assert.Equal(1, quantity31.NanogramsPerDeciliter); Assert.Equal(MassConcentrationUnit.NanogramPerDeciliter, quantity31.Unit); var quantity32 = MassConcentration.From(1, MassConcentrationUnit.NanogramPerLiter); - AssertEx.EqualTolerance(1, quantity32.NanogramsPerLiter, NanogramsPerLiterTolerance); + Assert.Equal(1, quantity32.NanogramsPerLiter); Assert.Equal(MassConcentrationUnit.NanogramPerLiter, quantity32.Unit); var quantity33 = MassConcentration.From(1, MassConcentrationUnit.NanogramPerMicroliter); - AssertEx.EqualTolerance(1, quantity33.NanogramsPerMicroliter, NanogramsPerMicroliterTolerance); + Assert.Equal(1, quantity33.NanogramsPerMicroliter); Assert.Equal(MassConcentrationUnit.NanogramPerMicroliter, quantity33.Unit); var quantity34 = MassConcentration.From(1, MassConcentrationUnit.NanogramPerMilliliter); - AssertEx.EqualTolerance(1, quantity34.NanogramsPerMilliliter, NanogramsPerMilliliterTolerance); + Assert.Equal(1, quantity34.NanogramsPerMilliliter); Assert.Equal(MassConcentrationUnit.NanogramPerMilliliter, quantity34.Unit); var quantity35 = MassConcentration.From(1, MassConcentrationUnit.OuncePerImperialGallon); - AssertEx.EqualTolerance(1, quantity35.OuncesPerImperialGallon, OuncesPerImperialGallonTolerance); + Assert.Equal(1, quantity35.OuncesPerImperialGallon); Assert.Equal(MassConcentrationUnit.OuncePerImperialGallon, quantity35.Unit); var quantity36 = MassConcentration.From(1, MassConcentrationUnit.OuncePerUSGallon); - AssertEx.EqualTolerance(1, quantity36.OuncesPerUSGallon, OuncesPerUSGallonTolerance); + Assert.Equal(1, quantity36.OuncesPerUSGallon); Assert.Equal(MassConcentrationUnit.OuncePerUSGallon, quantity36.Unit); var quantity37 = MassConcentration.From(1, MassConcentrationUnit.PicogramPerDeciliter); - AssertEx.EqualTolerance(1, quantity37.PicogramsPerDeciliter, PicogramsPerDeciliterTolerance); + Assert.Equal(1, quantity37.PicogramsPerDeciliter); Assert.Equal(MassConcentrationUnit.PicogramPerDeciliter, quantity37.Unit); var quantity38 = MassConcentration.From(1, MassConcentrationUnit.PicogramPerLiter); - AssertEx.EqualTolerance(1, quantity38.PicogramsPerLiter, PicogramsPerLiterTolerance); + Assert.Equal(1, quantity38.PicogramsPerLiter); Assert.Equal(MassConcentrationUnit.PicogramPerLiter, quantity38.Unit); var quantity39 = MassConcentration.From(1, MassConcentrationUnit.PicogramPerMicroliter); - AssertEx.EqualTolerance(1, quantity39.PicogramsPerMicroliter, PicogramsPerMicroliterTolerance); + Assert.Equal(1, quantity39.PicogramsPerMicroliter); Assert.Equal(MassConcentrationUnit.PicogramPerMicroliter, quantity39.Unit); var quantity40 = MassConcentration.From(1, MassConcentrationUnit.PicogramPerMilliliter); - AssertEx.EqualTolerance(1, quantity40.PicogramsPerMilliliter, PicogramsPerMilliliterTolerance); + Assert.Equal(1, quantity40.PicogramsPerMilliliter); Assert.Equal(MassConcentrationUnit.PicogramPerMilliliter, quantity40.Unit); var quantity41 = MassConcentration.From(1, MassConcentrationUnit.PoundPerCubicFoot); - AssertEx.EqualTolerance(1, quantity41.PoundsPerCubicFoot, PoundsPerCubicFootTolerance); + Assert.Equal(1, quantity41.PoundsPerCubicFoot); Assert.Equal(MassConcentrationUnit.PoundPerCubicFoot, quantity41.Unit); var quantity42 = MassConcentration.From(1, MassConcentrationUnit.PoundPerCubicInch); - AssertEx.EqualTolerance(1, quantity42.PoundsPerCubicInch, PoundsPerCubicInchTolerance); + Assert.Equal(1, quantity42.PoundsPerCubicInch); Assert.Equal(MassConcentrationUnit.PoundPerCubicInch, quantity42.Unit); var quantity43 = MassConcentration.From(1, MassConcentrationUnit.PoundPerImperialGallon); - AssertEx.EqualTolerance(1, quantity43.PoundsPerImperialGallon, PoundsPerImperialGallonTolerance); + Assert.Equal(1, quantity43.PoundsPerImperialGallon); Assert.Equal(MassConcentrationUnit.PoundPerImperialGallon, quantity43.Unit); var quantity44 = MassConcentration.From(1, MassConcentrationUnit.PoundPerUSGallon); - AssertEx.EqualTolerance(1, quantity44.PoundsPerUSGallon, PoundsPerUSGallonTolerance); + Assert.Equal(1, quantity44.PoundsPerUSGallon); Assert.Equal(MassConcentrationUnit.PoundPerUSGallon, quantity44.Unit); var quantity45 = MassConcentration.From(1, MassConcentrationUnit.SlugPerCubicFoot); - AssertEx.EqualTolerance(1, quantity45.SlugsPerCubicFoot, SlugsPerCubicFootTolerance); + Assert.Equal(1, quantity45.SlugsPerCubicFoot); Assert.Equal(MassConcentrationUnit.SlugPerCubicFoot, quantity45.Unit); var quantity46 = MassConcentration.From(1, MassConcentrationUnit.TonnePerCubicCentimeter); - AssertEx.EqualTolerance(1, quantity46.TonnesPerCubicCentimeter, TonnesPerCubicCentimeterTolerance); + Assert.Equal(1, quantity46.TonnesPerCubicCentimeter); Assert.Equal(MassConcentrationUnit.TonnePerCubicCentimeter, quantity46.Unit); var quantity47 = MassConcentration.From(1, MassConcentrationUnit.TonnePerCubicMeter); - AssertEx.EqualTolerance(1, quantity47.TonnesPerCubicMeter, TonnesPerCubicMeterTolerance); + Assert.Equal(1, quantity47.TonnesPerCubicMeter); Assert.Equal(MassConcentrationUnit.TonnePerCubicMeter, quantity47.Unit); var quantity48 = MassConcentration.From(1, MassConcentrationUnit.TonnePerCubicMillimeter); - AssertEx.EqualTolerance(1, quantity48.TonnesPerCubicMillimeter, TonnesPerCubicMillimeterTolerance); + Assert.Equal(1, quantity48.TonnesPerCubicMillimeter); Assert.Equal(MassConcentrationUnit.TonnePerCubicMillimeter, quantity48.Unit); } @@ -747,703 +765,128 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 cg/dl", MassConcentrationUnit.CentigramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 cg/l", MassConcentrationUnit.CentigramPerLiter, 4.2)] + [InlineData("en-US", "4.2 cg/μl", MassConcentrationUnit.CentigramPerMicroliter, 4.2)] + [InlineData("en-US", "4.2 cg/ml", MassConcentrationUnit.CentigramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 dg/dl", MassConcentrationUnit.DecigramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 dg/l", MassConcentrationUnit.DecigramPerLiter, 4.2)] + [InlineData("en-US", "4.2 dg/μl", MassConcentrationUnit.DecigramPerMicroliter, 4.2)] + [InlineData("en-US", "4.2 dg/ml", MassConcentrationUnit.DecigramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 g/cm³", MassConcentrationUnit.GramPerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 g/m³", MassConcentrationUnit.GramPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 g/mm³", MassConcentrationUnit.GramPerCubicMillimeter, 4.2)] + [InlineData("en-US", "4.2 g/dl", MassConcentrationUnit.GramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 g/l", MassConcentrationUnit.GramPerLiter, 4.2)] + [InlineData("en-US", "4.2 g/μl", MassConcentrationUnit.GramPerMicroliter, 4.2)] + [InlineData("en-US", "4.2 g/ml", MassConcentrationUnit.GramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 kg/cm³", MassConcentrationUnit.KilogramPerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 kg/m³", MassConcentrationUnit.KilogramPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 kg/mm³", MassConcentrationUnit.KilogramPerCubicMillimeter, 4.2)] + [InlineData("en-US", "4.2 kg/l", MassConcentrationUnit.KilogramPerLiter, 4.2)] + [InlineData("en-US", "4.2 kip/ft³", MassConcentrationUnit.KilopoundPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 kip/in³", MassConcentrationUnit.KilopoundPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 µg/m³", MassConcentrationUnit.MicrogramPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 µg/dl", MassConcentrationUnit.MicrogramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 µg/l", MassConcentrationUnit.MicrogramPerLiter, 4.2)] + [InlineData("en-US", "4.2 µg/μl", MassConcentrationUnit.MicrogramPerMicroliter, 4.2)] + [InlineData("en-US", "4.2 µg/ml", MassConcentrationUnit.MicrogramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 mg/m³", MassConcentrationUnit.MilligramPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 mg/dl", MassConcentrationUnit.MilligramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 mg/l", MassConcentrationUnit.MilligramPerLiter, 4.2)] + [InlineData("en-US", "4.2 mg/μl", MassConcentrationUnit.MilligramPerMicroliter, 4.2)] + [InlineData("en-US", "4.2 mg/ml", MassConcentrationUnit.MilligramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 ng/dl", MassConcentrationUnit.NanogramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 ng/l", MassConcentrationUnit.NanogramPerLiter, 4.2)] + [InlineData("en-US", "4.2 ng/μl", MassConcentrationUnit.NanogramPerMicroliter, 4.2)] + [InlineData("en-US", "4.2 ng/ml", MassConcentrationUnit.NanogramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 oz/gal (imp.)", MassConcentrationUnit.OuncePerImperialGallon, 4.2)] + [InlineData("en-US", "4.2 oz/gal (U.S.)", MassConcentrationUnit.OuncePerUSGallon, 4.2)] + [InlineData("en-US", "4.2 pg/dl", MassConcentrationUnit.PicogramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 pg/l", MassConcentrationUnit.PicogramPerLiter, 4.2)] + [InlineData("en-US", "4.2 pg/μl", MassConcentrationUnit.PicogramPerMicroliter, 4.2)] + [InlineData("en-US", "4.2 pg/ml", MassConcentrationUnit.PicogramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 lb/ft³", MassConcentrationUnit.PoundPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 lb/in³", MassConcentrationUnit.PoundPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 ppg (imp.)", MassConcentrationUnit.PoundPerImperialGallon, 4.2)] + [InlineData("en-US", "4.2 ppg (U.S.)", MassConcentrationUnit.PoundPerUSGallon, 4.2)] + [InlineData("en-US", "4.2 slug/ft³", MassConcentrationUnit.SlugPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 t/cm³", MassConcentrationUnit.TonnePerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 t/m³", MassConcentrationUnit.TonnePerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 t/mm³", MassConcentrationUnit.TonnePerCubicMillimeter, 4.2)] + [InlineData("ru-RU", "4,2 г/м³", MassConcentrationUnit.GramPerCubicMeter, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = MassConcentration.Parse("1 cg/dl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentigramsPerDeciliter, CentigramsPerDeciliterTolerance); - Assert.Equal(MassConcentrationUnit.CentigramPerDeciliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 cg/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentigramsPerLiter, CentigramsPerLiterTolerance); - Assert.Equal(MassConcentrationUnit.CentigramPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 cg/μl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentigramsPerMicroliter, CentigramsPerMicroliterTolerance); - Assert.Equal(MassConcentrationUnit.CentigramPerMicroliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 cg/ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentigramsPerMilliliter, CentigramsPerMilliliterTolerance); - Assert.Equal(MassConcentrationUnit.CentigramPerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 dg/dl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecigramsPerDeciliter, DecigramsPerDeciliterTolerance); - Assert.Equal(MassConcentrationUnit.DecigramPerDeciliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 dg/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecigramsPerLiter, DecigramsPerLiterTolerance); - Assert.Equal(MassConcentrationUnit.DecigramPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 dg/μl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecigramsPerMicroliter, DecigramsPerMicroliterTolerance); - Assert.Equal(MassConcentrationUnit.DecigramPerMicroliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 dg/ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecigramsPerMilliliter, DecigramsPerMilliliterTolerance); - Assert.Equal(MassConcentrationUnit.DecigramPerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 g/cm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerCubicCentimeter, GramsPerCubicCentimeterTolerance); - Assert.Equal(MassConcentrationUnit.GramPerCubicCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 g/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerCubicMeter, GramsPerCubicMeterTolerance); - Assert.Equal(MassConcentrationUnit.GramPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 г/м³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.GramsPerCubicMeter, GramsPerCubicMeterTolerance); - Assert.Equal(MassConcentrationUnit.GramPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 g/mm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerCubicMillimeter, GramsPerCubicMillimeterTolerance); - Assert.Equal(MassConcentrationUnit.GramPerCubicMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 g/dl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerDeciliter, GramsPerDeciliterTolerance); - Assert.Equal(MassConcentrationUnit.GramPerDeciliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 g/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerLiter, GramsPerLiterTolerance); - Assert.Equal(MassConcentrationUnit.GramPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 g/μl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerMicroliter, GramsPerMicroliterTolerance); - Assert.Equal(MassConcentrationUnit.GramPerMicroliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 g/ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerMilliliter, GramsPerMilliliterTolerance); - Assert.Equal(MassConcentrationUnit.GramPerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 kg/cm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerCubicCentimeter, KilogramsPerCubicCentimeterTolerance); - Assert.Equal(MassConcentrationUnit.KilogramPerCubicCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 kg/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - Assert.Equal(MassConcentrationUnit.KilogramPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 кг/м³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - Assert.Equal(MassConcentrationUnit.KilogramPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 kg/mm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerCubicMillimeter, KilogramsPerCubicMillimeterTolerance); - Assert.Equal(MassConcentrationUnit.KilogramPerCubicMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 kg/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerLiter, KilogramsPerLiterTolerance); - Assert.Equal(MassConcentrationUnit.KilogramPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 kip/ft³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsPerCubicFoot, KilopoundsPerCubicFootTolerance); - Assert.Equal(MassConcentrationUnit.KilopoundPerCubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 kip/in³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsPerCubicInch, KilopoundsPerCubicInchTolerance); - Assert.Equal(MassConcentrationUnit.KilopoundPerCubicInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 µg/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerCubicMeter, MicrogramsPerCubicMeterTolerance); - Assert.Equal(MassConcentrationUnit.MicrogramPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 мкг/м³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerCubicMeter, MicrogramsPerCubicMeterTolerance); - Assert.Equal(MassConcentrationUnit.MicrogramPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 µg/dl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerDeciliter, MicrogramsPerDeciliterTolerance); - Assert.Equal(MassConcentrationUnit.MicrogramPerDeciliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 µg/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerLiter, MicrogramsPerLiterTolerance); - Assert.Equal(MassConcentrationUnit.MicrogramPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 µg/μl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerMicroliter, MicrogramsPerMicroliterTolerance); - Assert.Equal(MassConcentrationUnit.MicrogramPerMicroliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 µg/ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerMilliliter, MicrogramsPerMilliliterTolerance); - Assert.Equal(MassConcentrationUnit.MicrogramPerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 mg/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligramsPerCubicMeter, MilligramsPerCubicMeterTolerance); - Assert.Equal(MassConcentrationUnit.MilligramPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 мг/м³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MilligramsPerCubicMeter, MilligramsPerCubicMeterTolerance); - Assert.Equal(MassConcentrationUnit.MilligramPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 mg/dl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligramsPerDeciliter, MilligramsPerDeciliterTolerance); - Assert.Equal(MassConcentrationUnit.MilligramPerDeciliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 mg/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligramsPerLiter, MilligramsPerLiterTolerance); - Assert.Equal(MassConcentrationUnit.MilligramPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 mg/μl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligramsPerMicroliter, MilligramsPerMicroliterTolerance); - Assert.Equal(MassConcentrationUnit.MilligramPerMicroliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 mg/ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligramsPerMilliliter, MilligramsPerMilliliterTolerance); - Assert.Equal(MassConcentrationUnit.MilligramPerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 ng/dl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanogramsPerDeciliter, NanogramsPerDeciliterTolerance); - Assert.Equal(MassConcentrationUnit.NanogramPerDeciliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 ng/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanogramsPerLiter, NanogramsPerLiterTolerance); - Assert.Equal(MassConcentrationUnit.NanogramPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 ng/μl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanogramsPerMicroliter, NanogramsPerMicroliterTolerance); - Assert.Equal(MassConcentrationUnit.NanogramPerMicroliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 ng/ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanogramsPerMilliliter, NanogramsPerMilliliterTolerance); - Assert.Equal(MassConcentrationUnit.NanogramPerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 oz/gal (imp.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.OuncesPerImperialGallon, OuncesPerImperialGallonTolerance); - Assert.Equal(MassConcentrationUnit.OuncePerImperialGallon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 oz/gal (U.S.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.OuncesPerUSGallon, OuncesPerUSGallonTolerance); - Assert.Equal(MassConcentrationUnit.OuncePerUSGallon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 pg/dl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PicogramsPerDeciliter, PicogramsPerDeciliterTolerance); - Assert.Equal(MassConcentrationUnit.PicogramPerDeciliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 pg/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PicogramsPerLiter, PicogramsPerLiterTolerance); - Assert.Equal(MassConcentrationUnit.PicogramPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 pg/μl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PicogramsPerMicroliter, PicogramsPerMicroliterTolerance); - Assert.Equal(MassConcentrationUnit.PicogramPerMicroliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 pg/ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PicogramsPerMilliliter, PicogramsPerMilliliterTolerance); - Assert.Equal(MassConcentrationUnit.PicogramPerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 lb/ft³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicFoot, PoundsPerCubicFootTolerance); - Assert.Equal(MassConcentrationUnit.PoundPerCubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 lb/in³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicInch, PoundsPerCubicInchTolerance); - Assert.Equal(MassConcentrationUnit.PoundPerCubicInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 ppg (imp.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerImperialGallon, PoundsPerImperialGallonTolerance); - Assert.Equal(MassConcentrationUnit.PoundPerImperialGallon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 ppg (U.S.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerUSGallon, PoundsPerUSGallonTolerance); - Assert.Equal(MassConcentrationUnit.PoundPerUSGallon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 slug/ft³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SlugsPerCubicFoot, SlugsPerCubicFootTolerance); - Assert.Equal(MassConcentrationUnit.SlugPerCubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 t/cm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonnesPerCubicCentimeter, TonnesPerCubicCentimeterTolerance); - Assert.Equal(MassConcentrationUnit.TonnePerCubicCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 t/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonnesPerCubicMeter, TonnesPerCubicMeterTolerance); - Assert.Equal(MassConcentrationUnit.TonnePerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassConcentration.Parse("1 t/mm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonnesPerCubicMillimeter, TonnesPerCubicMillimeterTolerance); - Assert.Equal(MassConcentrationUnit.TonnePerCubicMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = MassConcentration.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 cg/dl", MassConcentrationUnit.CentigramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 cg/l", MassConcentrationUnit.CentigramPerLiter, 4.2)] + [InlineData("en-US", "4.2 cg/μl", MassConcentrationUnit.CentigramPerMicroliter, 4.2)] + [InlineData("en-US", "4.2 cg/ml", MassConcentrationUnit.CentigramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 dg/dl", MassConcentrationUnit.DecigramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 dg/l", MassConcentrationUnit.DecigramPerLiter, 4.2)] + [InlineData("en-US", "4.2 dg/μl", MassConcentrationUnit.DecigramPerMicroliter, 4.2)] + [InlineData("en-US", "4.2 dg/ml", MassConcentrationUnit.DecigramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 g/cm³", MassConcentrationUnit.GramPerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 g/m³", MassConcentrationUnit.GramPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 g/mm³", MassConcentrationUnit.GramPerCubicMillimeter, 4.2)] + [InlineData("en-US", "4.2 g/dl", MassConcentrationUnit.GramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 g/l", MassConcentrationUnit.GramPerLiter, 4.2)] + [InlineData("en-US", "4.2 g/μl", MassConcentrationUnit.GramPerMicroliter, 4.2)] + [InlineData("en-US", "4.2 g/ml", MassConcentrationUnit.GramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 kg/cm³", MassConcentrationUnit.KilogramPerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 kg/m³", MassConcentrationUnit.KilogramPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 kg/mm³", MassConcentrationUnit.KilogramPerCubicMillimeter, 4.2)] + [InlineData("en-US", "4.2 kg/l", MassConcentrationUnit.KilogramPerLiter, 4.2)] + [InlineData("en-US", "4.2 kip/ft³", MassConcentrationUnit.KilopoundPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 kip/in³", MassConcentrationUnit.KilopoundPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 µg/m³", MassConcentrationUnit.MicrogramPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 µg/dl", MassConcentrationUnit.MicrogramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 µg/l", MassConcentrationUnit.MicrogramPerLiter, 4.2)] + [InlineData("en-US", "4.2 µg/μl", MassConcentrationUnit.MicrogramPerMicroliter, 4.2)] + [InlineData("en-US", "4.2 µg/ml", MassConcentrationUnit.MicrogramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 mg/m³", MassConcentrationUnit.MilligramPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 mg/dl", MassConcentrationUnit.MilligramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 mg/l", MassConcentrationUnit.MilligramPerLiter, 4.2)] + [InlineData("en-US", "4.2 mg/μl", MassConcentrationUnit.MilligramPerMicroliter, 4.2)] + [InlineData("en-US", "4.2 mg/ml", MassConcentrationUnit.MilligramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 ng/dl", MassConcentrationUnit.NanogramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 ng/l", MassConcentrationUnit.NanogramPerLiter, 4.2)] + [InlineData("en-US", "4.2 ng/μl", MassConcentrationUnit.NanogramPerMicroliter, 4.2)] + [InlineData("en-US", "4.2 ng/ml", MassConcentrationUnit.NanogramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 oz/gal (imp.)", MassConcentrationUnit.OuncePerImperialGallon, 4.2)] + [InlineData("en-US", "4.2 oz/gal (U.S.)", MassConcentrationUnit.OuncePerUSGallon, 4.2)] + [InlineData("en-US", "4.2 pg/dl", MassConcentrationUnit.PicogramPerDeciliter, 4.2)] + [InlineData("en-US", "4.2 pg/l", MassConcentrationUnit.PicogramPerLiter, 4.2)] + [InlineData("en-US", "4.2 pg/μl", MassConcentrationUnit.PicogramPerMicroliter, 4.2)] + [InlineData("en-US", "4.2 pg/ml", MassConcentrationUnit.PicogramPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 lb/ft³", MassConcentrationUnit.PoundPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 lb/in³", MassConcentrationUnit.PoundPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 ppg (imp.)", MassConcentrationUnit.PoundPerImperialGallon, 4.2)] + [InlineData("en-US", "4.2 ppg (U.S.)", MassConcentrationUnit.PoundPerUSGallon, 4.2)] + [InlineData("en-US", "4.2 slug/ft³", MassConcentrationUnit.SlugPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 t/cm³", MassConcentrationUnit.TonnePerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 t/m³", MassConcentrationUnit.TonnePerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 t/mm³", MassConcentrationUnit.TonnePerCubicMillimeter, 4.2)] + [InlineData("ru-RU", "4,2 г/м³", MassConcentrationUnit.GramPerCubicMeter, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(MassConcentration.TryParse("1 cg/dl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentigramsPerDeciliter, CentigramsPerDeciliterTolerance); - Assert.Equal(MassConcentrationUnit.CentigramPerDeciliter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 cg/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentigramsPerLiter, CentigramsPerLiterTolerance); - Assert.Equal(MassConcentrationUnit.CentigramPerLiter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 cg/μl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentigramsPerMicroliter, CentigramsPerMicroliterTolerance); - Assert.Equal(MassConcentrationUnit.CentigramPerMicroliter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 cg/ml", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentigramsPerMilliliter, CentigramsPerMilliliterTolerance); - Assert.Equal(MassConcentrationUnit.CentigramPerMilliliter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 dg/dl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecigramsPerDeciliter, DecigramsPerDeciliterTolerance); - Assert.Equal(MassConcentrationUnit.DecigramPerDeciliter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 dg/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecigramsPerLiter, DecigramsPerLiterTolerance); - Assert.Equal(MassConcentrationUnit.DecigramPerLiter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 dg/μl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecigramsPerMicroliter, DecigramsPerMicroliterTolerance); - Assert.Equal(MassConcentrationUnit.DecigramPerMicroliter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 dg/ml", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecigramsPerMilliliter, DecigramsPerMilliliterTolerance); - Assert.Equal(MassConcentrationUnit.DecigramPerMilliliter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 g/cm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerCubicCentimeter, GramsPerCubicCentimeterTolerance); - Assert.Equal(MassConcentrationUnit.GramPerCubicCentimeter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 g/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerCubicMeter, GramsPerCubicMeterTolerance); - Assert.Equal(MassConcentrationUnit.GramPerCubicMeter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 г/м³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerCubicMeter, GramsPerCubicMeterTolerance); - Assert.Equal(MassConcentrationUnit.GramPerCubicMeter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 g/mm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerCubicMillimeter, GramsPerCubicMillimeterTolerance); - Assert.Equal(MassConcentrationUnit.GramPerCubicMillimeter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 g/dl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerDeciliter, GramsPerDeciliterTolerance); - Assert.Equal(MassConcentrationUnit.GramPerDeciliter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 g/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerLiter, GramsPerLiterTolerance); - Assert.Equal(MassConcentrationUnit.GramPerLiter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 g/μl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerMicroliter, GramsPerMicroliterTolerance); - Assert.Equal(MassConcentrationUnit.GramPerMicroliter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 g/ml", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerMilliliter, GramsPerMilliliterTolerance); - Assert.Equal(MassConcentrationUnit.GramPerMilliliter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 kg/cm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerCubicCentimeter, KilogramsPerCubicCentimeterTolerance); - Assert.Equal(MassConcentrationUnit.KilogramPerCubicCentimeter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 kg/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - Assert.Equal(MassConcentrationUnit.KilogramPerCubicMeter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 кг/м³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - Assert.Equal(MassConcentrationUnit.KilogramPerCubicMeter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 kg/mm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerCubicMillimeter, KilogramsPerCubicMillimeterTolerance); - Assert.Equal(MassConcentrationUnit.KilogramPerCubicMillimeter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 kg/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerLiter, KilogramsPerLiterTolerance); - Assert.Equal(MassConcentrationUnit.KilogramPerLiter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 kip/ft³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsPerCubicFoot, KilopoundsPerCubicFootTolerance); - Assert.Equal(MassConcentrationUnit.KilopoundPerCubicFoot, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 kip/in³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsPerCubicInch, KilopoundsPerCubicInchTolerance); - Assert.Equal(MassConcentrationUnit.KilopoundPerCubicInch, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 µg/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerCubicMeter, MicrogramsPerCubicMeterTolerance); - Assert.Equal(MassConcentrationUnit.MicrogramPerCubicMeter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 мкг/м³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerCubicMeter, MicrogramsPerCubicMeterTolerance); - Assert.Equal(MassConcentrationUnit.MicrogramPerCubicMeter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 µg/dl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerDeciliter, MicrogramsPerDeciliterTolerance); - Assert.Equal(MassConcentrationUnit.MicrogramPerDeciliter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 µg/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerLiter, MicrogramsPerLiterTolerance); - Assert.Equal(MassConcentrationUnit.MicrogramPerLiter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 µg/μl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerMicroliter, MicrogramsPerMicroliterTolerance); - Assert.Equal(MassConcentrationUnit.MicrogramPerMicroliter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 µg/ml", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerMilliliter, MicrogramsPerMilliliterTolerance); - Assert.Equal(MassConcentrationUnit.MicrogramPerMilliliter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 mg/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligramsPerCubicMeter, MilligramsPerCubicMeterTolerance); - Assert.Equal(MassConcentrationUnit.MilligramPerCubicMeter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 мг/м³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligramsPerCubicMeter, MilligramsPerCubicMeterTolerance); - Assert.Equal(MassConcentrationUnit.MilligramPerCubicMeter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 mg/dl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligramsPerDeciliter, MilligramsPerDeciliterTolerance); - Assert.Equal(MassConcentrationUnit.MilligramPerDeciliter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 mg/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligramsPerLiter, MilligramsPerLiterTolerance); - Assert.Equal(MassConcentrationUnit.MilligramPerLiter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 mg/μl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligramsPerMicroliter, MilligramsPerMicroliterTolerance); - Assert.Equal(MassConcentrationUnit.MilligramPerMicroliter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 mg/ml", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligramsPerMilliliter, MilligramsPerMilliliterTolerance); - Assert.Equal(MassConcentrationUnit.MilligramPerMilliliter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 ng/dl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanogramsPerDeciliter, NanogramsPerDeciliterTolerance); - Assert.Equal(MassConcentrationUnit.NanogramPerDeciliter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 ng/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanogramsPerLiter, NanogramsPerLiterTolerance); - Assert.Equal(MassConcentrationUnit.NanogramPerLiter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 ng/μl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanogramsPerMicroliter, NanogramsPerMicroliterTolerance); - Assert.Equal(MassConcentrationUnit.NanogramPerMicroliter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 ng/ml", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanogramsPerMilliliter, NanogramsPerMilliliterTolerance); - Assert.Equal(MassConcentrationUnit.NanogramPerMilliliter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 oz/gal (imp.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.OuncesPerImperialGallon, OuncesPerImperialGallonTolerance); - Assert.Equal(MassConcentrationUnit.OuncePerImperialGallon, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 oz/gal (U.S.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.OuncesPerUSGallon, OuncesPerUSGallonTolerance); - Assert.Equal(MassConcentrationUnit.OuncePerUSGallon, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 pg/dl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PicogramsPerDeciliter, PicogramsPerDeciliterTolerance); - Assert.Equal(MassConcentrationUnit.PicogramPerDeciliter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 pg/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PicogramsPerLiter, PicogramsPerLiterTolerance); - Assert.Equal(MassConcentrationUnit.PicogramPerLiter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 pg/μl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PicogramsPerMicroliter, PicogramsPerMicroliterTolerance); - Assert.Equal(MassConcentrationUnit.PicogramPerMicroliter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 pg/ml", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PicogramsPerMilliliter, PicogramsPerMilliliterTolerance); - Assert.Equal(MassConcentrationUnit.PicogramPerMilliliter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 lb/ft³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicFoot, PoundsPerCubicFootTolerance); - Assert.Equal(MassConcentrationUnit.PoundPerCubicFoot, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 lb/in³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerCubicInch, PoundsPerCubicInchTolerance); - Assert.Equal(MassConcentrationUnit.PoundPerCubicInch, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 ppg (imp.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerImperialGallon, PoundsPerImperialGallonTolerance); - Assert.Equal(MassConcentrationUnit.PoundPerImperialGallon, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 ppg (U.S.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerUSGallon, PoundsPerUSGallonTolerance); - Assert.Equal(MassConcentrationUnit.PoundPerUSGallon, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 slug/ft³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SlugsPerCubicFoot, SlugsPerCubicFootTolerance); - Assert.Equal(MassConcentrationUnit.SlugPerCubicFoot, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 t/cm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonnesPerCubicCentimeter, TonnesPerCubicCentimeterTolerance); - Assert.Equal(MassConcentrationUnit.TonnePerCubicCentimeter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 t/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonnesPerCubicMeter, TonnesPerCubicMeterTolerance); - Assert.Equal(MassConcentrationUnit.TonnePerCubicMeter, parsed.Unit); - } - - { - Assert.True(MassConcentration.TryParse("1 t/mm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonnesPerCubicMillimeter, TonnesPerCubicMillimeterTolerance); - Assert.Equal(MassConcentrationUnit.TonnePerCubicMillimeter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(MassConcentration.TryParse(quantityString, out MassConcentration parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -1920,6 +1363,79 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, MassCo Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", MassConcentrationUnit.CentigramPerDeciliter, "cg/dl")] + [InlineData("en-US", MassConcentrationUnit.CentigramPerLiter, "cg/l")] + [InlineData("en-US", MassConcentrationUnit.CentigramPerMicroliter, "cg/μl")] + [InlineData("en-US", MassConcentrationUnit.CentigramPerMilliliter, "cg/ml")] + [InlineData("en-US", MassConcentrationUnit.DecigramPerDeciliter, "dg/dl")] + [InlineData("en-US", MassConcentrationUnit.DecigramPerLiter, "dg/l")] + [InlineData("en-US", MassConcentrationUnit.DecigramPerMicroliter, "dg/μl")] + [InlineData("en-US", MassConcentrationUnit.DecigramPerMilliliter, "dg/ml")] + [InlineData("en-US", MassConcentrationUnit.GramPerCubicCentimeter, "g/cm³")] + [InlineData("en-US", MassConcentrationUnit.GramPerCubicMeter, "g/m³")] + [InlineData("en-US", MassConcentrationUnit.GramPerCubicMillimeter, "g/mm³")] + [InlineData("en-US", MassConcentrationUnit.GramPerDeciliter, "g/dl")] + [InlineData("en-US", MassConcentrationUnit.GramPerLiter, "g/l")] + [InlineData("en-US", MassConcentrationUnit.GramPerMicroliter, "g/μl")] + [InlineData("en-US", MassConcentrationUnit.GramPerMilliliter, "g/ml")] + [InlineData("en-US", MassConcentrationUnit.KilogramPerCubicCentimeter, "kg/cm³")] + [InlineData("en-US", MassConcentrationUnit.KilogramPerCubicMeter, "kg/m³")] + [InlineData("en-US", MassConcentrationUnit.KilogramPerCubicMillimeter, "kg/mm³")] + [InlineData("en-US", MassConcentrationUnit.KilogramPerLiter, "kg/l")] + [InlineData("en-US", MassConcentrationUnit.KilopoundPerCubicFoot, "kip/ft³")] + [InlineData("en-US", MassConcentrationUnit.KilopoundPerCubicInch, "kip/in³")] + [InlineData("en-US", MassConcentrationUnit.MicrogramPerCubicMeter, "µg/m³")] + [InlineData("en-US", MassConcentrationUnit.MicrogramPerDeciliter, "µg/dl")] + [InlineData("en-US", MassConcentrationUnit.MicrogramPerLiter, "µg/l")] + [InlineData("en-US", MassConcentrationUnit.MicrogramPerMicroliter, "µg/μl")] + [InlineData("en-US", MassConcentrationUnit.MicrogramPerMilliliter, "µg/ml")] + [InlineData("en-US", MassConcentrationUnit.MilligramPerCubicMeter, "mg/m³")] + [InlineData("en-US", MassConcentrationUnit.MilligramPerDeciliter, "mg/dl")] + [InlineData("en-US", MassConcentrationUnit.MilligramPerLiter, "mg/l")] + [InlineData("en-US", MassConcentrationUnit.MilligramPerMicroliter, "mg/μl")] + [InlineData("en-US", MassConcentrationUnit.MilligramPerMilliliter, "mg/ml")] + [InlineData("en-US", MassConcentrationUnit.NanogramPerDeciliter, "ng/dl")] + [InlineData("en-US", MassConcentrationUnit.NanogramPerLiter, "ng/l")] + [InlineData("en-US", MassConcentrationUnit.NanogramPerMicroliter, "ng/μl")] + [InlineData("en-US", MassConcentrationUnit.NanogramPerMilliliter, "ng/ml")] + [InlineData("en-US", MassConcentrationUnit.OuncePerImperialGallon, "oz/gal (imp.)")] + [InlineData("en-US", MassConcentrationUnit.OuncePerUSGallon, "oz/gal (U.S.)")] + [InlineData("en-US", MassConcentrationUnit.PicogramPerDeciliter, "pg/dl")] + [InlineData("en-US", MassConcentrationUnit.PicogramPerLiter, "pg/l")] + [InlineData("en-US", MassConcentrationUnit.PicogramPerMicroliter, "pg/μl")] + [InlineData("en-US", MassConcentrationUnit.PicogramPerMilliliter, "pg/ml")] + [InlineData("en-US", MassConcentrationUnit.PoundPerCubicFoot, "lb/ft³")] + [InlineData("en-US", MassConcentrationUnit.PoundPerCubicInch, "lb/in³")] + [InlineData("en-US", MassConcentrationUnit.PoundPerImperialGallon, "ppg (imp.)")] + [InlineData("en-US", MassConcentrationUnit.PoundPerUSGallon, "ppg (U.S.)")] + [InlineData("en-US", MassConcentrationUnit.SlugPerCubicFoot, "slug/ft³")] + [InlineData("en-US", MassConcentrationUnit.TonnePerCubicCentimeter, "t/cm³")] + [InlineData("en-US", MassConcentrationUnit.TonnePerCubicMeter, "t/m³")] + [InlineData("en-US", MassConcentrationUnit.TonnePerCubicMillimeter, "t/mm³")] + [InlineData("ru-RU", MassConcentrationUnit.GramPerCubicMeter, "г/м³")] + [InlineData("ru-RU", MassConcentrationUnit.KilogramPerCubicMeter, "кг/м³")] + [InlineData("ru-RU", MassConcentrationUnit.MicrogramPerCubicMeter, "мкг/м³")] + [InlineData("ru-RU", MassConcentrationUnit.MilligramPerCubicMeter, "мг/м³")] + public void GetAbbreviationForCulture(string culture, MassConcentrationUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = MassConcentration.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(MassConcentration.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = MassConcentration.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(MassConcentrationUnit unit) @@ -1950,6 +1466,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); }); } @@ -1973,80 +1490,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] @@ -2092,8 +1611,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); @@ -2130,23 +1647,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = MassConcentration.FromKilogramsPerCubicMeter(1); - Assert.True(v.Equals(MassConcentration.FromKilogramsPerCubicMeter(1), KilogramsPerCubicMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(MassConcentration.Zero, KilogramsPerCubicMeterTolerance, ComparisonType.Relative)); - Assert.True(MassConcentration.FromKilogramsPerCubicMeter(100).Equals(MassConcentration.FromKilogramsPerCubicMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(MassConcentration.FromKilogramsPerCubicMeter(100).Equals(MassConcentration.FromKilogramsPerCubicMeter(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = MassConcentration.FromKilogramsPerCubicMeter(1); - Assert.Throws(() => v.Equals(MassConcentration.FromKilogramsPerCubicMeter(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -2161,6 +1661,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(kilogrampercubicmeter.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = MassConcentration.FromKilogramsPerCubicMeter(1); + var negativeTolerance = MassConcentration.FromKilogramsPerCubicMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -2177,6 +1703,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() { @@ -2331,158 +1869,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(MassConcentration))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MassConcentrationUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal(MassConcentration.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal(MassConcentration.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal(new {MassConcentration.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 76c0556516..d5d504dc78 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassFlowTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassFlowTestsBase.g.cs @@ -224,7 +224,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new MassFlow(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -237,15 +237,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void MassFlow_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + MassFlowUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new MassFlow(1, MassFlowUnit.GramPerSecond); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(MassFlow.Zero, quantityInfo.Zero); Assert.Equal("MassFlow", quantityInfo.Name); + Assert.Equal(MassFlow.Zero, quantityInfo.Zero); + Assert.Equal(MassFlow.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(MassFlow.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void MassFlowInfo_CreateWithCustomUnitInfos() + { + MassFlowUnit[] expectedUnits = [MassFlowUnit.GramPerSecond]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -291,135 +309,135 @@ public void GramPerSecondToMassFlowUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = MassFlow.From(1, MassFlowUnit.CentigramPerDay); - AssertEx.EqualTolerance(1, quantity00.CentigramsPerDay, CentigramsPerDayTolerance); + Assert.Equal(1, quantity00.CentigramsPerDay); Assert.Equal(MassFlowUnit.CentigramPerDay, quantity00.Unit); var quantity01 = MassFlow.From(1, MassFlowUnit.CentigramPerSecond); - AssertEx.EqualTolerance(1, quantity01.CentigramsPerSecond, CentigramsPerSecondTolerance); + Assert.Equal(1, quantity01.CentigramsPerSecond); Assert.Equal(MassFlowUnit.CentigramPerSecond, quantity01.Unit); var quantity02 = MassFlow.From(1, MassFlowUnit.DecagramPerDay); - AssertEx.EqualTolerance(1, quantity02.DecagramsPerDay, DecagramsPerDayTolerance); + Assert.Equal(1, quantity02.DecagramsPerDay); Assert.Equal(MassFlowUnit.DecagramPerDay, quantity02.Unit); var quantity03 = MassFlow.From(1, MassFlowUnit.DecagramPerSecond); - AssertEx.EqualTolerance(1, quantity03.DecagramsPerSecond, DecagramsPerSecondTolerance); + Assert.Equal(1, quantity03.DecagramsPerSecond); Assert.Equal(MassFlowUnit.DecagramPerSecond, quantity03.Unit); var quantity04 = MassFlow.From(1, MassFlowUnit.DecigramPerDay); - AssertEx.EqualTolerance(1, quantity04.DecigramsPerDay, DecigramsPerDayTolerance); + Assert.Equal(1, quantity04.DecigramsPerDay); Assert.Equal(MassFlowUnit.DecigramPerDay, quantity04.Unit); var quantity05 = MassFlow.From(1, MassFlowUnit.DecigramPerSecond); - AssertEx.EqualTolerance(1, quantity05.DecigramsPerSecond, DecigramsPerSecondTolerance); + Assert.Equal(1, quantity05.DecigramsPerSecond); Assert.Equal(MassFlowUnit.DecigramPerSecond, quantity05.Unit); var quantity06 = MassFlow.From(1, MassFlowUnit.GramPerDay); - AssertEx.EqualTolerance(1, quantity06.GramsPerDay, GramsPerDayTolerance); + Assert.Equal(1, quantity06.GramsPerDay); Assert.Equal(MassFlowUnit.GramPerDay, quantity06.Unit); var quantity07 = MassFlow.From(1, MassFlowUnit.GramPerHour); - AssertEx.EqualTolerance(1, quantity07.GramsPerHour, GramsPerHourTolerance); + Assert.Equal(1, quantity07.GramsPerHour); Assert.Equal(MassFlowUnit.GramPerHour, quantity07.Unit); var quantity08 = MassFlow.From(1, MassFlowUnit.GramPerSecond); - AssertEx.EqualTolerance(1, quantity08.GramsPerSecond, GramsPerSecondTolerance); + Assert.Equal(1, quantity08.GramsPerSecond); Assert.Equal(MassFlowUnit.GramPerSecond, quantity08.Unit); var quantity09 = MassFlow.From(1, MassFlowUnit.HectogramPerDay); - AssertEx.EqualTolerance(1, quantity09.HectogramsPerDay, HectogramsPerDayTolerance); + Assert.Equal(1, quantity09.HectogramsPerDay); Assert.Equal(MassFlowUnit.HectogramPerDay, quantity09.Unit); var quantity10 = MassFlow.From(1, MassFlowUnit.HectogramPerSecond); - AssertEx.EqualTolerance(1, quantity10.HectogramsPerSecond, HectogramsPerSecondTolerance); + Assert.Equal(1, quantity10.HectogramsPerSecond); Assert.Equal(MassFlowUnit.HectogramPerSecond, quantity10.Unit); var quantity11 = MassFlow.From(1, MassFlowUnit.KilogramPerDay); - AssertEx.EqualTolerance(1, quantity11.KilogramsPerDay, KilogramsPerDayTolerance); + Assert.Equal(1, quantity11.KilogramsPerDay); Assert.Equal(MassFlowUnit.KilogramPerDay, quantity11.Unit); var quantity12 = MassFlow.From(1, MassFlowUnit.KilogramPerHour); - AssertEx.EqualTolerance(1, quantity12.KilogramsPerHour, KilogramsPerHourTolerance); + Assert.Equal(1, quantity12.KilogramsPerHour); Assert.Equal(MassFlowUnit.KilogramPerHour, quantity12.Unit); var quantity13 = MassFlow.From(1, MassFlowUnit.KilogramPerMinute); - AssertEx.EqualTolerance(1, quantity13.KilogramsPerMinute, KilogramsPerMinuteTolerance); + Assert.Equal(1, quantity13.KilogramsPerMinute); Assert.Equal(MassFlowUnit.KilogramPerMinute, quantity13.Unit); var quantity14 = MassFlow.From(1, MassFlowUnit.KilogramPerSecond); - AssertEx.EqualTolerance(1, quantity14.KilogramsPerSecond, KilogramsPerSecondTolerance); + Assert.Equal(1, quantity14.KilogramsPerSecond); Assert.Equal(MassFlowUnit.KilogramPerSecond, quantity14.Unit); var quantity15 = MassFlow.From(1, MassFlowUnit.MegagramPerDay); - AssertEx.EqualTolerance(1, quantity15.MegagramsPerDay, MegagramsPerDayTolerance); + Assert.Equal(1, quantity15.MegagramsPerDay); Assert.Equal(MassFlowUnit.MegagramPerDay, quantity15.Unit); var quantity16 = MassFlow.From(1, MassFlowUnit.MegapoundPerDay); - AssertEx.EqualTolerance(1, quantity16.MegapoundsPerDay, MegapoundsPerDayTolerance); + Assert.Equal(1, quantity16.MegapoundsPerDay); Assert.Equal(MassFlowUnit.MegapoundPerDay, quantity16.Unit); var quantity17 = MassFlow.From(1, MassFlowUnit.MegapoundPerHour); - AssertEx.EqualTolerance(1, quantity17.MegapoundsPerHour, MegapoundsPerHourTolerance); + Assert.Equal(1, quantity17.MegapoundsPerHour); Assert.Equal(MassFlowUnit.MegapoundPerHour, quantity17.Unit); var quantity18 = MassFlow.From(1, MassFlowUnit.MegapoundPerMinute); - AssertEx.EqualTolerance(1, quantity18.MegapoundsPerMinute, MegapoundsPerMinuteTolerance); + Assert.Equal(1, quantity18.MegapoundsPerMinute); Assert.Equal(MassFlowUnit.MegapoundPerMinute, quantity18.Unit); var quantity19 = MassFlow.From(1, MassFlowUnit.MegapoundPerSecond); - AssertEx.EqualTolerance(1, quantity19.MegapoundsPerSecond, MegapoundsPerSecondTolerance); + Assert.Equal(1, quantity19.MegapoundsPerSecond); Assert.Equal(MassFlowUnit.MegapoundPerSecond, quantity19.Unit); var quantity20 = MassFlow.From(1, MassFlowUnit.MicrogramPerDay); - AssertEx.EqualTolerance(1, quantity20.MicrogramsPerDay, MicrogramsPerDayTolerance); + Assert.Equal(1, quantity20.MicrogramsPerDay); Assert.Equal(MassFlowUnit.MicrogramPerDay, quantity20.Unit); var quantity21 = MassFlow.From(1, MassFlowUnit.MicrogramPerSecond); - AssertEx.EqualTolerance(1, quantity21.MicrogramsPerSecond, MicrogramsPerSecondTolerance); + Assert.Equal(1, quantity21.MicrogramsPerSecond); Assert.Equal(MassFlowUnit.MicrogramPerSecond, quantity21.Unit); var quantity22 = MassFlow.From(1, MassFlowUnit.MilligramPerDay); - AssertEx.EqualTolerance(1, quantity22.MilligramsPerDay, MilligramsPerDayTolerance); + Assert.Equal(1, quantity22.MilligramsPerDay); Assert.Equal(MassFlowUnit.MilligramPerDay, quantity22.Unit); var quantity23 = MassFlow.From(1, MassFlowUnit.MilligramPerSecond); - AssertEx.EqualTolerance(1, quantity23.MilligramsPerSecond, MilligramsPerSecondTolerance); + Assert.Equal(1, quantity23.MilligramsPerSecond); Assert.Equal(MassFlowUnit.MilligramPerSecond, quantity23.Unit); var quantity24 = MassFlow.From(1, MassFlowUnit.NanogramPerDay); - AssertEx.EqualTolerance(1, quantity24.NanogramsPerDay, NanogramsPerDayTolerance); + Assert.Equal(1, quantity24.NanogramsPerDay); Assert.Equal(MassFlowUnit.NanogramPerDay, quantity24.Unit); var quantity25 = MassFlow.From(1, MassFlowUnit.NanogramPerSecond); - AssertEx.EqualTolerance(1, quantity25.NanogramsPerSecond, NanogramsPerSecondTolerance); + Assert.Equal(1, quantity25.NanogramsPerSecond); Assert.Equal(MassFlowUnit.NanogramPerSecond, quantity25.Unit); var quantity26 = MassFlow.From(1, MassFlowUnit.PoundPerDay); - AssertEx.EqualTolerance(1, quantity26.PoundsPerDay, PoundsPerDayTolerance); + Assert.Equal(1, quantity26.PoundsPerDay); Assert.Equal(MassFlowUnit.PoundPerDay, quantity26.Unit); var quantity27 = MassFlow.From(1, MassFlowUnit.PoundPerHour); - AssertEx.EqualTolerance(1, quantity27.PoundsPerHour, PoundsPerHourTolerance); + Assert.Equal(1, quantity27.PoundsPerHour); Assert.Equal(MassFlowUnit.PoundPerHour, quantity27.Unit); var quantity28 = MassFlow.From(1, MassFlowUnit.PoundPerMinute); - AssertEx.EqualTolerance(1, quantity28.PoundsPerMinute, PoundsPerMinuteTolerance); + Assert.Equal(1, quantity28.PoundsPerMinute); Assert.Equal(MassFlowUnit.PoundPerMinute, quantity28.Unit); var quantity29 = MassFlow.From(1, MassFlowUnit.PoundPerSecond); - AssertEx.EqualTolerance(1, quantity29.PoundsPerSecond, PoundsPerSecondTolerance); + Assert.Equal(1, quantity29.PoundsPerSecond); Assert.Equal(MassFlowUnit.PoundPerSecond, quantity29.Unit); var quantity30 = MassFlow.From(1, MassFlowUnit.ShortTonPerHour); - AssertEx.EqualTolerance(1, quantity30.ShortTonsPerHour, ShortTonsPerHourTolerance); + Assert.Equal(1, quantity30.ShortTonsPerHour); Assert.Equal(MassFlowUnit.ShortTonPerHour, quantity30.Unit); var quantity31 = MassFlow.From(1, MassFlowUnit.TonnePerDay); - AssertEx.EqualTolerance(1, quantity31.TonnesPerDay, TonnesPerDayTolerance); + Assert.Equal(1, quantity31.TonnesPerDay); Assert.Equal(MassFlowUnit.TonnePerDay, quantity31.Unit); var quantity32 = MassFlow.From(1, MassFlowUnit.TonnePerHour); - AssertEx.EqualTolerance(1, quantity32.TonnesPerHour, TonnesPerHourTolerance); + Assert.Equal(1, quantity32.TonnesPerHour); Assert.Equal(MassFlowUnit.TonnePerHour, quantity32.Unit); } @@ -587,574 +605,110 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 cg/d", MassFlowUnit.CentigramPerDay, 4.2)] + [InlineData("en-US", "4.2 cg/s", MassFlowUnit.CentigramPerSecond, 4.2)] + [InlineData("en-US", "4.2 cg/S", MassFlowUnit.CentigramPerSecond, 4.2)] + [InlineData("en-US", "4.2 dag/d", MassFlowUnit.DecagramPerDay, 4.2)] + [InlineData("en-US", "4.2 dag/s", MassFlowUnit.DecagramPerSecond, 4.2)] + [InlineData("en-US", "4.2 dag/S", MassFlowUnit.DecagramPerSecond, 4.2)] + [InlineData("en-US", "4.2 dg/d", MassFlowUnit.DecigramPerDay, 4.2)] + [InlineData("en-US", "4.2 dg/s", MassFlowUnit.DecigramPerSecond, 4.2)] + [InlineData("en-US", "4.2 dg/S", MassFlowUnit.DecigramPerSecond, 4.2)] + [InlineData("en-US", "4.2 g/d", MassFlowUnit.GramPerDay, 4.2)] + [InlineData("en-US", "4.2 g/h", MassFlowUnit.GramPerHour, 4.2)] + [InlineData("en-US", "4.2 g/s", MassFlowUnit.GramPerSecond, 4.2)] + [InlineData("en-US", "4.2 g/S", MassFlowUnit.GramPerSecond, 4.2)] + [InlineData("en-US", "4.2 hg/d", MassFlowUnit.HectogramPerDay, 4.2)] + [InlineData("en-US", "4.2 hg/s", MassFlowUnit.HectogramPerSecond, 4.2)] + [InlineData("en-US", "4.2 hg/S", MassFlowUnit.HectogramPerSecond, 4.2)] + [InlineData("en-US", "4.2 kg/d", MassFlowUnit.KilogramPerDay, 4.2)] + [InlineData("en-US", "4.2 kg/h", MassFlowUnit.KilogramPerHour, 4.2)] + [InlineData("en-US", "4.2 kg/min", MassFlowUnit.KilogramPerMinute, 4.2)] + [InlineData("en-US", "4.2 kg/s", MassFlowUnit.KilogramPerSecond, 4.2)] + [InlineData("en-US", "4.2 kg/S", MassFlowUnit.KilogramPerSecond, 4.2)] + [InlineData("en-US", "4.2 Mg/d", MassFlowUnit.MegagramPerDay, 4.2)] + [InlineData("en-US", "4.2 Mlb/d", MassFlowUnit.MegapoundPerDay, 4.2)] + [InlineData("en-US", "4.2 Mlb/h", MassFlowUnit.MegapoundPerHour, 4.2)] + [InlineData("en-US", "4.2 Mlb/min", MassFlowUnit.MegapoundPerMinute, 4.2)] + [InlineData("en-US", "4.2 Mlb/s", MassFlowUnit.MegapoundPerSecond, 4.2)] + [InlineData("en-US", "4.2 µg/d", MassFlowUnit.MicrogramPerDay, 4.2)] + [InlineData("en-US", "4.2 µg/s", MassFlowUnit.MicrogramPerSecond, 4.2)] + [InlineData("en-US", "4.2 µg/S", MassFlowUnit.MicrogramPerSecond, 4.2)] + [InlineData("en-US", "4.2 mg/d", MassFlowUnit.MilligramPerDay, 4.2)] + [InlineData("en-US", "4.2 mg/s", MassFlowUnit.MilligramPerSecond, 4.2)] + [InlineData("en-US", "4.2 mg/S", MassFlowUnit.MilligramPerSecond, 4.2)] + [InlineData("en-US", "4.2 ng/d", MassFlowUnit.NanogramPerDay, 4.2)] + [InlineData("en-US", "4.2 ng/s", MassFlowUnit.NanogramPerSecond, 4.2)] + [InlineData("en-US", "4.2 ng/S", MassFlowUnit.NanogramPerSecond, 4.2)] + [InlineData("en-US", "4.2 lb/d", MassFlowUnit.PoundPerDay, 4.2)] + [InlineData("en-US", "4.2 lb/h", MassFlowUnit.PoundPerHour, 4.2)] + [InlineData("en-US", "4.2 lb/min", MassFlowUnit.PoundPerMinute, 4.2)] + [InlineData("en-US", "4.2 lb/s", MassFlowUnit.PoundPerSecond, 4.2)] + [InlineData("en-US", "4.2 short tn/h", MassFlowUnit.ShortTonPerHour, 4.2)] + [InlineData("en-US", "4.2 t/d", MassFlowUnit.TonnePerDay, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = MassFlow.Parse("1 cg/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentigramsPerDay, CentigramsPerDayTolerance); - Assert.Equal(MassFlowUnit.CentigramPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 cg/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentigramsPerSecond, CentigramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.CentigramPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 cg/S", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentigramsPerSecond, CentigramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.CentigramPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 dag/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecagramsPerDay, DecagramsPerDayTolerance); - Assert.Equal(MassFlowUnit.DecagramPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 dag/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecagramsPerSecond, DecagramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.DecagramPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 dag/S", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecagramsPerSecond, DecagramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.DecagramPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 dg/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecigramsPerDay, DecigramsPerDayTolerance); - Assert.Equal(MassFlowUnit.DecigramPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 dg/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecigramsPerSecond, DecigramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.DecigramPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 dg/S", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecigramsPerSecond, DecigramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.DecigramPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 g/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerDay, GramsPerDayTolerance); - Assert.Equal(MassFlowUnit.GramPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 g/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerHour, GramsPerHourTolerance); - Assert.Equal(MassFlowUnit.GramPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 g/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerSecond, GramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.GramPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 g/S", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerSecond, GramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.GramPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 hg/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.HectogramsPerDay, HectogramsPerDayTolerance); - Assert.Equal(MassFlowUnit.HectogramPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 hg/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.HectogramsPerSecond, HectogramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.HectogramPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 hg/S", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.HectogramsPerSecond, HectogramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.HectogramPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 kg/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerDay, KilogramsPerDayTolerance); - Assert.Equal(MassFlowUnit.KilogramPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 kg/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerHour, KilogramsPerHourTolerance); - Assert.Equal(MassFlowUnit.KilogramPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 кг/ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerHour, KilogramsPerHourTolerance); - Assert.Equal(MassFlowUnit.KilogramPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 kg/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerMinute, KilogramsPerMinuteTolerance); - Assert.Equal(MassFlowUnit.KilogramPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 кг/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerMinute, KilogramsPerMinuteTolerance); - Assert.Equal(MassFlowUnit.KilogramPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 kg/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerSecond, KilogramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.KilogramPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 kg/S", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerSecond, KilogramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.KilogramPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 Mg/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegagramsPerDay, MegagramsPerDayTolerance); - Assert.Equal(MassFlowUnit.MegagramPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 Mlb/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegapoundsPerDay, MegapoundsPerDayTolerance); - Assert.Equal(MassFlowUnit.MegapoundPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 Mlb/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegapoundsPerHour, MegapoundsPerHourTolerance); - Assert.Equal(MassFlowUnit.MegapoundPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 Mlb/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegapoundsPerMinute, MegapoundsPerMinuteTolerance); - Assert.Equal(MassFlowUnit.MegapoundPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 Mlb/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegapoundsPerSecond, MegapoundsPerSecondTolerance); - Assert.Equal(MassFlowUnit.MegapoundPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 µg/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerDay, MicrogramsPerDayTolerance); - Assert.Equal(MassFlowUnit.MicrogramPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 µg/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerSecond, MicrogramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.MicrogramPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 µg/S", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerSecond, MicrogramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.MicrogramPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 mg/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligramsPerDay, MilligramsPerDayTolerance); - Assert.Equal(MassFlowUnit.MilligramPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 mg/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligramsPerSecond, MilligramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.MilligramPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 mg/S", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligramsPerSecond, MilligramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.MilligramPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 ng/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanogramsPerDay, NanogramsPerDayTolerance); - Assert.Equal(MassFlowUnit.NanogramPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 ng/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanogramsPerSecond, NanogramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.NanogramPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 ng/S", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanogramsPerSecond, NanogramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.NanogramPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 lb/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerDay, PoundsPerDayTolerance); - Assert.Equal(MassFlowUnit.PoundPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 lb/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerHour, PoundsPerHourTolerance); - Assert.Equal(MassFlowUnit.PoundPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 lb/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerMinute, PoundsPerMinuteTolerance); - Assert.Equal(MassFlowUnit.PoundPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 lb/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerSecond, PoundsPerSecondTolerance); - Assert.Equal(MassFlowUnit.PoundPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 short tn/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ShortTonsPerHour, ShortTonsPerHourTolerance); - Assert.Equal(MassFlowUnit.ShortTonPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 t/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonnesPerDay, TonnesPerDayTolerance); - Assert.Equal(MassFlowUnit.TonnePerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlow.Parse("1 t/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonnesPerHour, TonnesPerHourTolerance); - Assert.Equal(MassFlowUnit.TonnePerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = MassFlow.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 cg/d", MassFlowUnit.CentigramPerDay, 4.2)] + [InlineData("en-US", "4.2 cg/s", MassFlowUnit.CentigramPerSecond, 4.2)] + [InlineData("en-US", "4.2 cg/S", MassFlowUnit.CentigramPerSecond, 4.2)] + [InlineData("en-US", "4.2 dag/d", MassFlowUnit.DecagramPerDay, 4.2)] + [InlineData("en-US", "4.2 dag/s", MassFlowUnit.DecagramPerSecond, 4.2)] + [InlineData("en-US", "4.2 dag/S", MassFlowUnit.DecagramPerSecond, 4.2)] + [InlineData("en-US", "4.2 dg/d", MassFlowUnit.DecigramPerDay, 4.2)] + [InlineData("en-US", "4.2 dg/s", MassFlowUnit.DecigramPerSecond, 4.2)] + [InlineData("en-US", "4.2 dg/S", MassFlowUnit.DecigramPerSecond, 4.2)] + [InlineData("en-US", "4.2 g/d", MassFlowUnit.GramPerDay, 4.2)] + [InlineData("en-US", "4.2 g/h", MassFlowUnit.GramPerHour, 4.2)] + [InlineData("en-US", "4.2 g/s", MassFlowUnit.GramPerSecond, 4.2)] + [InlineData("en-US", "4.2 g/S", MassFlowUnit.GramPerSecond, 4.2)] + [InlineData("en-US", "4.2 hg/d", MassFlowUnit.HectogramPerDay, 4.2)] + [InlineData("en-US", "4.2 hg/s", MassFlowUnit.HectogramPerSecond, 4.2)] + [InlineData("en-US", "4.2 hg/S", MassFlowUnit.HectogramPerSecond, 4.2)] + [InlineData("en-US", "4.2 kg/d", MassFlowUnit.KilogramPerDay, 4.2)] + [InlineData("en-US", "4.2 kg/h", MassFlowUnit.KilogramPerHour, 4.2)] + [InlineData("en-US", "4.2 kg/min", MassFlowUnit.KilogramPerMinute, 4.2)] + [InlineData("en-US", "4.2 kg/s", MassFlowUnit.KilogramPerSecond, 4.2)] + [InlineData("en-US", "4.2 kg/S", MassFlowUnit.KilogramPerSecond, 4.2)] + [InlineData("en-US", "4.2 Mg/d", MassFlowUnit.MegagramPerDay, 4.2)] + [InlineData("en-US", "4.2 Mlb/d", MassFlowUnit.MegapoundPerDay, 4.2)] + [InlineData("en-US", "4.2 Mlb/h", MassFlowUnit.MegapoundPerHour, 4.2)] + [InlineData("en-US", "4.2 Mlb/min", MassFlowUnit.MegapoundPerMinute, 4.2)] + [InlineData("en-US", "4.2 Mlb/s", MassFlowUnit.MegapoundPerSecond, 4.2)] + [InlineData("en-US", "4.2 µg/d", MassFlowUnit.MicrogramPerDay, 4.2)] + [InlineData("en-US", "4.2 µg/s", MassFlowUnit.MicrogramPerSecond, 4.2)] + [InlineData("en-US", "4.2 µg/S", MassFlowUnit.MicrogramPerSecond, 4.2)] + [InlineData("en-US", "4.2 mg/d", MassFlowUnit.MilligramPerDay, 4.2)] + [InlineData("en-US", "4.2 mg/s", MassFlowUnit.MilligramPerSecond, 4.2)] + [InlineData("en-US", "4.2 mg/S", MassFlowUnit.MilligramPerSecond, 4.2)] + [InlineData("en-US", "4.2 ng/d", MassFlowUnit.NanogramPerDay, 4.2)] + [InlineData("en-US", "4.2 ng/s", MassFlowUnit.NanogramPerSecond, 4.2)] + [InlineData("en-US", "4.2 ng/S", MassFlowUnit.NanogramPerSecond, 4.2)] + [InlineData("en-US", "4.2 lb/d", MassFlowUnit.PoundPerDay, 4.2)] + [InlineData("en-US", "4.2 lb/h", MassFlowUnit.PoundPerHour, 4.2)] + [InlineData("en-US", "4.2 lb/min", MassFlowUnit.PoundPerMinute, 4.2)] + [InlineData("en-US", "4.2 lb/s", MassFlowUnit.PoundPerSecond, 4.2)] + [InlineData("en-US", "4.2 short tn/h", MassFlowUnit.ShortTonPerHour, 4.2)] + [InlineData("en-US", "4.2 t/d", MassFlowUnit.TonnePerDay, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(MassFlow.TryParse("1 cg/d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentigramsPerDay, CentigramsPerDayTolerance); - Assert.Equal(MassFlowUnit.CentigramPerDay, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 cg/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentigramsPerSecond, CentigramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.CentigramPerSecond, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 cg/S", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentigramsPerSecond, CentigramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.CentigramPerSecond, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 dag/d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecagramsPerDay, DecagramsPerDayTolerance); - Assert.Equal(MassFlowUnit.DecagramPerDay, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 dag/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecagramsPerSecond, DecagramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.DecagramPerSecond, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 dag/S", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecagramsPerSecond, DecagramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.DecagramPerSecond, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 dg/d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecigramsPerDay, DecigramsPerDayTolerance); - Assert.Equal(MassFlowUnit.DecigramPerDay, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 dg/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecigramsPerSecond, DecigramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.DecigramPerSecond, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 dg/S", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecigramsPerSecond, DecigramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.DecigramPerSecond, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 g/d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerDay, GramsPerDayTolerance); - Assert.Equal(MassFlowUnit.GramPerDay, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 g/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerHour, GramsPerHourTolerance); - Assert.Equal(MassFlowUnit.GramPerHour, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 g/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerSecond, GramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.GramPerSecond, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 g/S", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerSecond, GramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.GramPerSecond, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 hg/d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HectogramsPerDay, HectogramsPerDayTolerance); - Assert.Equal(MassFlowUnit.HectogramPerDay, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 hg/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HectogramsPerSecond, HectogramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.HectogramPerSecond, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 hg/S", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HectogramsPerSecond, HectogramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.HectogramPerSecond, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 kg/d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerDay, KilogramsPerDayTolerance); - Assert.Equal(MassFlowUnit.KilogramPerDay, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 kg/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerHour, KilogramsPerHourTolerance); - Assert.Equal(MassFlowUnit.KilogramPerHour, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 кг/ч", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerHour, KilogramsPerHourTolerance); - Assert.Equal(MassFlowUnit.KilogramPerHour, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 kg/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerMinute, KilogramsPerMinuteTolerance); - Assert.Equal(MassFlowUnit.KilogramPerMinute, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 кг/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerMinute, KilogramsPerMinuteTolerance); - Assert.Equal(MassFlowUnit.KilogramPerMinute, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 kg/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerSecond, KilogramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.KilogramPerSecond, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 kg/S", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerSecond, KilogramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.KilogramPerSecond, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 Mlb/d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegapoundsPerDay, MegapoundsPerDayTolerance); - Assert.Equal(MassFlowUnit.MegapoundPerDay, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 Mlb/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegapoundsPerHour, MegapoundsPerHourTolerance); - Assert.Equal(MassFlowUnit.MegapoundPerHour, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 Mlb/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegapoundsPerMinute, MegapoundsPerMinuteTolerance); - Assert.Equal(MassFlowUnit.MegapoundPerMinute, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 Mlb/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegapoundsPerSecond, MegapoundsPerSecondTolerance); - Assert.Equal(MassFlowUnit.MegapoundPerSecond, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 µg/d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerDay, MicrogramsPerDayTolerance); - Assert.Equal(MassFlowUnit.MicrogramPerDay, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 µg/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerSecond, MicrogramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.MicrogramPerSecond, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 µg/S", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerSecond, MicrogramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.MicrogramPerSecond, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 mg/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligramsPerSecond, MilligramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.MilligramPerSecond, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 mg/S", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligramsPerSecond, MilligramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.MilligramPerSecond, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 ng/d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanogramsPerDay, NanogramsPerDayTolerance); - Assert.Equal(MassFlowUnit.NanogramPerDay, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 ng/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanogramsPerSecond, NanogramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.NanogramPerSecond, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 ng/S", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanogramsPerSecond, NanogramsPerSecondTolerance); - Assert.Equal(MassFlowUnit.NanogramPerSecond, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 lb/d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerDay, PoundsPerDayTolerance); - Assert.Equal(MassFlowUnit.PoundPerDay, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 lb/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerHour, PoundsPerHourTolerance); - Assert.Equal(MassFlowUnit.PoundPerHour, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 lb/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerMinute, PoundsPerMinuteTolerance); - Assert.Equal(MassFlowUnit.PoundPerMinute, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 lb/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerSecond, PoundsPerSecondTolerance); - Assert.Equal(MassFlowUnit.PoundPerSecond, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 short tn/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ShortTonsPerHour, ShortTonsPerHourTolerance); - Assert.Equal(MassFlowUnit.ShortTonPerHour, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 t/d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonnesPerDay, TonnesPerDayTolerance); - Assert.Equal(MassFlowUnit.TonnePerDay, parsed.Unit); - } - - { - Assert.True(MassFlow.TryParse("1 t/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonnesPerHour, TonnesPerHourTolerance); - Assert.Equal(MassFlowUnit.TonnePerHour, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(MassFlow.TryParse(quantityString, out MassFlow parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -1567,6 +1121,61 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, MassFl Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", MassFlowUnit.CentigramPerDay, "cg/d")] + [InlineData("en-US", MassFlowUnit.CentigramPerSecond, "cg/s")] + [InlineData("en-US", MassFlowUnit.DecagramPerDay, "dag/d")] + [InlineData("en-US", MassFlowUnit.DecagramPerSecond, "dag/s")] + [InlineData("en-US", MassFlowUnit.DecigramPerDay, "dg/d")] + [InlineData("en-US", MassFlowUnit.DecigramPerSecond, "dg/s")] + [InlineData("en-US", MassFlowUnit.GramPerDay, "g/d")] + [InlineData("en-US", MassFlowUnit.GramPerHour, "g/h")] + [InlineData("en-US", MassFlowUnit.GramPerSecond, "g/s")] + [InlineData("en-US", MassFlowUnit.HectogramPerDay, "hg/d")] + [InlineData("en-US", MassFlowUnit.HectogramPerSecond, "hg/s")] + [InlineData("en-US", MassFlowUnit.KilogramPerDay, "kg/d")] + [InlineData("en-US", MassFlowUnit.KilogramPerHour, "kg/h")] + [InlineData("en-US", MassFlowUnit.KilogramPerMinute, "kg/min")] + [InlineData("en-US", MassFlowUnit.KilogramPerSecond, "kg/s")] + [InlineData("en-US", MassFlowUnit.MegagramPerDay, "Mg/d")] + [InlineData("en-US", MassFlowUnit.MegapoundPerDay, "Mlb/d")] + [InlineData("en-US", MassFlowUnit.MegapoundPerHour, "Mlb/h")] + [InlineData("en-US", MassFlowUnit.MegapoundPerMinute, "Mlb/min")] + [InlineData("en-US", MassFlowUnit.MegapoundPerSecond, "Mlb/s")] + [InlineData("en-US", MassFlowUnit.MicrogramPerDay, "µg/d")] + [InlineData("en-US", MassFlowUnit.MicrogramPerSecond, "µg/s")] + [InlineData("en-US", MassFlowUnit.MilligramPerDay, "mg/d")] + [InlineData("en-US", MassFlowUnit.MilligramPerSecond, "mg/s")] + [InlineData("en-US", MassFlowUnit.NanogramPerDay, "ng/d")] + [InlineData("en-US", MassFlowUnit.NanogramPerSecond, "ng/s")] + [InlineData("en-US", MassFlowUnit.PoundPerDay, "lb/d")] + [InlineData("en-US", MassFlowUnit.PoundPerHour, "lb/h")] + [InlineData("en-US", MassFlowUnit.PoundPerMinute, "lb/min")] + [InlineData("en-US", MassFlowUnit.PoundPerSecond, "lb/s")] + [InlineData("en-US", MassFlowUnit.ShortTonPerHour, "short tn/h")] + [InlineData("en-US", MassFlowUnit.TonnePerDay, "t/d")] + [InlineData("en-US", MassFlowUnit.TonnePerHour, "t/h")] + [InlineData("ru-RU", MassFlowUnit.KilogramPerHour, "кг/ч")] + [InlineData("ru-RU", MassFlowUnit.KilogramPerMinute, "кг/мин")] + public void GetAbbreviationForCulture(string culture, MassFlowUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = MassFlow.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(MassFlow.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = MassFlow.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(MassFlowUnit unit) @@ -1597,6 +1206,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); }); } @@ -1620,64 +1230,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] @@ -1723,8 +1335,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); @@ -1761,23 +1371,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = MassFlow.FromGramsPerSecond(1); - Assert.True(v.Equals(MassFlow.FromGramsPerSecond(1), GramsPerSecondTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(MassFlow.Zero, GramsPerSecondTolerance, ComparisonType.Relative)); - Assert.True(MassFlow.FromGramsPerSecond(100).Equals(MassFlow.FromGramsPerSecond(120), 0.3, ComparisonType.Relative)); - Assert.False(MassFlow.FromGramsPerSecond(100).Equals(MassFlow.FromGramsPerSecond(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = MassFlow.FromGramsPerSecond(1); - Assert.Throws(() => v.Equals(MassFlow.FromGramsPerSecond(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1792,6 +1385,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(grampersecond.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = MassFlow.FromGramsPerSecond(1); + var negativeTolerance = MassFlow.FromGramsPerSecond(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1808,6 +1427,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() { @@ -1930,158 +1561,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(MassFlow))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MassFlowUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal(MassFlow.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal(MassFlow.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal(new {MassFlow.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 977dd21715..9438abb688 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassFluxTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassFluxTestsBase.g.cs @@ -140,7 +140,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new MassFlux(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -153,15 +153,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void MassFlux_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + MassFluxUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new MassFlux(1, MassFluxUnit.KilogramPerSecondPerSquareMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(MassFlux.Zero, quantityInfo.Zero); Assert.Equal("MassFlux", quantityInfo.Name); + Assert.Equal(MassFlux.Zero, quantityInfo.Zero); + Assert.Equal(MassFlux.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(MassFlux.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -186,51 +204,51 @@ public void KilogramPerSecondPerSquareMeterToMassFluxUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = MassFlux.From(1, MassFluxUnit.GramPerHourPerSquareCentimeter); - AssertEx.EqualTolerance(1, quantity00.GramsPerHourPerSquareCentimeter, GramsPerHourPerSquareCentimeterTolerance); + Assert.Equal(1, quantity00.GramsPerHourPerSquareCentimeter); Assert.Equal(MassFluxUnit.GramPerHourPerSquareCentimeter, quantity00.Unit); var quantity01 = MassFlux.From(1, MassFluxUnit.GramPerHourPerSquareMeter); - AssertEx.EqualTolerance(1, quantity01.GramsPerHourPerSquareMeter, GramsPerHourPerSquareMeterTolerance); + Assert.Equal(1, quantity01.GramsPerHourPerSquareMeter); Assert.Equal(MassFluxUnit.GramPerHourPerSquareMeter, quantity01.Unit); var quantity02 = MassFlux.From(1, MassFluxUnit.GramPerHourPerSquareMillimeter); - AssertEx.EqualTolerance(1, quantity02.GramsPerHourPerSquareMillimeter, GramsPerHourPerSquareMillimeterTolerance); + Assert.Equal(1, quantity02.GramsPerHourPerSquareMillimeter); Assert.Equal(MassFluxUnit.GramPerHourPerSquareMillimeter, quantity02.Unit); var quantity03 = MassFlux.From(1, MassFluxUnit.GramPerSecondPerSquareCentimeter); - AssertEx.EqualTolerance(1, quantity03.GramsPerSecondPerSquareCentimeter, GramsPerSecondPerSquareCentimeterTolerance); + Assert.Equal(1, quantity03.GramsPerSecondPerSquareCentimeter); Assert.Equal(MassFluxUnit.GramPerSecondPerSquareCentimeter, quantity03.Unit); var quantity04 = MassFlux.From(1, MassFluxUnit.GramPerSecondPerSquareMeter); - AssertEx.EqualTolerance(1, quantity04.GramsPerSecondPerSquareMeter, GramsPerSecondPerSquareMeterTolerance); + Assert.Equal(1, quantity04.GramsPerSecondPerSquareMeter); Assert.Equal(MassFluxUnit.GramPerSecondPerSquareMeter, quantity04.Unit); var quantity05 = MassFlux.From(1, MassFluxUnit.GramPerSecondPerSquareMillimeter); - AssertEx.EqualTolerance(1, quantity05.GramsPerSecondPerSquareMillimeter, GramsPerSecondPerSquareMillimeterTolerance); + Assert.Equal(1, quantity05.GramsPerSecondPerSquareMillimeter); Assert.Equal(MassFluxUnit.GramPerSecondPerSquareMillimeter, quantity05.Unit); var quantity06 = MassFlux.From(1, MassFluxUnit.KilogramPerHourPerSquareCentimeter); - AssertEx.EqualTolerance(1, quantity06.KilogramsPerHourPerSquareCentimeter, KilogramsPerHourPerSquareCentimeterTolerance); + Assert.Equal(1, quantity06.KilogramsPerHourPerSquareCentimeter); Assert.Equal(MassFluxUnit.KilogramPerHourPerSquareCentimeter, quantity06.Unit); var quantity07 = MassFlux.From(1, MassFluxUnit.KilogramPerHourPerSquareMeter); - AssertEx.EqualTolerance(1, quantity07.KilogramsPerHourPerSquareMeter, KilogramsPerHourPerSquareMeterTolerance); + Assert.Equal(1, quantity07.KilogramsPerHourPerSquareMeter); Assert.Equal(MassFluxUnit.KilogramPerHourPerSquareMeter, quantity07.Unit); var quantity08 = MassFlux.From(1, MassFluxUnit.KilogramPerHourPerSquareMillimeter); - AssertEx.EqualTolerance(1, quantity08.KilogramsPerHourPerSquareMillimeter, KilogramsPerHourPerSquareMillimeterTolerance); + Assert.Equal(1, quantity08.KilogramsPerHourPerSquareMillimeter); Assert.Equal(MassFluxUnit.KilogramPerHourPerSquareMillimeter, quantity08.Unit); var quantity09 = MassFlux.From(1, MassFluxUnit.KilogramPerSecondPerSquareCentimeter); - AssertEx.EqualTolerance(1, quantity09.KilogramsPerSecondPerSquareCentimeter, KilogramsPerSecondPerSquareCentimeterTolerance); + Assert.Equal(1, quantity09.KilogramsPerSecondPerSquareCentimeter); Assert.Equal(MassFluxUnit.KilogramPerSecondPerSquareCentimeter, quantity09.Unit); var quantity10 = MassFlux.From(1, MassFluxUnit.KilogramPerSecondPerSquareMeter); - AssertEx.EqualTolerance(1, quantity10.KilogramsPerSecondPerSquareMeter, KilogramsPerSecondPerSquareMeterTolerance); + Assert.Equal(1, quantity10.KilogramsPerSecondPerSquareMeter); Assert.Equal(MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity10.Unit); var quantity11 = MassFlux.From(1, MassFluxUnit.KilogramPerSecondPerSquareMillimeter); - AssertEx.EqualTolerance(1, quantity11.KilogramsPerSecondPerSquareMillimeter, KilogramsPerSecondPerSquareMillimeterTolerance); + Assert.Equal(1, quantity11.KilogramsPerSecondPerSquareMillimeter); Assert.Equal(MassFluxUnit.KilogramPerSecondPerSquareMillimeter, quantity11.Unit); } @@ -377,170 +395,46 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 g·h⁻¹·cm⁻²", MassFluxUnit.GramPerHourPerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 g·h⁻¹·m⁻²", MassFluxUnit.GramPerHourPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 g·h⁻¹·mm⁻²", MassFluxUnit.GramPerHourPerSquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 g·s⁻¹·cm⁻²", MassFluxUnit.GramPerSecondPerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 g·s⁻¹·m⁻²", MassFluxUnit.GramPerSecondPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 g·s⁻¹·mm⁻²", MassFluxUnit.GramPerSecondPerSquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 kg·h⁻¹·cm⁻²", MassFluxUnit.KilogramPerHourPerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 kg·h⁻¹·m⁻²", MassFluxUnit.KilogramPerHourPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 kg·h⁻¹·mm⁻²", MassFluxUnit.KilogramPerHourPerSquareMillimeter, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = MassFlux.Parse("1 g·h⁻¹·cm⁻²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerHourPerSquareCentimeter, GramsPerHourPerSquareCentimeterTolerance); - Assert.Equal(MassFluxUnit.GramPerHourPerSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlux.Parse("1 g·h⁻¹·m⁻²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerHourPerSquareMeter, GramsPerHourPerSquareMeterTolerance); - Assert.Equal(MassFluxUnit.GramPerHourPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlux.Parse("1 g·h⁻¹·mm⁻²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerHourPerSquareMillimeter, GramsPerHourPerSquareMillimeterTolerance); - Assert.Equal(MassFluxUnit.GramPerHourPerSquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlux.Parse("1 g·s⁻¹·cm⁻²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerSecondPerSquareCentimeter, GramsPerSecondPerSquareCentimeterTolerance); - Assert.Equal(MassFluxUnit.GramPerSecondPerSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlux.Parse("1 g·s⁻¹·m⁻²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerSecondPerSquareMeter, GramsPerSecondPerSquareMeterTolerance); - Assert.Equal(MassFluxUnit.GramPerSecondPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlux.Parse("1 g·s⁻¹·mm⁻²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerSecondPerSquareMillimeter, GramsPerSecondPerSquareMillimeterTolerance); - Assert.Equal(MassFluxUnit.GramPerSecondPerSquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlux.Parse("1 kg·h⁻¹·cm⁻²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerHourPerSquareCentimeter, KilogramsPerHourPerSquareCentimeterTolerance); - Assert.Equal(MassFluxUnit.KilogramPerHourPerSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlux.Parse("1 kg·h⁻¹·m⁻²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerHourPerSquareMeter, KilogramsPerHourPerSquareMeterTolerance); - Assert.Equal(MassFluxUnit.KilogramPerHourPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlux.Parse("1 kg·h⁻¹·mm⁻²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerHourPerSquareMillimeter, KilogramsPerHourPerSquareMillimeterTolerance); - Assert.Equal(MassFluxUnit.KilogramPerHourPerSquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlux.Parse("1 kg·s⁻¹·cm⁻²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerSecondPerSquareCentimeter, KilogramsPerSecondPerSquareCentimeterTolerance); - Assert.Equal(MassFluxUnit.KilogramPerSecondPerSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlux.Parse("1 kg·s⁻¹·m⁻²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerSecondPerSquareMeter, KilogramsPerSecondPerSquareMeterTolerance); - Assert.Equal(MassFluxUnit.KilogramPerSecondPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFlux.Parse("1 kg·s⁻¹·mm⁻²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerSecondPerSquareMillimeter, KilogramsPerSecondPerSquareMillimeterTolerance); - Assert.Equal(MassFluxUnit.KilogramPerSecondPerSquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = MassFlux.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 g·h⁻¹·cm⁻²", MassFluxUnit.GramPerHourPerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 g·h⁻¹·m⁻²", MassFluxUnit.GramPerHourPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 g·h⁻¹·mm⁻²", MassFluxUnit.GramPerHourPerSquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 g·s⁻¹·cm⁻²", MassFluxUnit.GramPerSecondPerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 g·s⁻¹·m⁻²", MassFluxUnit.GramPerSecondPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 g·s⁻¹·mm⁻²", MassFluxUnit.GramPerSecondPerSquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 kg·h⁻¹·cm⁻²", MassFluxUnit.KilogramPerHourPerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 kg·h⁻¹·m⁻²", MassFluxUnit.KilogramPerHourPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 kg·h⁻¹·mm⁻²", MassFluxUnit.KilogramPerHourPerSquareMillimeter, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(MassFlux.TryParse("1 g·h⁻¹·cm⁻²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerHourPerSquareCentimeter, GramsPerHourPerSquareCentimeterTolerance); - Assert.Equal(MassFluxUnit.GramPerHourPerSquareCentimeter, parsed.Unit); - } - - { - Assert.True(MassFlux.TryParse("1 g·h⁻¹·m⁻²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerHourPerSquareMeter, GramsPerHourPerSquareMeterTolerance); - Assert.Equal(MassFluxUnit.GramPerHourPerSquareMeter, parsed.Unit); - } - - { - Assert.True(MassFlux.TryParse("1 g·h⁻¹·mm⁻²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerHourPerSquareMillimeter, GramsPerHourPerSquareMillimeterTolerance); - Assert.Equal(MassFluxUnit.GramPerHourPerSquareMillimeter, parsed.Unit); - } - - { - Assert.True(MassFlux.TryParse("1 g·s⁻¹·cm⁻²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerSecondPerSquareCentimeter, GramsPerSecondPerSquareCentimeterTolerance); - Assert.Equal(MassFluxUnit.GramPerSecondPerSquareCentimeter, parsed.Unit); - } - - { - Assert.True(MassFlux.TryParse("1 g·s⁻¹·m⁻²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerSecondPerSquareMeter, GramsPerSecondPerSquareMeterTolerance); - Assert.Equal(MassFluxUnit.GramPerSecondPerSquareMeter, parsed.Unit); - } - - { - Assert.True(MassFlux.TryParse("1 g·s⁻¹·mm⁻²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerSecondPerSquareMillimeter, GramsPerSecondPerSquareMillimeterTolerance); - Assert.Equal(MassFluxUnit.GramPerSecondPerSquareMillimeter, parsed.Unit); - } - - { - Assert.True(MassFlux.TryParse("1 kg·h⁻¹·cm⁻²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerHourPerSquareCentimeter, KilogramsPerHourPerSquareCentimeterTolerance); - Assert.Equal(MassFluxUnit.KilogramPerHourPerSquareCentimeter, parsed.Unit); - } - - { - Assert.True(MassFlux.TryParse("1 kg·h⁻¹·m⁻²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerHourPerSquareMeter, KilogramsPerHourPerSquareMeterTolerance); - Assert.Equal(MassFluxUnit.KilogramPerHourPerSquareMeter, parsed.Unit); - } - - { - Assert.True(MassFlux.TryParse("1 kg·h⁻¹·mm⁻²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerHourPerSquareMillimeter, KilogramsPerHourPerSquareMillimeterTolerance); - Assert.Equal(MassFluxUnit.KilogramPerHourPerSquareMillimeter, parsed.Unit); - } - - { - Assert.True(MassFlux.TryParse("1 kg·s⁻¹·cm⁻²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerSecondPerSquareCentimeter, KilogramsPerSecondPerSquareCentimeterTolerance); - Assert.Equal(MassFluxUnit.KilogramPerSecondPerSquareCentimeter, parsed.Unit); - } - - { - Assert.True(MassFlux.TryParse("1 kg·s⁻¹·m⁻²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerSecondPerSquareMeter, KilogramsPerSecondPerSquareMeterTolerance); - Assert.Equal(MassFluxUnit.KilogramPerSecondPerSquareMeter, parsed.Unit); - } - - { - Assert.True(MassFlux.TryParse("1 kg·s⁻¹·mm⁻²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerSecondPerSquareMillimeter, KilogramsPerSecondPerSquareMillimeterTolerance); - Assert.Equal(MassFluxUnit.KilogramPerSecondPerSquareMillimeter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(MassFlux.TryParse(quantityString, out MassFlux parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -705,6 +599,38 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, MassFl Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", MassFluxUnit.GramPerHourPerSquareCentimeter, "g·h⁻¹·cm⁻²")] + [InlineData("en-US", MassFluxUnit.GramPerHourPerSquareMeter, "g·h⁻¹·m⁻²")] + [InlineData("en-US", MassFluxUnit.GramPerHourPerSquareMillimeter, "g·h⁻¹·mm⁻²")] + [InlineData("en-US", MassFluxUnit.GramPerSecondPerSquareCentimeter, "g·s⁻¹·cm⁻²")] + [InlineData("en-US", MassFluxUnit.GramPerSecondPerSquareMeter, "g·s⁻¹·m⁻²")] + [InlineData("en-US", MassFluxUnit.GramPerSecondPerSquareMillimeter, "g·s⁻¹·mm⁻²")] + [InlineData("en-US", MassFluxUnit.KilogramPerHourPerSquareCentimeter, "kg·h⁻¹·cm⁻²")] + [InlineData("en-US", MassFluxUnit.KilogramPerHourPerSquareMeter, "kg·h⁻¹·m⁻²")] + [InlineData("en-US", MassFluxUnit.KilogramPerHourPerSquareMillimeter, "kg·h⁻¹·mm⁻²")] + [InlineData("en-US", MassFluxUnit.KilogramPerSecondPerSquareCentimeter, "kg·s⁻¹·cm⁻²")] + [InlineData("en-US", MassFluxUnit.KilogramPerSecondPerSquareMeter, "kg·s⁻¹·m⁻²")] + [InlineData("en-US", MassFluxUnit.KilogramPerSecondPerSquareMillimeter, "kg·s⁻¹·mm⁻²")] + public void GetAbbreviationForCulture(string culture, MassFluxUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = MassFlux.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(MassFlux.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = MassFlux.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(MassFluxUnit unit) @@ -735,6 +661,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); }); } @@ -758,43 +685,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] @@ -840,8 +769,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); @@ -879,34 +806,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = MassFlux.FromKilogramsPerSecondPerSquareMeter(1); - Assert.True(v.Equals(MassFlux.FromKilogramsPerSecondPerSquareMeter(1), KilogramsPerSecondPerSquareMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(MassFlux.Zero, KilogramsPerSecondPerSquareMeterTolerance, ComparisonType.Relative)); - Assert.True(MassFlux.FromKilogramsPerSecondPerSquareMeter(100).Equals(MassFlux.FromKilogramsPerSecondPerSquareMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(MassFlux.FromKilogramsPerSecondPerSquareMeter(100).Equals(MassFlux.FromKilogramsPerSecondPerSquareMeter(120), 0.1, ComparisonType.Relative)); + MassFlux kilogrampersecondpersquaremeter = MassFlux.FromKilogramsPerSecondPerSquareMeter(1); + Assert.False(kilogrampersecondpersquaremeter.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = MassFlux.FromKilogramsPerSecondPerSquareMeter(1); - Assert.Throws(() => v.Equals(MassFlux.FromKilogramsPerSecondPerSquareMeter(1), -1, ComparisonType.Relative)); + MassFlux kilogrampersecondpersquaremeter = MassFlux.FromKilogramsPerSecondPerSquareMeter(1); + Assert.False(kilogrampersecondpersquaremeter.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - MassFlux kilogrampersecondpersquaremeter = MassFlux.FromKilogramsPerSecondPerSquareMeter(1); - Assert.False(kilogrampersecondpersquaremeter.Equals(new object())); + var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(firstValue); + var otherQuantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(secondValue); + MassFlux maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - MassFlux kilogrampersecondpersquaremeter = MassFlux.FromKilogramsPerSecondPerSquareMeter(1); - Assert.False(kilogrampersecondpersquaremeter.Equals(null)); + var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1); + var negativeTolerance = MassFlux.FromKilogramsPerSecondPerSquareMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -925,6 +861,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() { @@ -1005,158 +953,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(MassFlux))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MassFluxUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal(MassFlux.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal(MassFlux.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal(new {MassFlux.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 bb9e42263e..5aa242f79b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassFractionTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassFractionTestsBase.g.cs @@ -180,15 +180,33 @@ public void Ctor_WithNaNValue_DoNotThrowsArgumentException() [Fact] public void MassFraction_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + MassFractionUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new MassFraction(1, MassFractionUnit.DecimalFraction); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(MassFraction.Zero, quantityInfo.Zero); Assert.Equal("MassFraction", quantityInfo.Name); + Assert.Equal(MassFraction.Zero, quantityInfo.Zero); + Assert.Equal(MassFraction.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(MassFraction.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + [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] @@ -225,99 +243,99 @@ public void DecimalFractionToMassFractionUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = MassFraction.From(1, MassFractionUnit.CentigramPerGram); - AssertEx.EqualTolerance(1, quantity00.CentigramsPerGram, CentigramsPerGramTolerance); + Assert.Equal(1, quantity00.CentigramsPerGram); Assert.Equal(MassFractionUnit.CentigramPerGram, quantity00.Unit); var quantity01 = MassFraction.From(1, MassFractionUnit.CentigramPerKilogram); - AssertEx.EqualTolerance(1, quantity01.CentigramsPerKilogram, CentigramsPerKilogramTolerance); + Assert.Equal(1, quantity01.CentigramsPerKilogram); Assert.Equal(MassFractionUnit.CentigramPerKilogram, quantity01.Unit); var quantity02 = MassFraction.From(1, MassFractionUnit.DecagramPerGram); - AssertEx.EqualTolerance(1, quantity02.DecagramsPerGram, DecagramsPerGramTolerance); + Assert.Equal(1, quantity02.DecagramsPerGram); Assert.Equal(MassFractionUnit.DecagramPerGram, quantity02.Unit); var quantity03 = MassFraction.From(1, MassFractionUnit.DecagramPerKilogram); - AssertEx.EqualTolerance(1, quantity03.DecagramsPerKilogram, DecagramsPerKilogramTolerance); + Assert.Equal(1, quantity03.DecagramsPerKilogram); Assert.Equal(MassFractionUnit.DecagramPerKilogram, quantity03.Unit); var quantity04 = MassFraction.From(1, MassFractionUnit.DecigramPerGram); - AssertEx.EqualTolerance(1, quantity04.DecigramsPerGram, DecigramsPerGramTolerance); + Assert.Equal(1, quantity04.DecigramsPerGram); Assert.Equal(MassFractionUnit.DecigramPerGram, quantity04.Unit); var quantity05 = MassFraction.From(1, MassFractionUnit.DecigramPerKilogram); - AssertEx.EqualTolerance(1, quantity05.DecigramsPerKilogram, DecigramsPerKilogramTolerance); + Assert.Equal(1, quantity05.DecigramsPerKilogram); Assert.Equal(MassFractionUnit.DecigramPerKilogram, quantity05.Unit); var quantity06 = MassFraction.From(1, MassFractionUnit.DecimalFraction); - AssertEx.EqualTolerance(1, quantity06.DecimalFractions, DecimalFractionsTolerance); + Assert.Equal(1, quantity06.DecimalFractions); Assert.Equal(MassFractionUnit.DecimalFraction, quantity06.Unit); var quantity07 = MassFraction.From(1, MassFractionUnit.GramPerGram); - AssertEx.EqualTolerance(1, quantity07.GramsPerGram, GramsPerGramTolerance); + Assert.Equal(1, quantity07.GramsPerGram); Assert.Equal(MassFractionUnit.GramPerGram, quantity07.Unit); var quantity08 = MassFraction.From(1, MassFractionUnit.GramPerKilogram); - AssertEx.EqualTolerance(1, quantity08.GramsPerKilogram, GramsPerKilogramTolerance); + Assert.Equal(1, quantity08.GramsPerKilogram); Assert.Equal(MassFractionUnit.GramPerKilogram, quantity08.Unit); var quantity09 = MassFraction.From(1, MassFractionUnit.HectogramPerGram); - AssertEx.EqualTolerance(1, quantity09.HectogramsPerGram, HectogramsPerGramTolerance); + Assert.Equal(1, quantity09.HectogramsPerGram); Assert.Equal(MassFractionUnit.HectogramPerGram, quantity09.Unit); var quantity10 = MassFraction.From(1, MassFractionUnit.HectogramPerKilogram); - AssertEx.EqualTolerance(1, quantity10.HectogramsPerKilogram, HectogramsPerKilogramTolerance); + Assert.Equal(1, quantity10.HectogramsPerKilogram); Assert.Equal(MassFractionUnit.HectogramPerKilogram, quantity10.Unit); var quantity11 = MassFraction.From(1, MassFractionUnit.KilogramPerGram); - AssertEx.EqualTolerance(1, quantity11.KilogramsPerGram, KilogramsPerGramTolerance); + Assert.Equal(1, quantity11.KilogramsPerGram); Assert.Equal(MassFractionUnit.KilogramPerGram, quantity11.Unit); var quantity12 = MassFraction.From(1, MassFractionUnit.KilogramPerKilogram); - AssertEx.EqualTolerance(1, quantity12.KilogramsPerKilogram, KilogramsPerKilogramTolerance); + Assert.Equal(1, quantity12.KilogramsPerKilogram); Assert.Equal(MassFractionUnit.KilogramPerKilogram, quantity12.Unit); var quantity13 = MassFraction.From(1, MassFractionUnit.MicrogramPerGram); - AssertEx.EqualTolerance(1, quantity13.MicrogramsPerGram, MicrogramsPerGramTolerance); + Assert.Equal(1, quantity13.MicrogramsPerGram); Assert.Equal(MassFractionUnit.MicrogramPerGram, quantity13.Unit); var quantity14 = MassFraction.From(1, MassFractionUnit.MicrogramPerKilogram); - AssertEx.EqualTolerance(1, quantity14.MicrogramsPerKilogram, MicrogramsPerKilogramTolerance); + Assert.Equal(1, quantity14.MicrogramsPerKilogram); Assert.Equal(MassFractionUnit.MicrogramPerKilogram, quantity14.Unit); var quantity15 = MassFraction.From(1, MassFractionUnit.MilligramPerGram); - AssertEx.EqualTolerance(1, quantity15.MilligramsPerGram, MilligramsPerGramTolerance); + Assert.Equal(1, quantity15.MilligramsPerGram); Assert.Equal(MassFractionUnit.MilligramPerGram, quantity15.Unit); var quantity16 = MassFraction.From(1, MassFractionUnit.MilligramPerKilogram); - AssertEx.EqualTolerance(1, quantity16.MilligramsPerKilogram, MilligramsPerKilogramTolerance); + Assert.Equal(1, quantity16.MilligramsPerKilogram); Assert.Equal(MassFractionUnit.MilligramPerKilogram, quantity16.Unit); var quantity17 = MassFraction.From(1, MassFractionUnit.NanogramPerGram); - AssertEx.EqualTolerance(1, quantity17.NanogramsPerGram, NanogramsPerGramTolerance); + Assert.Equal(1, quantity17.NanogramsPerGram); Assert.Equal(MassFractionUnit.NanogramPerGram, quantity17.Unit); var quantity18 = MassFraction.From(1, MassFractionUnit.NanogramPerKilogram); - AssertEx.EqualTolerance(1, quantity18.NanogramsPerKilogram, NanogramsPerKilogramTolerance); + Assert.Equal(1, quantity18.NanogramsPerKilogram); Assert.Equal(MassFractionUnit.NanogramPerKilogram, quantity18.Unit); var quantity19 = MassFraction.From(1, MassFractionUnit.PartPerBillion); - AssertEx.EqualTolerance(1, quantity19.PartsPerBillion, PartsPerBillionTolerance); + Assert.Equal(1, quantity19.PartsPerBillion); Assert.Equal(MassFractionUnit.PartPerBillion, quantity19.Unit); var quantity20 = MassFraction.From(1, MassFractionUnit.PartPerMillion); - AssertEx.EqualTolerance(1, quantity20.PartsPerMillion, PartsPerMillionTolerance); + Assert.Equal(1, quantity20.PartsPerMillion); Assert.Equal(MassFractionUnit.PartPerMillion, quantity20.Unit); var quantity21 = MassFraction.From(1, MassFractionUnit.PartPerThousand); - AssertEx.EqualTolerance(1, quantity21.PartsPerThousand, PartsPerThousandTolerance); + Assert.Equal(1, quantity21.PartsPerThousand); Assert.Equal(MassFractionUnit.PartPerThousand, quantity21.Unit); var quantity22 = MassFraction.From(1, MassFractionUnit.PartPerTrillion); - AssertEx.EqualTolerance(1, quantity22.PartsPerTrillion, PartsPerTrillionTolerance); + Assert.Equal(1, quantity22.PartsPerTrillion); Assert.Equal(MassFractionUnit.PartPerTrillion, quantity22.Unit); var quantity23 = MassFraction.From(1, MassFractionUnit.Percent); - AssertEx.EqualTolerance(1, quantity23.Percent, PercentTolerance); + Assert.Equal(1, quantity23.Percent); Assert.Equal(MassFractionUnit.Percent, quantity23.Unit); } @@ -437,339 +455,72 @@ public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 cg/g", MassFractionUnit.CentigramPerGram, 4.2)] + [InlineData("en-US", "4.2 cg/kg", MassFractionUnit.CentigramPerKilogram, 4.2)] + [InlineData("en-US", "4.2 dag/g", MassFractionUnit.DecagramPerGram, 4.2)] + [InlineData("en-US", "4.2 dag/kg", MassFractionUnit.DecagramPerKilogram, 4.2)] + [InlineData("en-US", "4.2 dg/g", MassFractionUnit.DecigramPerGram, 4.2)] + [InlineData("en-US", "4.2 dg/kg", MassFractionUnit.DecigramPerKilogram, 4.2)] + [InlineData("en-US", "4.2 ", MassFractionUnit.DecimalFraction, 4.2)] + [InlineData("en-US", "4.2 g/g", MassFractionUnit.GramPerGram, 4.2)] + [InlineData("en-US", "4.2 g/kg", MassFractionUnit.GramPerKilogram, 4.2)] + [InlineData("en-US", "4.2 hg/g", MassFractionUnit.HectogramPerGram, 4.2)] + [InlineData("en-US", "4.2 hg/kg", MassFractionUnit.HectogramPerKilogram, 4.2)] + [InlineData("en-US", "4.2 kg/g", MassFractionUnit.KilogramPerGram, 4.2)] + [InlineData("en-US", "4.2 kg/kg", MassFractionUnit.KilogramPerKilogram, 4.2)] + [InlineData("en-US", "4.2 µg/g", MassFractionUnit.MicrogramPerGram, 4.2)] + [InlineData("en-US", "4.2 µg/kg", MassFractionUnit.MicrogramPerKilogram, 4.2)] + [InlineData("en-US", "4.2 mg/g", MassFractionUnit.MilligramPerGram, 4.2)] + [InlineData("en-US", "4.2 mg/kg", MassFractionUnit.MilligramPerKilogram, 4.2)] + [InlineData("en-US", "4.2 ng/g", MassFractionUnit.NanogramPerGram, 4.2)] + [InlineData("en-US", "4.2 ng/kg", MassFractionUnit.NanogramPerKilogram, 4.2)] + [InlineData("en-US", "4.2 ppb", MassFractionUnit.PartPerBillion, 4.2)] + [InlineData("en-US", "4.2 ppm", MassFractionUnit.PartPerMillion, 4.2)] + [InlineData("en-US", "4.2 ‰", MassFractionUnit.PartPerThousand, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = MassFraction.Parse("1 cg/g", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentigramsPerGram, CentigramsPerGramTolerance); - Assert.Equal(MassFractionUnit.CentigramPerGram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFraction.Parse("1 cg/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentigramsPerKilogram, CentigramsPerKilogramTolerance); - Assert.Equal(MassFractionUnit.CentigramPerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFraction.Parse("1 dag/g", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecagramsPerGram, DecagramsPerGramTolerance); - Assert.Equal(MassFractionUnit.DecagramPerGram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFraction.Parse("1 dag/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecagramsPerKilogram, DecagramsPerKilogramTolerance); - Assert.Equal(MassFractionUnit.DecagramPerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFraction.Parse("1 dg/g", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecigramsPerGram, DecigramsPerGramTolerance); - Assert.Equal(MassFractionUnit.DecigramPerGram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFraction.Parse("1 dg/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecigramsPerKilogram, DecigramsPerKilogramTolerance); - Assert.Equal(MassFractionUnit.DecigramPerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFraction.Parse("1 ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecimalFractions, DecimalFractionsTolerance); - Assert.Equal(MassFractionUnit.DecimalFraction, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFraction.Parse("1 g/g", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerGram, GramsPerGramTolerance); - Assert.Equal(MassFractionUnit.GramPerGram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFraction.Parse("1 g/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerKilogram, GramsPerKilogramTolerance); - Assert.Equal(MassFractionUnit.GramPerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFraction.Parse("1 hg/g", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.HectogramsPerGram, HectogramsPerGramTolerance); - Assert.Equal(MassFractionUnit.HectogramPerGram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFraction.Parse("1 hg/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.HectogramsPerKilogram, HectogramsPerKilogramTolerance); - Assert.Equal(MassFractionUnit.HectogramPerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFraction.Parse("1 kg/g", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerGram, KilogramsPerGramTolerance); - Assert.Equal(MassFractionUnit.KilogramPerGram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFraction.Parse("1 kg/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerKilogram, KilogramsPerKilogramTolerance); - Assert.Equal(MassFractionUnit.KilogramPerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFraction.Parse("1 µg/g", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerGram, MicrogramsPerGramTolerance); - Assert.Equal(MassFractionUnit.MicrogramPerGram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFraction.Parse("1 µg/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerKilogram, MicrogramsPerKilogramTolerance); - Assert.Equal(MassFractionUnit.MicrogramPerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFraction.Parse("1 mg/g", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligramsPerGram, MilligramsPerGramTolerance); - Assert.Equal(MassFractionUnit.MilligramPerGram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFraction.Parse("1 mg/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligramsPerKilogram, MilligramsPerKilogramTolerance); - Assert.Equal(MassFractionUnit.MilligramPerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFraction.Parse("1 ng/g", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanogramsPerGram, NanogramsPerGramTolerance); - Assert.Equal(MassFractionUnit.NanogramPerGram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFraction.Parse("1 ng/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanogramsPerKilogram, NanogramsPerKilogramTolerance); - Assert.Equal(MassFractionUnit.NanogramPerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFraction.Parse("1 ppb", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PartsPerBillion, PartsPerBillionTolerance); - Assert.Equal(MassFractionUnit.PartPerBillion, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFraction.Parse("1 ppm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PartsPerMillion, PartsPerMillionTolerance); - Assert.Equal(MassFractionUnit.PartPerMillion, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFraction.Parse("1 ‰", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PartsPerThousand, PartsPerThousandTolerance); - Assert.Equal(MassFractionUnit.PartPerThousand, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFraction.Parse("1 ppt", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PartsPerTrillion, PartsPerTrillionTolerance); - Assert.Equal(MassFractionUnit.PartPerTrillion, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFraction.Parse("1 %", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Percent, PercentTolerance); - Assert.Equal(MassFractionUnit.Percent, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassFraction.Parse("1 % (w/w)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Percent, PercentTolerance); - Assert.Equal(MassFractionUnit.Percent, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = MassFraction.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 cg/g", MassFractionUnit.CentigramPerGram, 4.2)] + [InlineData("en-US", "4.2 cg/kg", MassFractionUnit.CentigramPerKilogram, 4.2)] + [InlineData("en-US", "4.2 dag/g", MassFractionUnit.DecagramPerGram, 4.2)] + [InlineData("en-US", "4.2 dag/kg", MassFractionUnit.DecagramPerKilogram, 4.2)] + [InlineData("en-US", "4.2 dg/g", MassFractionUnit.DecigramPerGram, 4.2)] + [InlineData("en-US", "4.2 dg/kg", MassFractionUnit.DecigramPerKilogram, 4.2)] + [InlineData("en-US", "4.2 ", MassFractionUnit.DecimalFraction, 4.2)] + [InlineData("en-US", "4.2 g/g", MassFractionUnit.GramPerGram, 4.2)] + [InlineData("en-US", "4.2 g/kg", MassFractionUnit.GramPerKilogram, 4.2)] + [InlineData("en-US", "4.2 hg/g", MassFractionUnit.HectogramPerGram, 4.2)] + [InlineData("en-US", "4.2 hg/kg", MassFractionUnit.HectogramPerKilogram, 4.2)] + [InlineData("en-US", "4.2 kg/g", MassFractionUnit.KilogramPerGram, 4.2)] + [InlineData("en-US", "4.2 kg/kg", MassFractionUnit.KilogramPerKilogram, 4.2)] + [InlineData("en-US", "4.2 µg/g", MassFractionUnit.MicrogramPerGram, 4.2)] + [InlineData("en-US", "4.2 µg/kg", MassFractionUnit.MicrogramPerKilogram, 4.2)] + [InlineData("en-US", "4.2 mg/g", MassFractionUnit.MilligramPerGram, 4.2)] + [InlineData("en-US", "4.2 mg/kg", MassFractionUnit.MilligramPerKilogram, 4.2)] + [InlineData("en-US", "4.2 ng/g", MassFractionUnit.NanogramPerGram, 4.2)] + [InlineData("en-US", "4.2 ng/kg", MassFractionUnit.NanogramPerKilogram, 4.2)] + [InlineData("en-US", "4.2 ppb", MassFractionUnit.PartPerBillion, 4.2)] + [InlineData("en-US", "4.2 ppm", MassFractionUnit.PartPerMillion, 4.2)] + [InlineData("en-US", "4.2 ‰", MassFractionUnit.PartPerThousand, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(MassFraction.TryParse("1 cg/g", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentigramsPerGram, CentigramsPerGramTolerance); - Assert.Equal(MassFractionUnit.CentigramPerGram, parsed.Unit); - } - - { - Assert.True(MassFraction.TryParse("1 cg/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentigramsPerKilogram, CentigramsPerKilogramTolerance); - Assert.Equal(MassFractionUnit.CentigramPerKilogram, parsed.Unit); - } - - { - Assert.True(MassFraction.TryParse("1 dag/g", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecagramsPerGram, DecagramsPerGramTolerance); - Assert.Equal(MassFractionUnit.DecagramPerGram, parsed.Unit); - } - - { - Assert.True(MassFraction.TryParse("1 dag/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecagramsPerKilogram, DecagramsPerKilogramTolerance); - Assert.Equal(MassFractionUnit.DecagramPerKilogram, parsed.Unit); - } - - { - Assert.True(MassFraction.TryParse("1 dg/g", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecigramsPerGram, DecigramsPerGramTolerance); - Assert.Equal(MassFractionUnit.DecigramPerGram, parsed.Unit); - } - - { - Assert.True(MassFraction.TryParse("1 dg/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecigramsPerKilogram, DecigramsPerKilogramTolerance); - Assert.Equal(MassFractionUnit.DecigramPerKilogram, parsed.Unit); - } - - { - Assert.True(MassFraction.TryParse("1 ", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecimalFractions, DecimalFractionsTolerance); - Assert.Equal(MassFractionUnit.DecimalFraction, parsed.Unit); - } - - { - Assert.True(MassFraction.TryParse("1 g/g", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerGram, GramsPerGramTolerance); - Assert.Equal(MassFractionUnit.GramPerGram, parsed.Unit); - } - - { - Assert.True(MassFraction.TryParse("1 g/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerKilogram, GramsPerKilogramTolerance); - Assert.Equal(MassFractionUnit.GramPerKilogram, parsed.Unit); - } - - { - Assert.True(MassFraction.TryParse("1 hg/g", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HectogramsPerGram, HectogramsPerGramTolerance); - Assert.Equal(MassFractionUnit.HectogramPerGram, parsed.Unit); - } - - { - Assert.True(MassFraction.TryParse("1 hg/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HectogramsPerKilogram, HectogramsPerKilogramTolerance); - Assert.Equal(MassFractionUnit.HectogramPerKilogram, parsed.Unit); - } - - { - Assert.True(MassFraction.TryParse("1 kg/g", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerGram, KilogramsPerGramTolerance); - Assert.Equal(MassFractionUnit.KilogramPerGram, parsed.Unit); - } - - { - Assert.True(MassFraction.TryParse("1 kg/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerKilogram, KilogramsPerKilogramTolerance); - Assert.Equal(MassFractionUnit.KilogramPerKilogram, parsed.Unit); - } - - { - Assert.True(MassFraction.TryParse("1 µg/g", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerGram, MicrogramsPerGramTolerance); - Assert.Equal(MassFractionUnit.MicrogramPerGram, parsed.Unit); - } - - { - Assert.True(MassFraction.TryParse("1 µg/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerKilogram, MicrogramsPerKilogramTolerance); - Assert.Equal(MassFractionUnit.MicrogramPerKilogram, parsed.Unit); - } - - { - Assert.True(MassFraction.TryParse("1 mg/g", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligramsPerGram, MilligramsPerGramTolerance); - Assert.Equal(MassFractionUnit.MilligramPerGram, parsed.Unit); - } - - { - Assert.True(MassFraction.TryParse("1 mg/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligramsPerKilogram, MilligramsPerKilogramTolerance); - Assert.Equal(MassFractionUnit.MilligramPerKilogram, parsed.Unit); - } - - { - Assert.True(MassFraction.TryParse("1 ng/g", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanogramsPerGram, NanogramsPerGramTolerance); - Assert.Equal(MassFractionUnit.NanogramPerGram, parsed.Unit); - } - - { - Assert.True(MassFraction.TryParse("1 ng/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanogramsPerKilogram, NanogramsPerKilogramTolerance); - Assert.Equal(MassFractionUnit.NanogramPerKilogram, parsed.Unit); - } - - { - Assert.True(MassFraction.TryParse("1 ppb", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PartsPerBillion, PartsPerBillionTolerance); - Assert.Equal(MassFractionUnit.PartPerBillion, parsed.Unit); - } - - { - Assert.True(MassFraction.TryParse("1 ppm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PartsPerMillion, PartsPerMillionTolerance); - Assert.Equal(MassFractionUnit.PartPerMillion, parsed.Unit); - } - - { - Assert.True(MassFraction.TryParse("1 ‰", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PartsPerThousand, PartsPerThousandTolerance); - Assert.Equal(MassFractionUnit.PartPerThousand, parsed.Unit); - } - - { - Assert.True(MassFraction.TryParse("1 ppt", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PartsPerTrillion, PartsPerTrillionTolerance); - Assert.Equal(MassFractionUnit.PartPerTrillion, parsed.Unit); - } - - { - Assert.True(MassFraction.TryParse("1 %", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Percent, PercentTolerance); - Assert.Equal(MassFractionUnit.Percent, parsed.Unit); - } - - { - Assert.True(MassFraction.TryParse("1 % (w/w)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Percent, PercentTolerance); - Assert.Equal(MassFractionUnit.Percent, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(MassFraction.TryParse(quantityString, out MassFraction parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -1038,6 +789,50 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, MassFr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", MassFractionUnit.CentigramPerGram, "cg/g")] + [InlineData("en-US", MassFractionUnit.CentigramPerKilogram, "cg/kg")] + [InlineData("en-US", MassFractionUnit.DecagramPerGram, "dag/g")] + [InlineData("en-US", MassFractionUnit.DecagramPerKilogram, "dag/kg")] + [InlineData("en-US", MassFractionUnit.DecigramPerGram, "dg/g")] + [InlineData("en-US", MassFractionUnit.DecigramPerKilogram, "dg/kg")] + [InlineData("en-US", MassFractionUnit.DecimalFraction, "")] + [InlineData("en-US", MassFractionUnit.GramPerGram, "g/g")] + [InlineData("en-US", MassFractionUnit.GramPerKilogram, "g/kg")] + [InlineData("en-US", MassFractionUnit.HectogramPerGram, "hg/g")] + [InlineData("en-US", MassFractionUnit.HectogramPerKilogram, "hg/kg")] + [InlineData("en-US", MassFractionUnit.KilogramPerGram, "kg/g")] + [InlineData("en-US", MassFractionUnit.KilogramPerKilogram, "kg/kg")] + [InlineData("en-US", MassFractionUnit.MicrogramPerGram, "µg/g")] + [InlineData("en-US", MassFractionUnit.MicrogramPerKilogram, "µg/kg")] + [InlineData("en-US", MassFractionUnit.MilligramPerGram, "mg/g")] + [InlineData("en-US", MassFractionUnit.MilligramPerKilogram, "mg/kg")] + [InlineData("en-US", MassFractionUnit.NanogramPerGram, "ng/g")] + [InlineData("en-US", MassFractionUnit.NanogramPerKilogram, "ng/kg")] + [InlineData("en-US", MassFractionUnit.PartPerBillion, "ppb")] + [InlineData("en-US", MassFractionUnit.PartPerMillion, "ppm")] + [InlineData("en-US", MassFractionUnit.PartPerThousand, "‰")] + [InlineData("en-US", MassFractionUnit.PartPerTrillion, "ppt")] + [InlineData("en-US", MassFractionUnit.Percent, "%")] + public void GetAbbreviationForCulture(string culture, MassFractionUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = MassFraction.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(MassFraction.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = MassFraction.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(MassFractionUnit unit) @@ -1068,6 +863,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); }); } @@ -1091,55 +887,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] @@ -1185,8 +983,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); @@ -1223,23 +1019,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = MassFraction.FromDecimalFractions(1); - Assert.True(v.Equals(MassFraction.FromDecimalFractions(1), DecimalFractionsTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(MassFraction.Zero, DecimalFractionsTolerance, ComparisonType.Relative)); - Assert.True(MassFraction.FromDecimalFractions(100).Equals(MassFraction.FromDecimalFractions(120), 0.3, ComparisonType.Relative)); - Assert.False(MassFraction.FromDecimalFractions(100).Equals(MassFraction.FromDecimalFractions(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = MassFraction.FromDecimalFractions(1); - Assert.Throws(() => v.Equals(MassFraction.FromDecimalFractions(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1254,6 +1033,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(decimalfraction.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = MassFraction.FromDecimalFractions(1); + var negativeTolerance = MassFraction.FromDecimalFractions(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1270,6 +1075,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() { @@ -1374,158 +1191,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(MassFraction))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MassFractionUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal(MassFraction.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal(MassFraction.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal(new {MassFraction.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 ad82b4299b..e7ef0ea1db 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassMomentOfInertiaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassMomentOfInertiaTestsBase.g.cs @@ -204,7 +204,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new MassMomentOfInertia(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -217,15 +217,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void MassMomentOfInertia_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + MassMomentOfInertiaUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new MassMomentOfInertia(1, MassMomentOfInertiaUnit.KilogramSquareMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(MassMomentOfInertia.Zero, quantityInfo.Zero); Assert.Equal("MassMomentOfInertia", quantityInfo.Name); + Assert.Equal(MassMomentOfInertia.Zero, quantityInfo.Zero); + Assert.Equal(MassMomentOfInertia.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(MassMomentOfInertia.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -266,115 +284,115 @@ public void KilogramSquareMeterToMassMomentOfInertiaUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.GramSquareCentimeter); - AssertEx.EqualTolerance(1, quantity00.GramSquareCentimeters, GramSquareCentimetersTolerance); + Assert.Equal(1, quantity00.GramSquareCentimeters); Assert.Equal(MassMomentOfInertiaUnit.GramSquareCentimeter, quantity00.Unit); var quantity01 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.GramSquareDecimeter); - AssertEx.EqualTolerance(1, quantity01.GramSquareDecimeters, GramSquareDecimetersTolerance); + Assert.Equal(1, quantity01.GramSquareDecimeters); Assert.Equal(MassMomentOfInertiaUnit.GramSquareDecimeter, quantity01.Unit); var quantity02 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.GramSquareMeter); - AssertEx.EqualTolerance(1, quantity02.GramSquareMeters, GramSquareMetersTolerance); + Assert.Equal(1, quantity02.GramSquareMeters); Assert.Equal(MassMomentOfInertiaUnit.GramSquareMeter, quantity02.Unit); var quantity03 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.GramSquareMillimeter); - AssertEx.EqualTolerance(1, quantity03.GramSquareMillimeters, GramSquareMillimetersTolerance); + Assert.Equal(1, quantity03.GramSquareMillimeters); Assert.Equal(MassMomentOfInertiaUnit.GramSquareMillimeter, quantity03.Unit); var quantity04 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.KilogramSquareCentimeter); - AssertEx.EqualTolerance(1, quantity04.KilogramSquareCentimeters, KilogramSquareCentimetersTolerance); + Assert.Equal(1, quantity04.KilogramSquareCentimeters); Assert.Equal(MassMomentOfInertiaUnit.KilogramSquareCentimeter, quantity04.Unit); var quantity05 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.KilogramSquareDecimeter); - AssertEx.EqualTolerance(1, quantity05.KilogramSquareDecimeters, KilogramSquareDecimetersTolerance); + Assert.Equal(1, quantity05.KilogramSquareDecimeters); Assert.Equal(MassMomentOfInertiaUnit.KilogramSquareDecimeter, quantity05.Unit); var quantity06 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.KilogramSquareMeter); - AssertEx.EqualTolerance(1, quantity06.KilogramSquareMeters, KilogramSquareMetersTolerance); + Assert.Equal(1, quantity06.KilogramSquareMeters); Assert.Equal(MassMomentOfInertiaUnit.KilogramSquareMeter, quantity06.Unit); var quantity07 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.KilogramSquareMillimeter); - AssertEx.EqualTolerance(1, quantity07.KilogramSquareMillimeters, KilogramSquareMillimetersTolerance); + Assert.Equal(1, quantity07.KilogramSquareMillimeters); Assert.Equal(MassMomentOfInertiaUnit.KilogramSquareMillimeter, quantity07.Unit); var quantity08 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.KilotonneSquareCentimeter); - AssertEx.EqualTolerance(1, quantity08.KilotonneSquareCentimeters, KilotonneSquareCentimetersTolerance); + Assert.Equal(1, quantity08.KilotonneSquareCentimeters); Assert.Equal(MassMomentOfInertiaUnit.KilotonneSquareCentimeter, quantity08.Unit); var quantity09 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.KilotonneSquareDecimeter); - AssertEx.EqualTolerance(1, quantity09.KilotonneSquareDecimeters, KilotonneSquareDecimetersTolerance); + Assert.Equal(1, quantity09.KilotonneSquareDecimeters); Assert.Equal(MassMomentOfInertiaUnit.KilotonneSquareDecimeter, quantity09.Unit); var quantity10 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.KilotonneSquareMeter); - AssertEx.EqualTolerance(1, quantity10.KilotonneSquareMeters, KilotonneSquareMetersTolerance); + Assert.Equal(1, quantity10.KilotonneSquareMeters); Assert.Equal(MassMomentOfInertiaUnit.KilotonneSquareMeter, quantity10.Unit); var quantity11 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.KilotonneSquareMillimeter); - AssertEx.EqualTolerance(1, quantity11.KilotonneSquareMillimeters, KilotonneSquareMillimetersTolerance); + Assert.Equal(1, quantity11.KilotonneSquareMillimeters); Assert.Equal(MassMomentOfInertiaUnit.KilotonneSquareMillimeter, quantity11.Unit); var quantity12 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.MegatonneSquareCentimeter); - AssertEx.EqualTolerance(1, quantity12.MegatonneSquareCentimeters, MegatonneSquareCentimetersTolerance); + Assert.Equal(1, quantity12.MegatonneSquareCentimeters); Assert.Equal(MassMomentOfInertiaUnit.MegatonneSquareCentimeter, quantity12.Unit); var quantity13 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.MegatonneSquareDecimeter); - AssertEx.EqualTolerance(1, quantity13.MegatonneSquareDecimeters, MegatonneSquareDecimetersTolerance); + Assert.Equal(1, quantity13.MegatonneSquareDecimeters); Assert.Equal(MassMomentOfInertiaUnit.MegatonneSquareDecimeter, quantity13.Unit); var quantity14 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.MegatonneSquareMeter); - AssertEx.EqualTolerance(1, quantity14.MegatonneSquareMeters, MegatonneSquareMetersTolerance); + Assert.Equal(1, quantity14.MegatonneSquareMeters); Assert.Equal(MassMomentOfInertiaUnit.MegatonneSquareMeter, quantity14.Unit); var quantity15 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.MegatonneSquareMillimeter); - AssertEx.EqualTolerance(1, quantity15.MegatonneSquareMillimeters, MegatonneSquareMillimetersTolerance); + Assert.Equal(1, quantity15.MegatonneSquareMillimeters); Assert.Equal(MassMomentOfInertiaUnit.MegatonneSquareMillimeter, quantity15.Unit); var quantity16 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.MilligramSquareCentimeter); - AssertEx.EqualTolerance(1, quantity16.MilligramSquareCentimeters, MilligramSquareCentimetersTolerance); + Assert.Equal(1, quantity16.MilligramSquareCentimeters); Assert.Equal(MassMomentOfInertiaUnit.MilligramSquareCentimeter, quantity16.Unit); var quantity17 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.MilligramSquareDecimeter); - AssertEx.EqualTolerance(1, quantity17.MilligramSquareDecimeters, MilligramSquareDecimetersTolerance); + Assert.Equal(1, quantity17.MilligramSquareDecimeters); Assert.Equal(MassMomentOfInertiaUnit.MilligramSquareDecimeter, quantity17.Unit); var quantity18 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.MilligramSquareMeter); - AssertEx.EqualTolerance(1, quantity18.MilligramSquareMeters, MilligramSquareMetersTolerance); + Assert.Equal(1, quantity18.MilligramSquareMeters); Assert.Equal(MassMomentOfInertiaUnit.MilligramSquareMeter, quantity18.Unit); var quantity19 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.MilligramSquareMillimeter); - AssertEx.EqualTolerance(1, quantity19.MilligramSquareMillimeters, MilligramSquareMillimetersTolerance); + Assert.Equal(1, quantity19.MilligramSquareMillimeters); Assert.Equal(MassMomentOfInertiaUnit.MilligramSquareMillimeter, quantity19.Unit); var quantity20 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.PoundSquareFoot); - AssertEx.EqualTolerance(1, quantity20.PoundSquareFeet, PoundSquareFeetTolerance); + Assert.Equal(1, quantity20.PoundSquareFeet); Assert.Equal(MassMomentOfInertiaUnit.PoundSquareFoot, quantity20.Unit); var quantity21 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.PoundSquareInch); - AssertEx.EqualTolerance(1, quantity21.PoundSquareInches, PoundSquareInchesTolerance); + Assert.Equal(1, quantity21.PoundSquareInches); Assert.Equal(MassMomentOfInertiaUnit.PoundSquareInch, quantity21.Unit); var quantity22 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.SlugSquareFoot); - AssertEx.EqualTolerance(1, quantity22.SlugSquareFeet, SlugSquareFeetTolerance); + Assert.Equal(1, quantity22.SlugSquareFeet); Assert.Equal(MassMomentOfInertiaUnit.SlugSquareFoot, quantity22.Unit); var quantity23 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.SlugSquareInch); - AssertEx.EqualTolerance(1, quantity23.SlugSquareInches, SlugSquareInchesTolerance); + Assert.Equal(1, quantity23.SlugSquareInches); Assert.Equal(MassMomentOfInertiaUnit.SlugSquareInch, quantity23.Unit); var quantity24 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.TonneSquareCentimeter); - AssertEx.EqualTolerance(1, quantity24.TonneSquareCentimeters, TonneSquareCentimetersTolerance); + Assert.Equal(1, quantity24.TonneSquareCentimeters); Assert.Equal(MassMomentOfInertiaUnit.TonneSquareCentimeter, quantity24.Unit); var quantity25 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.TonneSquareDecimeter); - AssertEx.EqualTolerance(1, quantity25.TonneSquareDecimeters, TonneSquareDecimetersTolerance); + Assert.Equal(1, quantity25.TonneSquareDecimeters); Assert.Equal(MassMomentOfInertiaUnit.TonneSquareDecimeter, quantity25.Unit); var quantity26 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.TonneSquareMeter); - AssertEx.EqualTolerance(1, quantity26.TonneSquareMeters, TonneSquareMetersTolerance); + Assert.Equal(1, quantity26.TonneSquareMeters); Assert.Equal(MassMomentOfInertiaUnit.TonneSquareMeter, quantity26.Unit); var quantity27 = MassMomentOfInertia.From(1, MassMomentOfInertiaUnit.TonneSquareMillimeter); - AssertEx.EqualTolerance(1, quantity27.TonneSquareMillimeters, TonneSquareMillimetersTolerance); + Assert.Equal(1, quantity27.TonneSquareMillimeters); Assert.Equal(MassMomentOfInertiaUnit.TonneSquareMillimeter, quantity27.Unit); } @@ -537,378 +555,78 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 g·cm²", MassMomentOfInertiaUnit.GramSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 g·dm²", MassMomentOfInertiaUnit.GramSquareDecimeter, 4.2)] + [InlineData("en-US", "4.2 g·m²", MassMomentOfInertiaUnit.GramSquareMeter, 4.2)] + [InlineData("en-US", "4.2 g·mm²", MassMomentOfInertiaUnit.GramSquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 kg·cm²", MassMomentOfInertiaUnit.KilogramSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 kg·dm²", MassMomentOfInertiaUnit.KilogramSquareDecimeter, 4.2)] + [InlineData("en-US", "4.2 kg·m²", MassMomentOfInertiaUnit.KilogramSquareMeter, 4.2)] + [InlineData("en-US", "4.2 kg·mm²", MassMomentOfInertiaUnit.KilogramSquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 kt·cm²", MassMomentOfInertiaUnit.KilotonneSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 kt·dm²", MassMomentOfInertiaUnit.KilotonneSquareDecimeter, 4.2)] + [InlineData("en-US", "4.2 kt·m²", MassMomentOfInertiaUnit.KilotonneSquareMeter, 4.2)] + [InlineData("en-US", "4.2 kt·mm²", MassMomentOfInertiaUnit.KilotonneSquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 Mt·cm²", MassMomentOfInertiaUnit.MegatonneSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 Mt·dm²", MassMomentOfInertiaUnit.MegatonneSquareDecimeter, 4.2)] + [InlineData("en-US", "4.2 Mt·m²", MassMomentOfInertiaUnit.MegatonneSquareMeter, 4.2)] + [InlineData("en-US", "4.2 Mt·mm²", MassMomentOfInertiaUnit.MegatonneSquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 mg·cm²", MassMomentOfInertiaUnit.MilligramSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 mg·dm²", MassMomentOfInertiaUnit.MilligramSquareDecimeter, 4.2)] + [InlineData("en-US", "4.2 mg·m²", MassMomentOfInertiaUnit.MilligramSquareMeter, 4.2)] + [InlineData("en-US", "4.2 mg·mm²", MassMomentOfInertiaUnit.MilligramSquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 lb·ft²", MassMomentOfInertiaUnit.PoundSquareFoot, 4.2)] + [InlineData("en-US", "4.2 lb·in²", MassMomentOfInertiaUnit.PoundSquareInch, 4.2)] + [InlineData("en-US", "4.2 slug·ft²", MassMomentOfInertiaUnit.SlugSquareFoot, 4.2)] + [InlineData("en-US", "4.2 slug·in²", MassMomentOfInertiaUnit.SlugSquareInch, 4.2)] + [InlineData("en-US", "4.2 t·cm²", MassMomentOfInertiaUnit.TonneSquareCentimeter, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = MassMomentOfInertia.Parse("1 g·cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramSquareCentimeters, GramSquareCentimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.GramSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassMomentOfInertia.Parse("1 g·dm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramSquareDecimeters, GramSquareDecimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.GramSquareDecimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassMomentOfInertia.Parse("1 g·m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramSquareMeters, GramSquareMetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.GramSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassMomentOfInertia.Parse("1 g·mm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramSquareMillimeters, GramSquareMillimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.GramSquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassMomentOfInertia.Parse("1 kg·cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramSquareCentimeters, KilogramSquareCentimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilogramSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassMomentOfInertia.Parse("1 kg·dm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramSquareDecimeters, KilogramSquareDecimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilogramSquareDecimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassMomentOfInertia.Parse("1 kg·m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramSquareMeters, KilogramSquareMetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilogramSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassMomentOfInertia.Parse("1 kg·mm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramSquareMillimeters, KilogramSquareMillimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilogramSquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassMomentOfInertia.Parse("1 kt·cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilotonneSquareCentimeters, KilotonneSquareCentimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilotonneSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassMomentOfInertia.Parse("1 kt·dm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilotonneSquareDecimeters, KilotonneSquareDecimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilotonneSquareDecimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassMomentOfInertia.Parse("1 kt·m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilotonneSquareMeters, KilotonneSquareMetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilotonneSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassMomentOfInertia.Parse("1 kt·mm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilotonneSquareMillimeters, KilotonneSquareMillimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilotonneSquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassMomentOfInertia.Parse("1 Mt·cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegatonneSquareCentimeters, MegatonneSquareCentimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MegatonneSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassMomentOfInertia.Parse("1 Mt·dm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegatonneSquareDecimeters, MegatonneSquareDecimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MegatonneSquareDecimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassMomentOfInertia.Parse("1 Mt·m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegatonneSquareMeters, MegatonneSquareMetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MegatonneSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassMomentOfInertia.Parse("1 Mt·mm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegatonneSquareMillimeters, MegatonneSquareMillimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MegatonneSquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassMomentOfInertia.Parse("1 mg·cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligramSquareCentimeters, MilligramSquareCentimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MilligramSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassMomentOfInertia.Parse("1 mg·dm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligramSquareDecimeters, MilligramSquareDecimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MilligramSquareDecimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassMomentOfInertia.Parse("1 mg·m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligramSquareMeters, MilligramSquareMetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MilligramSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassMomentOfInertia.Parse("1 mg·mm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligramSquareMillimeters, MilligramSquareMillimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MilligramSquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassMomentOfInertia.Parse("1 lb·ft²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundSquareFeet, PoundSquareFeetTolerance); - Assert.Equal(MassMomentOfInertiaUnit.PoundSquareFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassMomentOfInertia.Parse("1 lb·in²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundSquareInches, PoundSquareInchesTolerance); - Assert.Equal(MassMomentOfInertiaUnit.PoundSquareInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassMomentOfInertia.Parse("1 slug·ft²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SlugSquareFeet, SlugSquareFeetTolerance); - Assert.Equal(MassMomentOfInertiaUnit.SlugSquareFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassMomentOfInertia.Parse("1 slug·in²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SlugSquareInches, SlugSquareInchesTolerance); - Assert.Equal(MassMomentOfInertiaUnit.SlugSquareInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassMomentOfInertia.Parse("1 t·cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonneSquareCentimeters, TonneSquareCentimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.TonneSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassMomentOfInertia.Parse("1 t·dm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonneSquareDecimeters, TonneSquareDecimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.TonneSquareDecimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassMomentOfInertia.Parse("1 t·m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonneSquareMeters, TonneSquareMetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.TonneSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MassMomentOfInertia.Parse("1 t·mm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonneSquareMillimeters, TonneSquareMillimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.TonneSquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = MassMomentOfInertia.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 g·cm²", MassMomentOfInertiaUnit.GramSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 g·dm²", MassMomentOfInertiaUnit.GramSquareDecimeter, 4.2)] + [InlineData("en-US", "4.2 g·m²", MassMomentOfInertiaUnit.GramSquareMeter, 4.2)] + [InlineData("en-US", "4.2 g·mm²", MassMomentOfInertiaUnit.GramSquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 kg·cm²", MassMomentOfInertiaUnit.KilogramSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 kg·dm²", MassMomentOfInertiaUnit.KilogramSquareDecimeter, 4.2)] + [InlineData("en-US", "4.2 kg·m²", MassMomentOfInertiaUnit.KilogramSquareMeter, 4.2)] + [InlineData("en-US", "4.2 kg·mm²", MassMomentOfInertiaUnit.KilogramSquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 kt·cm²", MassMomentOfInertiaUnit.KilotonneSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 kt·dm²", MassMomentOfInertiaUnit.KilotonneSquareDecimeter, 4.2)] + [InlineData("en-US", "4.2 kt·m²", MassMomentOfInertiaUnit.KilotonneSquareMeter, 4.2)] + [InlineData("en-US", "4.2 kt·mm²", MassMomentOfInertiaUnit.KilotonneSquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 Mt·cm²", MassMomentOfInertiaUnit.MegatonneSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 Mt·dm²", MassMomentOfInertiaUnit.MegatonneSquareDecimeter, 4.2)] + [InlineData("en-US", "4.2 Mt·m²", MassMomentOfInertiaUnit.MegatonneSquareMeter, 4.2)] + [InlineData("en-US", "4.2 Mt·mm²", MassMomentOfInertiaUnit.MegatonneSquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 mg·cm²", MassMomentOfInertiaUnit.MilligramSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 mg·dm²", MassMomentOfInertiaUnit.MilligramSquareDecimeter, 4.2)] + [InlineData("en-US", "4.2 mg·m²", MassMomentOfInertiaUnit.MilligramSquareMeter, 4.2)] + [InlineData("en-US", "4.2 mg·mm²", MassMomentOfInertiaUnit.MilligramSquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 lb·ft²", MassMomentOfInertiaUnit.PoundSquareFoot, 4.2)] + [InlineData("en-US", "4.2 lb·in²", MassMomentOfInertiaUnit.PoundSquareInch, 4.2)] + [InlineData("en-US", "4.2 slug·ft²", MassMomentOfInertiaUnit.SlugSquareFoot, 4.2)] + [InlineData("en-US", "4.2 slug·in²", MassMomentOfInertiaUnit.SlugSquareInch, 4.2)] + [InlineData("en-US", "4.2 t·cm²", MassMomentOfInertiaUnit.TonneSquareCentimeter, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(MassMomentOfInertia.TryParse("1 g·cm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramSquareCentimeters, GramSquareCentimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.GramSquareCentimeter, parsed.Unit); - } - - { - Assert.True(MassMomentOfInertia.TryParse("1 g·dm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramSquareDecimeters, GramSquareDecimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.GramSquareDecimeter, parsed.Unit); - } - - { - Assert.True(MassMomentOfInertia.TryParse("1 g·m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramSquareMeters, GramSquareMetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.GramSquareMeter, parsed.Unit); - } - - { - Assert.True(MassMomentOfInertia.TryParse("1 g·mm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramSquareMillimeters, GramSquareMillimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.GramSquareMillimeter, parsed.Unit); - } - - { - Assert.True(MassMomentOfInertia.TryParse("1 kg·cm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramSquareCentimeters, KilogramSquareCentimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilogramSquareCentimeter, parsed.Unit); - } - - { - Assert.True(MassMomentOfInertia.TryParse("1 kg·dm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramSquareDecimeters, KilogramSquareDecimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilogramSquareDecimeter, parsed.Unit); - } - - { - Assert.True(MassMomentOfInertia.TryParse("1 kg·m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramSquareMeters, KilogramSquareMetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilogramSquareMeter, parsed.Unit); - } - - { - Assert.True(MassMomentOfInertia.TryParse("1 kg·mm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramSquareMillimeters, KilogramSquareMillimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilogramSquareMillimeter, parsed.Unit); - } - - { - Assert.True(MassMomentOfInertia.TryParse("1 kt·cm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilotonneSquareCentimeters, KilotonneSquareCentimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilotonneSquareCentimeter, parsed.Unit); - } - - { - Assert.True(MassMomentOfInertia.TryParse("1 kt·dm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilotonneSquareDecimeters, KilotonneSquareDecimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilotonneSquareDecimeter, parsed.Unit); - } - - { - Assert.True(MassMomentOfInertia.TryParse("1 kt·m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilotonneSquareMeters, KilotonneSquareMetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilotonneSquareMeter, parsed.Unit); - } - - { - Assert.True(MassMomentOfInertia.TryParse("1 kt·mm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilotonneSquareMillimeters, KilotonneSquareMillimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.KilotonneSquareMillimeter, parsed.Unit); - } - - { - Assert.True(MassMomentOfInertia.TryParse("1 Mt·cm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegatonneSquareCentimeters, MegatonneSquareCentimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MegatonneSquareCentimeter, parsed.Unit); - } - - { - Assert.True(MassMomentOfInertia.TryParse("1 Mt·dm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegatonneSquareDecimeters, MegatonneSquareDecimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MegatonneSquareDecimeter, parsed.Unit); - } - - { - Assert.True(MassMomentOfInertia.TryParse("1 Mt·m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegatonneSquareMeters, MegatonneSquareMetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MegatonneSquareMeter, parsed.Unit); - } - - { - Assert.True(MassMomentOfInertia.TryParse("1 Mt·mm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegatonneSquareMillimeters, MegatonneSquareMillimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MegatonneSquareMillimeter, parsed.Unit); - } - - { - Assert.True(MassMomentOfInertia.TryParse("1 mg·cm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligramSquareCentimeters, MilligramSquareCentimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MilligramSquareCentimeter, parsed.Unit); - } - - { - Assert.True(MassMomentOfInertia.TryParse("1 mg·dm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligramSquareDecimeters, MilligramSquareDecimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MilligramSquareDecimeter, parsed.Unit); - } - - { - Assert.True(MassMomentOfInertia.TryParse("1 mg·m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligramSquareMeters, MilligramSquareMetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MilligramSquareMeter, parsed.Unit); - } - - { - Assert.True(MassMomentOfInertia.TryParse("1 mg·mm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligramSquareMillimeters, MilligramSquareMillimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.MilligramSquareMillimeter, parsed.Unit); - } - - { - Assert.True(MassMomentOfInertia.TryParse("1 lb·ft²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundSquareFeet, PoundSquareFeetTolerance); - Assert.Equal(MassMomentOfInertiaUnit.PoundSquareFoot, parsed.Unit); - } - - { - Assert.True(MassMomentOfInertia.TryParse("1 lb·in²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundSquareInches, PoundSquareInchesTolerance); - Assert.Equal(MassMomentOfInertiaUnit.PoundSquareInch, parsed.Unit); - } - - { - Assert.True(MassMomentOfInertia.TryParse("1 slug·ft²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SlugSquareFeet, SlugSquareFeetTolerance); - Assert.Equal(MassMomentOfInertiaUnit.SlugSquareFoot, parsed.Unit); - } - - { - Assert.True(MassMomentOfInertia.TryParse("1 slug·in²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SlugSquareInches, SlugSquareInchesTolerance); - Assert.Equal(MassMomentOfInertiaUnit.SlugSquareInch, parsed.Unit); - } - - { - Assert.True(MassMomentOfInertia.TryParse("1 t·cm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonneSquareCentimeters, TonneSquareCentimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.TonneSquareCentimeter, parsed.Unit); - } - - { - Assert.True(MassMomentOfInertia.TryParse("1 t·dm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonneSquareDecimeters, TonneSquareDecimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.TonneSquareDecimeter, parsed.Unit); - } - - { - Assert.True(MassMomentOfInertia.TryParse("1 t·m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonneSquareMeters, TonneSquareMetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.TonneSquareMeter, parsed.Unit); - } - - { - Assert.True(MassMomentOfInertia.TryParse("1 t·mm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonneSquareMillimeters, TonneSquareMillimetersTolerance); - Assert.Equal(MassMomentOfInertiaUnit.TonneSquareMillimeter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(MassMomentOfInertia.TryParse(quantityString, out MassMomentOfInertia parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -1201,6 +919,54 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, MassMo Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", MassMomentOfInertiaUnit.GramSquareCentimeter, "g·cm²")] + [InlineData("en-US", MassMomentOfInertiaUnit.GramSquareDecimeter, "g·dm²")] + [InlineData("en-US", MassMomentOfInertiaUnit.GramSquareMeter, "g·m²")] + [InlineData("en-US", MassMomentOfInertiaUnit.GramSquareMillimeter, "g·mm²")] + [InlineData("en-US", MassMomentOfInertiaUnit.KilogramSquareCentimeter, "kg·cm²")] + [InlineData("en-US", MassMomentOfInertiaUnit.KilogramSquareDecimeter, "kg·dm²")] + [InlineData("en-US", MassMomentOfInertiaUnit.KilogramSquareMeter, "kg·m²")] + [InlineData("en-US", MassMomentOfInertiaUnit.KilogramSquareMillimeter, "kg·mm²")] + [InlineData("en-US", MassMomentOfInertiaUnit.KilotonneSquareCentimeter, "kt·cm²")] + [InlineData("en-US", MassMomentOfInertiaUnit.KilotonneSquareDecimeter, "kt·dm²")] + [InlineData("en-US", MassMomentOfInertiaUnit.KilotonneSquareMeter, "kt·m²")] + [InlineData("en-US", MassMomentOfInertiaUnit.KilotonneSquareMillimeter, "kt·mm²")] + [InlineData("en-US", MassMomentOfInertiaUnit.MegatonneSquareCentimeter, "Mt·cm²")] + [InlineData("en-US", MassMomentOfInertiaUnit.MegatonneSquareDecimeter, "Mt·dm²")] + [InlineData("en-US", MassMomentOfInertiaUnit.MegatonneSquareMeter, "Mt·m²")] + [InlineData("en-US", MassMomentOfInertiaUnit.MegatonneSquareMillimeter, "Mt·mm²")] + [InlineData("en-US", MassMomentOfInertiaUnit.MilligramSquareCentimeter, "mg·cm²")] + [InlineData("en-US", MassMomentOfInertiaUnit.MilligramSquareDecimeter, "mg·dm²")] + [InlineData("en-US", MassMomentOfInertiaUnit.MilligramSquareMeter, "mg·m²")] + [InlineData("en-US", MassMomentOfInertiaUnit.MilligramSquareMillimeter, "mg·mm²")] + [InlineData("en-US", MassMomentOfInertiaUnit.PoundSquareFoot, "lb·ft²")] + [InlineData("en-US", MassMomentOfInertiaUnit.PoundSquareInch, "lb·in²")] + [InlineData("en-US", MassMomentOfInertiaUnit.SlugSquareFoot, "slug·ft²")] + [InlineData("en-US", MassMomentOfInertiaUnit.SlugSquareInch, "slug·in²")] + [InlineData("en-US", MassMomentOfInertiaUnit.TonneSquareCentimeter, "t·cm²")] + [InlineData("en-US", MassMomentOfInertiaUnit.TonneSquareDecimeter, "t·dm²")] + [InlineData("en-US", MassMomentOfInertiaUnit.TonneSquareMeter, "t·m²")] + [InlineData("en-US", MassMomentOfInertiaUnit.TonneSquareMillimeter, "t·mm²")] + public void GetAbbreviationForCulture(string culture, MassMomentOfInertiaUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = MassMomentOfInertia.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(MassMomentOfInertia.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = MassMomentOfInertia.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(MassMomentOfInertiaUnit unit) @@ -1231,6 +997,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); }); } @@ -1254,59 +1021,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] @@ -1352,8 +1121,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); @@ -1390,23 +1157,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = MassMomentOfInertia.FromKilogramSquareMeters(1); - Assert.True(v.Equals(MassMomentOfInertia.FromKilogramSquareMeters(1), KilogramSquareMetersTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(MassMomentOfInertia.Zero, KilogramSquareMetersTolerance, ComparisonType.Relative)); - Assert.True(MassMomentOfInertia.FromKilogramSquareMeters(100).Equals(MassMomentOfInertia.FromKilogramSquareMeters(120), 0.3, ComparisonType.Relative)); - Assert.False(MassMomentOfInertia.FromKilogramSquareMeters(100).Equals(MassMomentOfInertia.FromKilogramSquareMeters(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = MassMomentOfInertia.FromKilogramSquareMeters(1); - Assert.Throws(() => v.Equals(MassMomentOfInertia.FromKilogramSquareMeters(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1421,6 +1171,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(kilogramsquaremeter.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1); + var negativeTolerance = MassMomentOfInertia.FromKilogramSquareMeters(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1437,6 +1213,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() { @@ -1549,158 +1337,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(MassMomentOfInertia))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MassMomentOfInertiaUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal(MassMomentOfInertia.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal(MassMomentOfInertia.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal(new {MassMomentOfInertia.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 9fcebac55b..a44bf46599 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassTestsBase.g.cs @@ -200,7 +200,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Mass(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -213,15 +213,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Mass_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + MassUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Mass(1, MassUnit.Kilogram); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Mass.Zero, quantityInfo.Zero); Assert.Equal("Mass", quantityInfo.Name); + Assert.Equal(Mass.Zero, quantityInfo.Zero); + Assert.Equal(Mass.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Mass.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -261,111 +279,111 @@ public void KilogramToMassUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Mass.From(1, MassUnit.Centigram); - AssertEx.EqualTolerance(1, quantity00.Centigrams, CentigramsTolerance); + Assert.Equal(1, quantity00.Centigrams); Assert.Equal(MassUnit.Centigram, quantity00.Unit); var quantity01 = Mass.From(1, MassUnit.Decagram); - AssertEx.EqualTolerance(1, quantity01.Decagrams, DecagramsTolerance); + Assert.Equal(1, quantity01.Decagrams); Assert.Equal(MassUnit.Decagram, quantity01.Unit); var quantity02 = Mass.From(1, MassUnit.Decigram); - AssertEx.EqualTolerance(1, quantity02.Decigrams, DecigramsTolerance); + Assert.Equal(1, quantity02.Decigrams); Assert.Equal(MassUnit.Decigram, quantity02.Unit); var quantity03 = Mass.From(1, MassUnit.EarthMass); - AssertEx.EqualTolerance(1, quantity03.EarthMasses, EarthMassesTolerance); + Assert.Equal(1, quantity03.EarthMasses); Assert.Equal(MassUnit.EarthMass, quantity03.Unit); var quantity04 = Mass.From(1, MassUnit.Femtogram); - AssertEx.EqualTolerance(1, quantity04.Femtograms, FemtogramsTolerance); + Assert.Equal(1, quantity04.Femtograms); Assert.Equal(MassUnit.Femtogram, quantity04.Unit); var quantity05 = Mass.From(1, MassUnit.Grain); - AssertEx.EqualTolerance(1, quantity05.Grains, GrainsTolerance); + Assert.Equal(1, quantity05.Grains); Assert.Equal(MassUnit.Grain, quantity05.Unit); var quantity06 = Mass.From(1, MassUnit.Gram); - AssertEx.EqualTolerance(1, quantity06.Grams, GramsTolerance); + Assert.Equal(1, quantity06.Grams); Assert.Equal(MassUnit.Gram, quantity06.Unit); var quantity07 = Mass.From(1, MassUnit.Hectogram); - AssertEx.EqualTolerance(1, quantity07.Hectograms, HectogramsTolerance); + Assert.Equal(1, quantity07.Hectograms); Assert.Equal(MassUnit.Hectogram, quantity07.Unit); var quantity08 = Mass.From(1, MassUnit.Kilogram); - AssertEx.EqualTolerance(1, quantity08.Kilograms, KilogramsTolerance); + Assert.Equal(1, quantity08.Kilograms); Assert.Equal(MassUnit.Kilogram, quantity08.Unit); var quantity09 = Mass.From(1, MassUnit.Kilopound); - AssertEx.EqualTolerance(1, quantity09.Kilopounds, KilopoundsTolerance); + Assert.Equal(1, quantity09.Kilopounds); Assert.Equal(MassUnit.Kilopound, quantity09.Unit); var quantity10 = Mass.From(1, MassUnit.Kilotonne); - AssertEx.EqualTolerance(1, quantity10.Kilotonnes, KilotonnesTolerance); + Assert.Equal(1, quantity10.Kilotonnes); Assert.Equal(MassUnit.Kilotonne, quantity10.Unit); var quantity11 = Mass.From(1, MassUnit.LongHundredweight); - AssertEx.EqualTolerance(1, quantity11.LongHundredweight, LongHundredweightTolerance); + Assert.Equal(1, quantity11.LongHundredweight); Assert.Equal(MassUnit.LongHundredweight, quantity11.Unit); var quantity12 = Mass.From(1, MassUnit.LongTon); - AssertEx.EqualTolerance(1, quantity12.LongTons, LongTonsTolerance); + Assert.Equal(1, quantity12.LongTons); Assert.Equal(MassUnit.LongTon, quantity12.Unit); var quantity13 = Mass.From(1, MassUnit.Megapound); - AssertEx.EqualTolerance(1, quantity13.Megapounds, MegapoundsTolerance); + Assert.Equal(1, quantity13.Megapounds); Assert.Equal(MassUnit.Megapound, quantity13.Unit); var quantity14 = Mass.From(1, MassUnit.Megatonne); - AssertEx.EqualTolerance(1, quantity14.Megatonnes, MegatonnesTolerance); + Assert.Equal(1, quantity14.Megatonnes); Assert.Equal(MassUnit.Megatonne, quantity14.Unit); var quantity15 = Mass.From(1, MassUnit.Microgram); - AssertEx.EqualTolerance(1, quantity15.Micrograms, MicrogramsTolerance); + Assert.Equal(1, quantity15.Micrograms); Assert.Equal(MassUnit.Microgram, quantity15.Unit); var quantity16 = Mass.From(1, MassUnit.Milligram); - AssertEx.EqualTolerance(1, quantity16.Milligrams, MilligramsTolerance); + Assert.Equal(1, quantity16.Milligrams); Assert.Equal(MassUnit.Milligram, quantity16.Unit); var quantity17 = Mass.From(1, MassUnit.Nanogram); - AssertEx.EqualTolerance(1, quantity17.Nanograms, NanogramsTolerance); + Assert.Equal(1, quantity17.Nanograms); Assert.Equal(MassUnit.Nanogram, quantity17.Unit); var quantity18 = Mass.From(1, MassUnit.Ounce); - AssertEx.EqualTolerance(1, quantity18.Ounces, OuncesTolerance); + Assert.Equal(1, quantity18.Ounces); Assert.Equal(MassUnit.Ounce, quantity18.Unit); var quantity19 = Mass.From(1, MassUnit.Picogram); - AssertEx.EqualTolerance(1, quantity19.Picograms, PicogramsTolerance); + Assert.Equal(1, quantity19.Picograms); Assert.Equal(MassUnit.Picogram, quantity19.Unit); var quantity20 = Mass.From(1, MassUnit.Pound); - AssertEx.EqualTolerance(1, quantity20.Pounds, PoundsTolerance); + Assert.Equal(1, quantity20.Pounds); Assert.Equal(MassUnit.Pound, quantity20.Unit); var quantity21 = Mass.From(1, MassUnit.ShortHundredweight); - AssertEx.EqualTolerance(1, quantity21.ShortHundredweight, ShortHundredweightTolerance); + Assert.Equal(1, quantity21.ShortHundredweight); Assert.Equal(MassUnit.ShortHundredweight, quantity21.Unit); var quantity22 = Mass.From(1, MassUnit.ShortTon); - AssertEx.EqualTolerance(1, quantity22.ShortTons, ShortTonsTolerance); + Assert.Equal(1, quantity22.ShortTons); Assert.Equal(MassUnit.ShortTon, quantity22.Unit); var quantity23 = Mass.From(1, MassUnit.Slug); - AssertEx.EqualTolerance(1, quantity23.Slugs, SlugsTolerance); + Assert.Equal(1, quantity23.Slugs); Assert.Equal(MassUnit.Slug, quantity23.Unit); var quantity24 = Mass.From(1, MassUnit.SolarMass); - AssertEx.EqualTolerance(1, quantity24.SolarMasses, SolarMassesTolerance); + Assert.Equal(1, quantity24.SolarMasses); Assert.Equal(MassUnit.SolarMass, quantity24.Unit); var quantity25 = Mass.From(1, MassUnit.Stone); - AssertEx.EqualTolerance(1, quantity25.Stone, StoneTolerance); + Assert.Equal(1, quantity25.Stone); Assert.Equal(MassUnit.Stone, quantity25.Unit); var quantity26 = Mass.From(1, MassUnit.Tonne); - AssertEx.EqualTolerance(1, quantity26.Tonnes, TonnesTolerance); + Assert.Equal(1, quantity26.Tonnes); Assert.Equal(MassUnit.Tonne, quantity26.Unit); } @@ -436,1056 +454,273 @@ public virtual void As_UnitSystem_SI_ReturnsQuantityInSIUnits() var convertedValue = quantity.As(UnitSystem.SI); - Assert.Equal(expectedValue, convertedValue); - } - - [Fact] - public void As_UnitSystem_ThrowsArgumentNullExceptionIfNull() - { - var quantity = new Mass(value: 1, unit: Mass.BaseUnit); - UnitSystem nullUnitSystem = null!; - Assert.Throws(() => quantity.As(nullUnitSystem)); - } - - [Fact] - public void As_UnitSystem_ThrowsArgumentExceptionIfNotSupported() - { - var quantity = new Mass(value: 1, unit: Mass.BaseUnit); - var unsupportedUnitSystem = new UnitSystem(UnsupportedBaseUnits); - Assert.Throws(() => quantity.As(unsupportedUnitSystem)); - } - - [Fact] - public virtual void ToUnit_UnitSystem_SI_ReturnsQuantityInSIUnits() - { - var quantity = new Mass(value: 1, unit: Mass.BaseUnit); - var expectedUnit = Mass.Info.GetDefaultUnit(UnitSystem.SI); - var expectedValue = quantity.As(expectedUnit); - - Assert.Multiple(() => - { - Mass quantityToConvert = quantity; - - Mass convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); - - Assert.Equal(expectedUnit, convertedQuantity.Unit); - Assert.Equal(expectedValue, convertedQuantity.Value); - }, () => - { - IQuantity quantityToConvert = quantity; - - IQuantity convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); - - Assert.Equal(expectedUnit, convertedQuantity.Unit); - Assert.Equal(expectedValue, convertedQuantity.Value); - }, () => - { - IQuantity quantityToConvert = quantity; - - IQuantity convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); - - Assert.Equal(expectedUnit, convertedQuantity.Unit); - Assert.Equal(expectedValue, convertedQuantity.Value); - }); - } - - [Fact] - public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() - { - UnitSystem nullUnitSystem = null!; - Assert.Multiple(() => - { - var quantity = new Mass(value: 1, unit: Mass.BaseUnit); - Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); - }, () => - { - IQuantity quantity = new Mass(value: 1, unit: Mass.BaseUnit); - Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); - }, () => - { - IQuantity quantity = new Mass(value: 1, unit: Mass.BaseUnit); - Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); - }); - } - - [Fact] - public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() - { - var unsupportedUnitSystem = new UnitSystem(UnsupportedBaseUnits); - Assert.Multiple(() => - { - var quantity = new Mass(value: 1, unit: Mass.BaseUnit); - Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); - }, () => - { - IQuantity quantity = new Mass(value: 1, unit: Mass.BaseUnit); - Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); - }, () => - { - IQuantity quantity = new Mass(value: 1, unit: Mass.BaseUnit); - Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); - }); - } - - [Fact] - public void Parse() - { - try - { - var parsed = Mass.Parse("1 cg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Centigrams, CentigramsTolerance); - Assert.Equal(MassUnit.Centigram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 сг", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Centigrams, CentigramsTolerance); - Assert.Equal(MassUnit.Centigram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 厘克", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Centigrams, CentigramsTolerance); - Assert.Equal(MassUnit.Centigram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 dag", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Decagrams, DecagramsTolerance); - Assert.Equal(MassUnit.Decagram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 даг", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Decagrams, DecagramsTolerance); - Assert.Equal(MassUnit.Decagram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 十克", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Decagrams, DecagramsTolerance); - Assert.Equal(MassUnit.Decagram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 dg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Decigrams, DecigramsTolerance); - Assert.Equal(MassUnit.Decigram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 дг", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Decigrams, DecigramsTolerance); - Assert.Equal(MassUnit.Decigram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 分克", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Decigrams, DecigramsTolerance); - Assert.Equal(MassUnit.Decigram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 em", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.EarthMasses, EarthMassesTolerance); - Assert.Equal(MassUnit.EarthMass, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 fg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Femtograms, FemtogramsTolerance); - Assert.Equal(MassUnit.Femtogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 фг", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Femtograms, FemtogramsTolerance); - Assert.Equal(MassUnit.Femtogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 飞克", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Femtograms, FemtogramsTolerance); - Assert.Equal(MassUnit.Femtogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 gr", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Grains, GrainsTolerance); - Assert.Equal(MassUnit.Grain, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 g", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Grams, GramsTolerance); - Assert.Equal(MassUnit.Gram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 г", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Grams, GramsTolerance); - Assert.Equal(MassUnit.Gram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 克", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Grams, GramsTolerance); - Assert.Equal(MassUnit.Gram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 hg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Hectograms, HectogramsTolerance); - Assert.Equal(MassUnit.Hectogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 гг", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Hectograms, HectogramsTolerance); - Assert.Equal(MassUnit.Hectogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 百克", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Hectograms, HectogramsTolerance); - Assert.Equal(MassUnit.Hectogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilograms, KilogramsTolerance); - Assert.Equal(MassUnit.Kilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 кг", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Kilograms, KilogramsTolerance); - Assert.Equal(MassUnit.Kilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 千克", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Kilograms, KilogramsTolerance); - Assert.Equal(MassUnit.Kilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 klb", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilopounds, KilopoundsTolerance); - Assert.Equal(MassUnit.Kilopound, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 klbs", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilopounds, KilopoundsTolerance); - Assert.Equal(MassUnit.Kilopound, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 klbm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilopounds, KilopoundsTolerance); - Assert.Equal(MassUnit.Kilopound, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 кфунт", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Kilopounds, KilopoundsTolerance); - Assert.Equal(MassUnit.Kilopound, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 千磅", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Kilopounds, KilopoundsTolerance); - Assert.Equal(MassUnit.Kilopound, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 kt", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilotonnes, KilotonnesTolerance); - Assert.Equal(MassUnit.Kilotonne, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 кт", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Kilotonnes, KilotonnesTolerance); - Assert.Equal(MassUnit.Kilotonne, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 千吨", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Kilotonnes, KilotonnesTolerance); - Assert.Equal(MassUnit.Kilotonne, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 cwt", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.LongHundredweight, LongHundredweightTolerance); - Assert.Equal(MassUnit.LongHundredweight, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 long tn", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.LongTons, LongTonsTolerance); - Assert.Equal(MassUnit.LongTon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 тонна большая", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.LongTons, LongTonsTolerance); - Assert.Equal(MassUnit.LongTon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 长吨", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.LongTons, LongTonsTolerance); - Assert.Equal(MassUnit.LongTon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 Mlb", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megapounds, MegapoundsTolerance); - Assert.Equal(MassUnit.Megapound, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 Mlbs", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megapounds, MegapoundsTolerance); - Assert.Equal(MassUnit.Megapound, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 Mlbm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megapounds, MegapoundsTolerance); - Assert.Equal(MassUnit.Megapound, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 Мфунт", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Megapounds, MegapoundsTolerance); - Assert.Equal(MassUnit.Megapound, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 兆磅", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Megapounds, MegapoundsTolerance); - Assert.Equal(MassUnit.Megapound, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 Mt", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megatonnes, MegatonnesTolerance); - Assert.Equal(MassUnit.Megatonne, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 Мт", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Megatonnes, MegatonnesTolerance); - Assert.Equal(MassUnit.Megatonne, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 兆吨", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Megatonnes, MegatonnesTolerance); - Assert.Equal(MassUnit.Megatonne, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 µg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Micrograms, MicrogramsTolerance); - Assert.Equal(MassUnit.Microgram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 мкг", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Micrograms, MicrogramsTolerance); - Assert.Equal(MassUnit.Microgram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 微克", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Micrograms, MicrogramsTolerance); - Assert.Equal(MassUnit.Microgram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 mg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Milligrams, MilligramsTolerance); - Assert.Equal(MassUnit.Milligram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 мг", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Milligrams, MilligramsTolerance); - Assert.Equal(MassUnit.Milligram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 毫克", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Milligrams, MilligramsTolerance); - Assert.Equal(MassUnit.Milligram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 ng", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanograms, NanogramsTolerance); - Assert.Equal(MassUnit.Nanogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 нг", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Nanograms, NanogramsTolerance); - Assert.Equal(MassUnit.Nanogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 纳克", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Nanograms, NanogramsTolerance); - Assert.Equal(MassUnit.Nanogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 oz", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Ounces, OuncesTolerance); - Assert.Equal(MassUnit.Ounce, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 盎司", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Ounces, OuncesTolerance); - Assert.Equal(MassUnit.Ounce, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 pg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Picograms, PicogramsTolerance); - Assert.Equal(MassUnit.Picogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 пг", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Picograms, PicogramsTolerance); - Assert.Equal(MassUnit.Picogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 皮克", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Picograms, PicogramsTolerance); - Assert.Equal(MassUnit.Picogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 lb", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Pounds, PoundsTolerance); - Assert.Equal(MassUnit.Pound, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 lbs", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Pounds, PoundsTolerance); - Assert.Equal(MassUnit.Pound, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 lbm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Pounds, PoundsTolerance); - Assert.Equal(MassUnit.Pound, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 фунт", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Pounds, PoundsTolerance); - Assert.Equal(MassUnit.Pound, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 磅", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Pounds, PoundsTolerance); - Assert.Equal(MassUnit.Pound, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 cwt", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ShortHundredweight, ShortHundredweightTolerance); - Assert.Equal(MassUnit.ShortHundredweight, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 t (short)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ShortTons, ShortTonsTolerance); - Assert.Equal(MassUnit.ShortTon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 short tn", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ShortTons, ShortTonsTolerance); - Assert.Equal(MassUnit.ShortTon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 ST", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ShortTons, ShortTonsTolerance); - Assert.Equal(MassUnit.ShortTon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 тонна малая", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.ShortTons, ShortTonsTolerance); - Assert.Equal(MassUnit.ShortTon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 短吨", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.ShortTons, ShortTonsTolerance); - Assert.Equal(MassUnit.ShortTon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 slug", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Slugs, SlugsTolerance); - Assert.Equal(MassUnit.Slug, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 M☉", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SolarMasses, SolarMassesTolerance); - Assert.Equal(MassUnit.SolarMass, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 M⊙", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SolarMasses, SolarMassesTolerance); - Assert.Equal(MassUnit.SolarMass, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 st", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Stone, StoneTolerance); - Assert.Equal(MassUnit.Stone, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 t", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Tonnes, TonnesTolerance); - Assert.Equal(MassUnit.Tonne, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 т", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Tonnes, TonnesTolerance); - Assert.Equal(MassUnit.Tonne, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Mass.Parse("1 吨", CultureInfo.GetCultureInfo("zh-CN")); - AssertEx.EqualTolerance(1, parsed.Tonnes, TonnesTolerance); - Assert.Equal(MassUnit.Tonne, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - } - - [Fact] - public void TryParse() - { - { - Assert.True(Mass.TryParse("1 cg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Centigrams, CentigramsTolerance); - Assert.Equal(MassUnit.Centigram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 сг", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Centigrams, CentigramsTolerance); - Assert.Equal(MassUnit.Centigram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 厘克", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Centigrams, CentigramsTolerance); - Assert.Equal(MassUnit.Centigram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 dag", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Decagrams, DecagramsTolerance); - Assert.Equal(MassUnit.Decagram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 даг", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Decagrams, DecagramsTolerance); - Assert.Equal(MassUnit.Decagram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 十克", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Decagrams, DecagramsTolerance); - Assert.Equal(MassUnit.Decagram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 dg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Decigrams, DecigramsTolerance); - Assert.Equal(MassUnit.Decigram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 дг", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Decigrams, DecigramsTolerance); - Assert.Equal(MassUnit.Decigram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 分克", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Decigrams, DecigramsTolerance); - Assert.Equal(MassUnit.Decigram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 em", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.EarthMasses, EarthMassesTolerance); - Assert.Equal(MassUnit.EarthMass, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 fg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Femtograms, FemtogramsTolerance); - Assert.Equal(MassUnit.Femtogram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 фг", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Femtograms, FemtogramsTolerance); - Assert.Equal(MassUnit.Femtogram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 飞克", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Femtograms, FemtogramsTolerance); - Assert.Equal(MassUnit.Femtogram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 gr", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Grains, GrainsTolerance); - Assert.Equal(MassUnit.Grain, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 g", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Grams, GramsTolerance); - Assert.Equal(MassUnit.Gram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 г", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Grams, GramsTolerance); - Assert.Equal(MassUnit.Gram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 克", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Grams, GramsTolerance); - Assert.Equal(MassUnit.Gram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 hg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Hectograms, HectogramsTolerance); - Assert.Equal(MassUnit.Hectogram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 гг", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Hectograms, HectogramsTolerance); - Assert.Equal(MassUnit.Hectogram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 百克", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Hectograms, HectogramsTolerance); - Assert.Equal(MassUnit.Hectogram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilograms, KilogramsTolerance); - Assert.Equal(MassUnit.Kilogram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 кг", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilograms, KilogramsTolerance); - Assert.Equal(MassUnit.Kilogram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 千克", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilograms, KilogramsTolerance); - Assert.Equal(MassUnit.Kilogram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 klb", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilopounds, KilopoundsTolerance); - Assert.Equal(MassUnit.Kilopound, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 klbs", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilopounds, KilopoundsTolerance); - Assert.Equal(MassUnit.Kilopound, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 klbm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilopounds, KilopoundsTolerance); - Assert.Equal(MassUnit.Kilopound, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 кфунт", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilopounds, KilopoundsTolerance); - Assert.Equal(MassUnit.Kilopound, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 千磅", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilopounds, KilopoundsTolerance); - Assert.Equal(MassUnit.Kilopound, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 kt", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilotonnes, KilotonnesTolerance); - Assert.Equal(MassUnit.Kilotonne, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 кт", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilotonnes, KilotonnesTolerance); - Assert.Equal(MassUnit.Kilotonne, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 千吨", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilotonnes, KilotonnesTolerance); - Assert.Equal(MassUnit.Kilotonne, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 long tn", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.LongTons, LongTonsTolerance); - Assert.Equal(MassUnit.LongTon, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 тонна большая", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.LongTons, LongTonsTolerance); - Assert.Equal(MassUnit.LongTon, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 长吨", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.LongTons, LongTonsTolerance); - Assert.Equal(MassUnit.LongTon, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 Mlb", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Megapounds, MegapoundsTolerance); - Assert.Equal(MassUnit.Megapound, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 Mlbs", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Megapounds, MegapoundsTolerance); - Assert.Equal(MassUnit.Megapound, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 Mlbm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Megapounds, MegapoundsTolerance); - Assert.Equal(MassUnit.Megapound, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 Мфунт", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Megapounds, MegapoundsTolerance); - Assert.Equal(MassUnit.Megapound, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 兆磅", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Megapounds, MegapoundsTolerance); - Assert.Equal(MassUnit.Megapound, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 Mt", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Megatonnes, MegatonnesTolerance); - Assert.Equal(MassUnit.Megatonne, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 Мт", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Megatonnes, MegatonnesTolerance); - Assert.Equal(MassUnit.Megatonne, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 兆吨", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Megatonnes, MegatonnesTolerance); - Assert.Equal(MassUnit.Megatonne, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 µg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Micrograms, MicrogramsTolerance); - Assert.Equal(MassUnit.Microgram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 мкг", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Micrograms, MicrogramsTolerance); - Assert.Equal(MassUnit.Microgram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 微克", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Micrograms, MicrogramsTolerance); - Assert.Equal(MassUnit.Microgram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 mg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Milligrams, MilligramsTolerance); - Assert.Equal(MassUnit.Milligram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 мг", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Milligrams, MilligramsTolerance); - Assert.Equal(MassUnit.Milligram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 毫克", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Milligrams, MilligramsTolerance); - Assert.Equal(MassUnit.Milligram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 ng", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanograms, NanogramsTolerance); - Assert.Equal(MassUnit.Nanogram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 нг", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanograms, NanogramsTolerance); - Assert.Equal(MassUnit.Nanogram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 纳克", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanograms, NanogramsTolerance); - Assert.Equal(MassUnit.Nanogram, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 oz", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Ounces, OuncesTolerance); - Assert.Equal(MassUnit.Ounce, parsed.Unit); - } - - { - Assert.True(Mass.TryParse("1 盎司", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Ounces, OuncesTolerance); - Assert.Equal(MassUnit.Ounce, parsed.Unit); - } + Assert.Equal(expectedValue, convertedValue); + } - { - Assert.True(Mass.TryParse("1 pg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Picograms, PicogramsTolerance); - Assert.Equal(MassUnit.Picogram, parsed.Unit); - } + [Fact] + public void As_UnitSystem_ThrowsArgumentNullExceptionIfNull() + { + var quantity = new Mass(value: 1, unit: Mass.BaseUnit); + UnitSystem nullUnitSystem = null!; + Assert.Throws(() => quantity.As(nullUnitSystem)); + } - { - Assert.True(Mass.TryParse("1 пг", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Picograms, PicogramsTolerance); - Assert.Equal(MassUnit.Picogram, parsed.Unit); - } + [Fact] + public void As_UnitSystem_ThrowsArgumentExceptionIfNotSupported() + { + var quantity = new Mass(value: 1, unit: Mass.BaseUnit); + var unsupportedUnitSystem = new UnitSystem(UnsupportedBaseUnits); + Assert.Throws(() => quantity.As(unsupportedUnitSystem)); + } - { - Assert.True(Mass.TryParse("1 皮克", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Picograms, PicogramsTolerance); - Assert.Equal(MassUnit.Picogram, parsed.Unit); - } + [Fact] + public virtual void ToUnit_UnitSystem_SI_ReturnsQuantityInSIUnits() + { + var quantity = new Mass(value: 1, unit: Mass.BaseUnit); + var expectedUnit = Mass.Info.GetDefaultUnit(UnitSystem.SI); + var expectedValue = quantity.As(expectedUnit); + Assert.Multiple(() => { - Assert.True(Mass.TryParse("1 lb", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Pounds, PoundsTolerance); - Assert.Equal(MassUnit.Pound, parsed.Unit); - } + Mass quantityToConvert = quantity; - { - Assert.True(Mass.TryParse("1 lbs", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Pounds, PoundsTolerance); - Assert.Equal(MassUnit.Pound, parsed.Unit); - } + Mass convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); + Assert.Equal(expectedUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }, () => { - Assert.True(Mass.TryParse("1 lbm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Pounds, PoundsTolerance); - Assert.Equal(MassUnit.Pound, parsed.Unit); - } + IQuantity quantityToConvert = quantity; - { - Assert.True(Mass.TryParse("1 фунт", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Pounds, PoundsTolerance); - Assert.Equal(MassUnit.Pound, parsed.Unit); - } + IQuantity convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); + Assert.Equal(expectedUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }, () => { - Assert.True(Mass.TryParse("1 磅", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Pounds, PoundsTolerance); - Assert.Equal(MassUnit.Pound, parsed.Unit); - } + IQuantity quantityToConvert = quantity; - { - Assert.True(Mass.TryParse("1 t (short)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ShortTons, ShortTonsTolerance); - Assert.Equal(MassUnit.ShortTon, parsed.Unit); - } + IQuantity convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); - { - Assert.True(Mass.TryParse("1 short tn", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ShortTons, ShortTonsTolerance); - Assert.Equal(MassUnit.ShortTon, parsed.Unit); - } + Assert.Equal(expectedUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }); + } + [Fact] + public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() + { + UnitSystem nullUnitSystem = null!; + Assert.Multiple(() => { - Assert.True(Mass.TryParse("1 тонна малая", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ShortTons, ShortTonsTolerance); - Assert.Equal(MassUnit.ShortTon, parsed.Unit); - } - + var quantity = new Mass(value: 1, unit: Mass.BaseUnit); + Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); + }, () => { - Assert.True(Mass.TryParse("1 短吨", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ShortTons, ShortTonsTolerance); - Assert.Equal(MassUnit.ShortTon, parsed.Unit); - } - + IQuantity quantity = new Mass(value: 1, unit: Mass.BaseUnit); + Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); + }, () => { - Assert.True(Mass.TryParse("1 slug", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Slugs, SlugsTolerance); - Assert.Equal(MassUnit.Slug, parsed.Unit); - } + IQuantity quantity = new Mass(value: 1, unit: Mass.BaseUnit); + Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); + }); + } + [Fact] + public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() + { + var unsupportedUnitSystem = new UnitSystem(UnsupportedBaseUnits); + Assert.Multiple(() => { - Assert.True(Mass.TryParse("1 M☉", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SolarMasses, SolarMassesTolerance); - Assert.Equal(MassUnit.SolarMass, parsed.Unit); - } - + var quantity = new Mass(value: 1, unit: Mass.BaseUnit); + Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); + }, () => { - Assert.True(Mass.TryParse("1 M⊙", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SolarMasses, SolarMassesTolerance); - Assert.Equal(MassUnit.SolarMass, parsed.Unit); - } - + IQuantity quantity = new Mass(value: 1, unit: Mass.BaseUnit); + Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); + }, () => { - Assert.True(Mass.TryParse("1 t", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Tonnes, TonnesTolerance); - Assert.Equal(MassUnit.Tonne, parsed.Unit); - } + IQuantity quantity = new Mass(value: 1, unit: Mass.BaseUnit); + Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); + }); + } - { - Assert.True(Mass.TryParse("1 т", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Tonnes, TonnesTolerance); - Assert.Equal(MassUnit.Tonne, parsed.Unit); - } + [Theory] + [InlineData("en-US", "4.2 cg", MassUnit.Centigram, 4.2)] + [InlineData("en-US", "4.2 dag", MassUnit.Decagram, 4.2)] + [InlineData("en-US", "4.2 dg", MassUnit.Decigram, 4.2)] + [InlineData("en-US", "4.2 em", MassUnit.EarthMass, 4.2)] + [InlineData("en-US", "4.2 fg", MassUnit.Femtogram, 4.2)] + [InlineData("en-US", "4.2 gr", MassUnit.Grain, 4.2)] + [InlineData("en-US", "4.2 g", MassUnit.Gram, 4.2)] + [InlineData("en-US", "4.2 hg", MassUnit.Hectogram, 4.2)] + [InlineData("en-US", "4.2 kg", MassUnit.Kilogram, 4.2)] + [InlineData("en-US", "4.2 klb", MassUnit.Kilopound, 4.2)] + [InlineData("en-US", "4.2 klbs", MassUnit.Kilopound, 4.2)] + [InlineData("en-US", "4.2 klbm", MassUnit.Kilopound, 4.2)] + [InlineData("en-US", "4.2 kt", MassUnit.Kilotonne, 4.2)] + [InlineData("en-US", "4.2 long tn", MassUnit.LongTon, 4.2)] + [InlineData("en-US", "4.2 Mlb", MassUnit.Megapound, 4.2)] + [InlineData("en-US", "4.2 Mlbs", MassUnit.Megapound, 4.2)] + [InlineData("en-US", "4.2 Mlbm", MassUnit.Megapound, 4.2)] + [InlineData("en-US", "4.2 Mt", MassUnit.Megatonne, 4.2)] + [InlineData("en-US", "4.2 µg", MassUnit.Microgram, 4.2)] + [InlineData("en-US", "4.2 mg", MassUnit.Milligram, 4.2)] + [InlineData("en-US", "4.2 ng", MassUnit.Nanogram, 4.2)] + [InlineData("en-US", "4.2 oz", MassUnit.Ounce, 4.2)] + [InlineData("en-US", "4.2 pg", MassUnit.Picogram, 4.2)] + [InlineData("en-US", "4.2 lb", MassUnit.Pound, 4.2)] + [InlineData("en-US", "4.2 lbs", MassUnit.Pound, 4.2)] + [InlineData("en-US", "4.2 lbm", MassUnit.Pound, 4.2)] + [InlineData("en-US", "4.2 t (short)", MassUnit.ShortTon, 4.2)] + [InlineData("en-US", "4.2 short tn", MassUnit.ShortTon, 4.2)] + [InlineData("en-US", "4.2 ST", MassUnit.ShortTon, 4.2)] + [InlineData("en-US", "4.2 slug", MassUnit.Slug, 4.2)] + [InlineData("en-US", "4.2 M☉", MassUnit.SolarMass, 4.2)] + [InlineData("en-US", "4.2 M⊙", MassUnit.SolarMass, 4.2)] + [InlineData("en-US", "4.2 st", MassUnit.Stone, 4.2)] + [InlineData("en-US", "4.2 t", MassUnit.Tonne, 4.2)] + [InlineData("ru-RU", "4,2 сг", MassUnit.Centigram, 4.2)] + [InlineData("ru-RU", "4,2 даг", MassUnit.Decagram, 4.2)] + [InlineData("ru-RU", "4,2 дг", MassUnit.Decigram, 4.2)] + [InlineData("ru-RU", "4,2 фг", MassUnit.Femtogram, 4.2)] + [InlineData("ru-RU", "4,2 г", MassUnit.Gram, 4.2)] + [InlineData("ru-RU", "4,2 гг", MassUnit.Hectogram, 4.2)] + [InlineData("ru-RU", "4,2 кг", MassUnit.Kilogram, 4.2)] + [InlineData("ru-RU", "4,2 кфунт", MassUnit.Kilopound, 4.2)] + [InlineData("ru-RU", "4,2 кт", MassUnit.Kilotonne, 4.2)] + [InlineData("ru-RU", "4,2 тонна большая", MassUnit.LongTon, 4.2)] + [InlineData("ru-RU", "4,2 Мфунт", MassUnit.Megapound, 4.2)] + [InlineData("ru-RU", "4,2 Мт", MassUnit.Megatonne, 4.2)] + [InlineData("ru-RU", "4,2 мкг", MassUnit.Microgram, 4.2)] + [InlineData("ru-RU", "4,2 мг", MassUnit.Milligram, 4.2)] + [InlineData("ru-RU", "4,2 нг", MassUnit.Nanogram, 4.2)] + [InlineData("ru-RU", "4,2 пг", MassUnit.Picogram, 4.2)] + [InlineData("ru-RU", "4,2 фунт", MassUnit.Pound, 4.2)] + [InlineData("ru-RU", "4,2 тонна малая", MassUnit.ShortTon, 4.2)] + [InlineData("ru-RU", "4,2 т", MassUnit.Tonne, 4.2)] + [InlineData("zh-CN", "4.2 厘克", MassUnit.Centigram, 4.2)] + [InlineData("zh-CN", "4.2 十克", MassUnit.Decagram, 4.2)] + [InlineData("zh-CN", "4.2 分克", MassUnit.Decigram, 4.2)] + [InlineData("zh-CN", "4.2 飞克", MassUnit.Femtogram, 4.2)] + [InlineData("zh-CN", "4.2 克", MassUnit.Gram, 4.2)] + [InlineData("zh-CN", "4.2 百克", MassUnit.Hectogram, 4.2)] + [InlineData("zh-CN", "4.2 千克", MassUnit.Kilogram, 4.2)] + [InlineData("zh-CN", "4.2 千磅", MassUnit.Kilopound, 4.2)] + [InlineData("zh-CN", "4.2 千吨", MassUnit.Kilotonne, 4.2)] + [InlineData("zh-CN", "4.2 长吨", MassUnit.LongTon, 4.2)] + [InlineData("zh-CN", "4.2 兆磅", MassUnit.Megapound, 4.2)] + [InlineData("zh-CN", "4.2 兆吨", MassUnit.Megatonne, 4.2)] + [InlineData("zh-CN", "4.2 微克", MassUnit.Microgram, 4.2)] + [InlineData("zh-CN", "4.2 毫克", MassUnit.Milligram, 4.2)] + [InlineData("zh-CN", "4.2 纳克", MassUnit.Nanogram, 4.2)] + [InlineData("zh-CN", "4.2 盎司", MassUnit.Ounce, 4.2)] + [InlineData("zh-CN", "4.2 皮克", MassUnit.Picogram, 4.2)] + [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, decimal expectedValue) + { + using var _ = new CultureScope(culture); + var parsed = Mass.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); + } - { - Assert.True(Mass.TryParse("1 吨", CultureInfo.GetCultureInfo("zh-CN"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Tonnes, TonnesTolerance); - Assert.Equal(MassUnit.Tonne, parsed.Unit); - } + [Theory] + [InlineData("en-US", "1 cwt")] // [LongHundredweight, ShortHundredweight] + public void ParseWithAmbiguousAbbreviation(string culture, string quantityString) + { + Assert.Throws(() => Mass.Parse(quantityString, CultureInfo.GetCultureInfo(culture))); + } + + [Theory] + [InlineData("en-US", "4.2 cg", MassUnit.Centigram, 4.2)] + [InlineData("en-US", "4.2 dag", MassUnit.Decagram, 4.2)] + [InlineData("en-US", "4.2 dg", MassUnit.Decigram, 4.2)] + [InlineData("en-US", "4.2 em", MassUnit.EarthMass, 4.2)] + [InlineData("en-US", "4.2 fg", MassUnit.Femtogram, 4.2)] + [InlineData("en-US", "4.2 gr", MassUnit.Grain, 4.2)] + [InlineData("en-US", "4.2 g", MassUnit.Gram, 4.2)] + [InlineData("en-US", "4.2 hg", MassUnit.Hectogram, 4.2)] + [InlineData("en-US", "4.2 kg", MassUnit.Kilogram, 4.2)] + [InlineData("en-US", "4.2 klb", MassUnit.Kilopound, 4.2)] + [InlineData("en-US", "4.2 klbs", MassUnit.Kilopound, 4.2)] + [InlineData("en-US", "4.2 klbm", MassUnit.Kilopound, 4.2)] + [InlineData("en-US", "4.2 kt", MassUnit.Kilotonne, 4.2)] + [InlineData("en-US", "4.2 long tn", MassUnit.LongTon, 4.2)] + [InlineData("en-US", "4.2 Mlb", MassUnit.Megapound, 4.2)] + [InlineData("en-US", "4.2 Mlbs", MassUnit.Megapound, 4.2)] + [InlineData("en-US", "4.2 Mlbm", MassUnit.Megapound, 4.2)] + [InlineData("en-US", "4.2 Mt", MassUnit.Megatonne, 4.2)] + [InlineData("en-US", "4.2 µg", MassUnit.Microgram, 4.2)] + [InlineData("en-US", "4.2 mg", MassUnit.Milligram, 4.2)] + [InlineData("en-US", "4.2 ng", MassUnit.Nanogram, 4.2)] + [InlineData("en-US", "4.2 oz", MassUnit.Ounce, 4.2)] + [InlineData("en-US", "4.2 pg", MassUnit.Picogram, 4.2)] + [InlineData("en-US", "4.2 lb", MassUnit.Pound, 4.2)] + [InlineData("en-US", "4.2 lbs", MassUnit.Pound, 4.2)] + [InlineData("en-US", "4.2 lbm", MassUnit.Pound, 4.2)] + [InlineData("en-US", "4.2 t (short)", MassUnit.ShortTon, 4.2)] + [InlineData("en-US", "4.2 short tn", MassUnit.ShortTon, 4.2)] + [InlineData("en-US", "4.2 ST", MassUnit.ShortTon, 4.2)] + [InlineData("en-US", "4.2 slug", MassUnit.Slug, 4.2)] + [InlineData("en-US", "4.2 M☉", MassUnit.SolarMass, 4.2)] + [InlineData("en-US", "4.2 M⊙", MassUnit.SolarMass, 4.2)] + [InlineData("en-US", "4.2 st", MassUnit.Stone, 4.2)] + [InlineData("en-US", "4.2 t", MassUnit.Tonne, 4.2)] + [InlineData("ru-RU", "4,2 сг", MassUnit.Centigram, 4.2)] + [InlineData("ru-RU", "4,2 даг", MassUnit.Decagram, 4.2)] + [InlineData("ru-RU", "4,2 дг", MassUnit.Decigram, 4.2)] + [InlineData("ru-RU", "4,2 фг", MassUnit.Femtogram, 4.2)] + [InlineData("ru-RU", "4,2 г", MassUnit.Gram, 4.2)] + [InlineData("ru-RU", "4,2 гг", MassUnit.Hectogram, 4.2)] + [InlineData("ru-RU", "4,2 кг", MassUnit.Kilogram, 4.2)] + [InlineData("ru-RU", "4,2 кфунт", MassUnit.Kilopound, 4.2)] + [InlineData("ru-RU", "4,2 кт", MassUnit.Kilotonne, 4.2)] + [InlineData("ru-RU", "4,2 тонна большая", MassUnit.LongTon, 4.2)] + [InlineData("ru-RU", "4,2 Мфунт", MassUnit.Megapound, 4.2)] + [InlineData("ru-RU", "4,2 Мт", MassUnit.Megatonne, 4.2)] + [InlineData("ru-RU", "4,2 мкг", MassUnit.Microgram, 4.2)] + [InlineData("ru-RU", "4,2 мг", MassUnit.Milligram, 4.2)] + [InlineData("ru-RU", "4,2 нг", MassUnit.Nanogram, 4.2)] + [InlineData("ru-RU", "4,2 пг", MassUnit.Picogram, 4.2)] + [InlineData("ru-RU", "4,2 фунт", MassUnit.Pound, 4.2)] + [InlineData("ru-RU", "4,2 тонна малая", MassUnit.ShortTon, 4.2)] + [InlineData("ru-RU", "4,2 т", MassUnit.Tonne, 4.2)] + [InlineData("zh-CN", "4.2 厘克", MassUnit.Centigram, 4.2)] + [InlineData("zh-CN", "4.2 十克", MassUnit.Decagram, 4.2)] + [InlineData("zh-CN", "4.2 分克", MassUnit.Decigram, 4.2)] + [InlineData("zh-CN", "4.2 飞克", MassUnit.Femtogram, 4.2)] + [InlineData("zh-CN", "4.2 克", MassUnit.Gram, 4.2)] + [InlineData("zh-CN", "4.2 百克", MassUnit.Hectogram, 4.2)] + [InlineData("zh-CN", "4.2 千克", MassUnit.Kilogram, 4.2)] + [InlineData("zh-CN", "4.2 千磅", MassUnit.Kilopound, 4.2)] + [InlineData("zh-CN", "4.2 千吨", MassUnit.Kilotonne, 4.2)] + [InlineData("zh-CN", "4.2 长吨", MassUnit.LongTon, 4.2)] + [InlineData("zh-CN", "4.2 兆磅", MassUnit.Megapound, 4.2)] + [InlineData("zh-CN", "4.2 兆吨", MassUnit.Megatonne, 4.2)] + [InlineData("zh-CN", "4.2 微克", MassUnit.Microgram, 4.2)] + [InlineData("zh-CN", "4.2 毫克", MassUnit.Milligram, 4.2)] + [InlineData("zh-CN", "4.2 纳克", MassUnit.Nanogram, 4.2)] + [InlineData("zh-CN", "4.2 盎司", MassUnit.Ounce, 4.2)] + [InlineData("zh-CN", "4.2 皮克", MassUnit.Picogram, 4.2)] + [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, decimal expectedValue) + { + using var _ = new CultureScope(culture); + Assert.True(Mass.TryParse(quantityString, out Mass parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); + } + [Theory] + [InlineData("en-US", "1 cwt")] // [LongHundredweight, ShortHundredweight] + public void TryParseWithAmbiguousAbbreviation(string culture, string quantityString) + { + Assert.False(Mass.TryParse(quantityString, CultureInfo.GetCultureInfo(culture), out _)); } [Theory] @@ -1996,6 +1231,92 @@ public void TryParseUnitWithAmbiguousAbbreviation(string culture, string abbrevi Assert.False(Mass.TryParseUnit(abbreviation, CultureInfo.GetCultureInfo(culture), out _)); } + [Theory] + [InlineData("en-US", MassUnit.Centigram, "cg")] + [InlineData("en-US", MassUnit.Decagram, "dag")] + [InlineData("en-US", MassUnit.Decigram, "dg")] + [InlineData("en-US", MassUnit.EarthMass, "em")] + [InlineData("en-US", MassUnit.Femtogram, "fg")] + [InlineData("en-US", MassUnit.Grain, "gr")] + [InlineData("en-US", MassUnit.Gram, "g")] + [InlineData("en-US", MassUnit.Hectogram, "hg")] + [InlineData("en-US", MassUnit.Kilogram, "kg")] + [InlineData("en-US", MassUnit.Kilopound, "klb")] + [InlineData("en-US", MassUnit.Kilotonne, "kt")] + [InlineData("en-US", MassUnit.LongHundredweight, "cwt")] + [InlineData("en-US", MassUnit.LongTon, "long tn")] + [InlineData("en-US", MassUnit.Megapound, "Mlb")] + [InlineData("en-US", MassUnit.Megatonne, "Mt")] + [InlineData("en-US", MassUnit.Microgram, "µg")] + [InlineData("en-US", MassUnit.Milligram, "mg")] + [InlineData("en-US", MassUnit.Nanogram, "ng")] + [InlineData("en-US", MassUnit.Ounce, "oz")] + [InlineData("en-US", MassUnit.Picogram, "pg")] + [InlineData("en-US", MassUnit.Pound, "lb")] + [InlineData("en-US", MassUnit.ShortHundredweight, "cwt")] + [InlineData("en-US", MassUnit.ShortTon, "t (short)")] + [InlineData("en-US", MassUnit.Slug, "slug")] + [InlineData("en-US", MassUnit.SolarMass, "M☉")] + [InlineData("en-US", MassUnit.Stone, "st")] + [InlineData("en-US", MassUnit.Tonne, "t")] + [InlineData("ru-RU", MassUnit.Centigram, "сг")] + [InlineData("ru-RU", MassUnit.Decagram, "даг")] + [InlineData("ru-RU", MassUnit.Decigram, "дг")] + [InlineData("ru-RU", MassUnit.Femtogram, "фг")] + [InlineData("ru-RU", MassUnit.Gram, "г")] + [InlineData("ru-RU", MassUnit.Hectogram, "гг")] + [InlineData("ru-RU", MassUnit.Kilogram, "кг")] + [InlineData("ru-RU", MassUnit.Kilopound, "кфунт")] + [InlineData("ru-RU", MassUnit.Kilotonne, "кт")] + [InlineData("ru-RU", MassUnit.LongTon, "тонна большая")] + [InlineData("ru-RU", MassUnit.Megapound, "Мфунт")] + [InlineData("ru-RU", MassUnit.Megatonne, "Мт")] + [InlineData("ru-RU", MassUnit.Microgram, "мкг")] + [InlineData("ru-RU", MassUnit.Milligram, "мг")] + [InlineData("ru-RU", MassUnit.Nanogram, "нг")] + [InlineData("ru-RU", MassUnit.Picogram, "пг")] + [InlineData("ru-RU", MassUnit.Pound, "фунт")] + [InlineData("ru-RU", MassUnit.ShortTon, "тонна малая")] + [InlineData("ru-RU", MassUnit.Tonne, "т")] + [InlineData("zh-CN", MassUnit.Centigram, "厘克")] + [InlineData("zh-CN", MassUnit.Decagram, "十克")] + [InlineData("zh-CN", MassUnit.Decigram, "分克")] + [InlineData("zh-CN", MassUnit.Femtogram, "飞克")] + [InlineData("zh-CN", MassUnit.Gram, "克")] + [InlineData("zh-CN", MassUnit.Hectogram, "百克")] + [InlineData("zh-CN", MassUnit.Kilogram, "千克")] + [InlineData("zh-CN", MassUnit.Kilopound, "千磅")] + [InlineData("zh-CN", MassUnit.Kilotonne, "千吨")] + [InlineData("zh-CN", MassUnit.LongTon, "长吨")] + [InlineData("zh-CN", MassUnit.Megapound, "兆磅")] + [InlineData("zh-CN", MassUnit.Megatonne, "兆吨")] + [InlineData("zh-CN", MassUnit.Microgram, "微克")] + [InlineData("zh-CN", MassUnit.Milligram, "毫克")] + [InlineData("zh-CN", MassUnit.Nanogram, "纳克")] + [InlineData("zh-CN", MassUnit.Ounce, "盎司")] + [InlineData("zh-CN", MassUnit.Picogram, "皮克")] + [InlineData("zh-CN", MassUnit.Pound, "磅")] + [InlineData("zh-CN", MassUnit.ShortTon, "短吨")] + [InlineData("zh-CN", MassUnit.Tonne, "吨")] + public void GetAbbreviationForCulture(string culture, MassUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Mass.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Mass.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Mass.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(MassUnit unit) @@ -2026,6 +1347,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); }); } @@ -2049,58 +1371,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] @@ -2146,8 +1470,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); @@ -2184,23 +1506,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = Mass.FromKilograms(1); - Assert.True(v.Equals(Mass.FromKilograms(1), KilogramsTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Mass.Zero, KilogramsTolerance, ComparisonType.Relative)); - Assert.True(Mass.FromKilograms(100).Equals(Mass.FromKilograms(120), 0.3, ComparisonType.Relative)); - Assert.False(Mass.FromKilograms(100).Equals(Mass.FromKilograms(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = Mass.FromKilograms(1); - Assert.Throws(() => v.Equals(Mass.FromKilograms(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -2215,6 +1520,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(kilogram.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = Mass.FromKilograms(1); + var negativeTolerance = Mass.FromKilograms(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -2231,6 +1562,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() { @@ -2341,158 +1684,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Mass.FromKilograms(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Mass.FromKilograms(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Mass.FromKilograms(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Mass.FromKilograms(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Mass.FromKilograms(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Mass.FromKilograms(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Mass.FromKilograms(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Mass.FromKilograms(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Mass.FromKilograms(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Mass.FromKilograms(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Mass.FromKilograms(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Mass.FromKilograms(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Mass.FromKilograms(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Mass.FromKilograms(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Mass.FromKilograms(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Mass.FromKilograms(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Mass))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Mass.FromKilograms(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MassUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Mass.FromKilograms(1.0); - Assert.Equal(Mass.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Mass.FromKilograms(1.0); - Assert.Equal(Mass.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Mass.FromKilograms(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Mass.FromKilograms(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Mass.FromKilograms(1.0); - Assert.Equal(new {Mass.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 8f39d4fcaa..82dcb193a8 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MolalityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MolalityTestsBase.g.cs @@ -104,7 +104,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Molality(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -117,15 +117,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Molality_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + MolalityUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Molality(1, MolalityUnit.MolePerKilogram); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Molality.Zero, quantityInfo.Zero); Assert.Equal("Molality", quantityInfo.Name); + Assert.Equal(Molality.Zero, quantityInfo.Zero); + Assert.Equal(Molality.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Molality.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void MolalityInfo_CreateWithCustomUnitInfos() + { + MolalityUnit[] expectedUnits = [MolalityUnit.MolePerKilogram]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -141,15 +159,15 @@ public void MolePerKilogramToMolalityUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Molality.From(1, MolalityUnit.MillimolePerKilogram); - AssertEx.EqualTolerance(1, quantity00.MillimolesPerKilogram, MillimolesPerKilogramTolerance); + Assert.Equal(1, quantity00.MillimolesPerKilogram); Assert.Equal(MolalityUnit.MillimolePerKilogram, quantity00.Unit); var quantity01 = Molality.From(1, MolalityUnit.MolePerGram); - AssertEx.EqualTolerance(1, quantity01.MolesPerGram, MolesPerGramTolerance); + Assert.Equal(1, quantity01.MolesPerGram); Assert.Equal(MolalityUnit.MolePerGram, quantity01.Unit); var quantity02 = Molality.From(1, MolalityUnit.MolePerKilogram); - AssertEx.EqualTolerance(1, quantity02.MolesPerKilogram, MolesPerKilogramTolerance); + Assert.Equal(1, quantity02.MolesPerKilogram); Assert.Equal(MolalityUnit.MolePerKilogram, quantity02.Unit); } @@ -287,53 +305,28 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [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, decimal expectedValue) { - try - { - var parsed = Molality.Parse("1 mmol/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillimolesPerKilogram, MillimolesPerKilogramTolerance); - Assert.Equal(MolalityUnit.MillimolePerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Molality.Parse("1 mol/g", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MolesPerGram, MolesPerGramTolerance); - Assert.Equal(MolalityUnit.MolePerGram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Molality.Parse("1 mol/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MolesPerKilogram, MolesPerKilogramTolerance); - Assert.Equal(MolalityUnit.MolePerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Molality.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [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, decimal expectedValue) { - { - Assert.True(Molality.TryParse("1 mmol/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimolesPerKilogram, MillimolesPerKilogramTolerance); - Assert.Equal(MolalityUnit.MillimolePerKilogram, parsed.Unit); - } - - { - Assert.True(Molality.TryParse("1 mol/g", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MolesPerGram, MolesPerGramTolerance); - Assert.Equal(MolalityUnit.MolePerGram, parsed.Unit); - } - - { - Assert.True(Molality.TryParse("1 mol/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MolesPerKilogram, MolesPerKilogramTolerance); - Assert.Equal(MolalityUnit.MolePerKilogram, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Molality.TryParse(quantityString, out Molality parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -426,6 +419,29 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Molali Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", MolalityUnit.MillimolePerKilogram, "mmol/kg")] + [InlineData("en-US", MolalityUnit.MolePerGram, "mol/g")] + [InlineData("en-US", MolalityUnit.MolePerKilogram, "mol/kg")] + public void GetAbbreviationForCulture(string culture, MolalityUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Molality.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Molality.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Molality.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(MolalityUnit unit) @@ -456,6 +472,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); }); } @@ -479,34 +496,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] @@ -552,8 +571,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); @@ -591,34 +608,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = Molality.FromMolesPerKilogram(1); - Assert.True(v.Equals(Molality.FromMolesPerKilogram(1), MolesPerKilogramTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Molality.Zero, MolesPerKilogramTolerance, ComparisonType.Relative)); - Assert.True(Molality.FromMolesPerKilogram(100).Equals(Molality.FromMolesPerKilogram(120), 0.3, ComparisonType.Relative)); - Assert.False(Molality.FromMolesPerKilogram(100).Equals(Molality.FromMolesPerKilogram(120), 0.1, ComparisonType.Relative)); + Molality moleperkilogram = Molality.FromMolesPerKilogram(1); + Assert.False(moleperkilogram.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = Molality.FromMolesPerKilogram(1); - Assert.Throws(() => v.Equals(Molality.FromMolesPerKilogram(1), -1, ComparisonType.Relative)); + Molality moleperkilogram = Molality.FromMolesPerKilogram(1); + Assert.False(moleperkilogram.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - Molality moleperkilogram = Molality.FromMolesPerKilogram(1); - Assert.False(moleperkilogram.Equals(new object())); + var quantity = Molality.FromMolesPerKilogram(firstValue); + var otherQuantity = Molality.FromMolesPerKilogram(secondValue); + Molality maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - Molality moleperkilogram = Molality.FromMolesPerKilogram(1); - Assert.False(moleperkilogram.Equals(null)); + var quantity = Molality.FromMolesPerKilogram(1); + var negativeTolerance = Molality.FromMolesPerKilogram(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -637,6 +663,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() { @@ -699,158 +737,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Molality.FromMolesPerKilogram(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Molality.FromMolesPerKilogram(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Molality.FromMolesPerKilogram(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Molality.FromMolesPerKilogram(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Molality.FromMolesPerKilogram(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Molality.FromMolesPerKilogram(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Molality.FromMolesPerKilogram(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Molality.FromMolesPerKilogram(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Molality.FromMolesPerKilogram(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Molality.FromMolesPerKilogram(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Molality.FromMolesPerKilogram(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Molality.FromMolesPerKilogram(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Molality.FromMolesPerKilogram(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Molality.FromMolesPerKilogram(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Molality.FromMolesPerKilogram(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Molality.FromMolesPerKilogram(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Molality))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Molality.FromMolesPerKilogram(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MolalityUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Molality.FromMolesPerKilogram(1.0); - Assert.Equal(Molality.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Molality.FromMolesPerKilogram(1.0); - Assert.Equal(Molality.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Molality.FromMolesPerKilogram(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Molality.FromMolesPerKilogram(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Molality.FromMolesPerKilogram(1.0); - Assert.Equal(new {Molality.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 8e18b466cd..98eab68cd0 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEnergyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEnergyTestsBase.g.cs @@ -104,7 +104,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new MolarEnergy(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -117,15 +117,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void MolarEnergy_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + MolarEnergyUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new MolarEnergy(1, MolarEnergyUnit.JoulePerMole); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(MolarEnergy.Zero, quantityInfo.Zero); Assert.Equal("MolarEnergy", quantityInfo.Name); + Assert.Equal(MolarEnergy.Zero, quantityInfo.Zero); + Assert.Equal(MolarEnergy.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(MolarEnergy.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void MolarEnergyInfo_CreateWithCustomUnitInfos() + { + MolarEnergyUnit[] expectedUnits = [MolarEnergyUnit.JoulePerMole]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -141,15 +159,15 @@ public void JoulePerMoleToMolarEnergyUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = MolarEnergy.From(1, MolarEnergyUnit.JoulePerMole); - AssertEx.EqualTolerance(1, quantity00.JoulesPerMole, JoulesPerMoleTolerance); + Assert.Equal(1, quantity00.JoulesPerMole); Assert.Equal(MolarEnergyUnit.JoulePerMole, quantity00.Unit); var quantity01 = MolarEnergy.From(1, MolarEnergyUnit.KilojoulePerMole); - AssertEx.EqualTolerance(1, quantity01.KilojoulesPerMole, KilojoulesPerMoleTolerance); + Assert.Equal(1, quantity01.KilojoulesPerMole); Assert.Equal(MolarEnergyUnit.KilojoulePerMole, quantity01.Unit); var quantity02 = MolarEnergy.From(1, MolarEnergyUnit.MegajoulePerMole); - AssertEx.EqualTolerance(1, quantity02.MegajoulesPerMole, MegajoulesPerMoleTolerance); + Assert.Equal(1, quantity02.MegajoulesPerMole); Assert.Equal(MolarEnergyUnit.MegajoulePerMole, quantity02.Unit); } @@ -287,53 +305,28 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [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, decimal expectedValue) { - try - { - var parsed = MolarEnergy.Parse("1 J/mol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.JoulesPerMole, JoulesPerMoleTolerance); - Assert.Equal(MolarEnergyUnit.JoulePerMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarEnergy.Parse("1 kJ/mol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilojoulesPerMole, KilojoulesPerMoleTolerance); - Assert.Equal(MolarEnergyUnit.KilojoulePerMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarEnergy.Parse("1 MJ/mol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegajoulesPerMole, MegajoulesPerMoleTolerance); - Assert.Equal(MolarEnergyUnit.MegajoulePerMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = MolarEnergy.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [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, decimal expectedValue) { - { - Assert.True(MolarEnergy.TryParse("1 J/mol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.JoulesPerMole, JoulesPerMoleTolerance); - Assert.Equal(MolarEnergyUnit.JoulePerMole, parsed.Unit); - } - - { - Assert.True(MolarEnergy.TryParse("1 kJ/mol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilojoulesPerMole, KilojoulesPerMoleTolerance); - Assert.Equal(MolarEnergyUnit.KilojoulePerMole, parsed.Unit); - } - - { - Assert.True(MolarEnergy.TryParse("1 MJ/mol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegajoulesPerMole, MegajoulesPerMoleTolerance); - Assert.Equal(MolarEnergyUnit.MegajoulePerMole, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(MolarEnergy.TryParse(quantityString, out MolarEnergy parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -426,6 +419,29 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, MolarE Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", MolarEnergyUnit.JoulePerMole, "J/mol")] + [InlineData("en-US", MolarEnergyUnit.KilojoulePerMole, "kJ/mol")] + [InlineData("en-US", MolarEnergyUnit.MegajoulePerMole, "MJ/mol")] + public void GetAbbreviationForCulture(string culture, MolarEnergyUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = MolarEnergy.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(MolarEnergy.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = MolarEnergy.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(MolarEnergyUnit unit) @@ -456,6 +472,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); }); } @@ -479,34 +496,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] @@ -552,8 +571,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); @@ -591,34 +608,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = MolarEnergy.FromJoulesPerMole(1); - Assert.True(v.Equals(MolarEnergy.FromJoulesPerMole(1), JoulesPerMoleTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(MolarEnergy.Zero, JoulesPerMoleTolerance, ComparisonType.Relative)); - Assert.True(MolarEnergy.FromJoulesPerMole(100).Equals(MolarEnergy.FromJoulesPerMole(120), 0.3, ComparisonType.Relative)); - Assert.False(MolarEnergy.FromJoulesPerMole(100).Equals(MolarEnergy.FromJoulesPerMole(120), 0.1, ComparisonType.Relative)); + MolarEnergy joulepermole = MolarEnergy.FromJoulesPerMole(1); + Assert.False(joulepermole.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = MolarEnergy.FromJoulesPerMole(1); - Assert.Throws(() => v.Equals(MolarEnergy.FromJoulesPerMole(1), -1, ComparisonType.Relative)); + MolarEnergy joulepermole = MolarEnergy.FromJoulesPerMole(1); + Assert.False(joulepermole.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - MolarEnergy joulepermole = MolarEnergy.FromJoulesPerMole(1); - Assert.False(joulepermole.Equals(new object())); + var quantity = MolarEnergy.FromJoulesPerMole(firstValue); + var otherQuantity = MolarEnergy.FromJoulesPerMole(secondValue); + MolarEnergy maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - MolarEnergy joulepermole = MolarEnergy.FromJoulesPerMole(1); - Assert.False(joulepermole.Equals(null)); + var quantity = MolarEnergy.FromJoulesPerMole(1); + var negativeTolerance = MolarEnergy.FromJoulesPerMole(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -637,6 +663,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() { @@ -699,158 +737,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(MolarEnergy))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MolarEnergyUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal(MolarEnergy.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal(MolarEnergy.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal(new {MolarEnergy.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 c90bb4d94c..85fd837dd1 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEntropyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEntropyTestsBase.g.cs @@ -104,7 +104,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new MolarEntropy(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -117,15 +117,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void MolarEntropy_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + MolarEntropyUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new MolarEntropy(1, MolarEntropyUnit.JoulePerMoleKelvin); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(MolarEntropy.Zero, quantityInfo.Zero); Assert.Equal("MolarEntropy", quantityInfo.Name); + Assert.Equal(MolarEntropy.Zero, quantityInfo.Zero); + Assert.Equal(MolarEntropy.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(MolarEntropy.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void MolarEntropyInfo_CreateWithCustomUnitInfos() + { + MolarEntropyUnit[] expectedUnits = [MolarEntropyUnit.JoulePerMoleKelvin]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -141,15 +159,15 @@ public void JoulePerMoleKelvinToMolarEntropyUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = MolarEntropy.From(1, MolarEntropyUnit.JoulePerMoleKelvin); - AssertEx.EqualTolerance(1, quantity00.JoulesPerMoleKelvin, JoulesPerMoleKelvinTolerance); + Assert.Equal(1, quantity00.JoulesPerMoleKelvin); Assert.Equal(MolarEntropyUnit.JoulePerMoleKelvin, quantity00.Unit); var quantity01 = MolarEntropy.From(1, MolarEntropyUnit.KilojoulePerMoleKelvin); - AssertEx.EqualTolerance(1, quantity01.KilojoulesPerMoleKelvin, KilojoulesPerMoleKelvinTolerance); + Assert.Equal(1, quantity01.KilojoulesPerMoleKelvin); Assert.Equal(MolarEntropyUnit.KilojoulePerMoleKelvin, quantity01.Unit); var quantity02 = MolarEntropy.From(1, MolarEntropyUnit.MegajoulePerMoleKelvin); - AssertEx.EqualTolerance(1, quantity02.MegajoulesPerMoleKelvin, MegajoulesPerMoleKelvinTolerance); + Assert.Equal(1, quantity02.MegajoulesPerMoleKelvin); Assert.Equal(MolarEntropyUnit.MegajoulePerMoleKelvin, quantity02.Unit); } @@ -287,53 +305,28 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [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, decimal expectedValue) { - try - { - var parsed = MolarEntropy.Parse("1 J/(mol·K)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.JoulesPerMoleKelvin, JoulesPerMoleKelvinTolerance); - Assert.Equal(MolarEntropyUnit.JoulePerMoleKelvin, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarEntropy.Parse("1 kJ/(mol·K)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilojoulesPerMoleKelvin, KilojoulesPerMoleKelvinTolerance); - Assert.Equal(MolarEntropyUnit.KilojoulePerMoleKelvin, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarEntropy.Parse("1 MJ/(mol·K)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegajoulesPerMoleKelvin, MegajoulesPerMoleKelvinTolerance); - Assert.Equal(MolarEntropyUnit.MegajoulePerMoleKelvin, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = MolarEntropy.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [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, decimal expectedValue) { - { - Assert.True(MolarEntropy.TryParse("1 J/(mol·K)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.JoulesPerMoleKelvin, JoulesPerMoleKelvinTolerance); - Assert.Equal(MolarEntropyUnit.JoulePerMoleKelvin, parsed.Unit); - } - - { - Assert.True(MolarEntropy.TryParse("1 kJ/(mol·K)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilojoulesPerMoleKelvin, KilojoulesPerMoleKelvinTolerance); - Assert.Equal(MolarEntropyUnit.KilojoulePerMoleKelvin, parsed.Unit); - } - - { - Assert.True(MolarEntropy.TryParse("1 MJ/(mol·K)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegajoulesPerMoleKelvin, MegajoulesPerMoleKelvinTolerance); - Assert.Equal(MolarEntropyUnit.MegajoulePerMoleKelvin, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(MolarEntropy.TryParse(quantityString, out MolarEntropy parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -426,6 +419,29 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, MolarE Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", MolarEntropyUnit.JoulePerMoleKelvin, "J/(mol·K)")] + [InlineData("en-US", MolarEntropyUnit.KilojoulePerMoleKelvin, "kJ/(mol·K)")] + [InlineData("en-US", MolarEntropyUnit.MegajoulePerMoleKelvin, "MJ/(mol·K)")] + public void GetAbbreviationForCulture(string culture, MolarEntropyUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = MolarEntropy.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(MolarEntropy.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = MolarEntropy.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(MolarEntropyUnit unit) @@ -456,6 +472,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); }); } @@ -479,34 +496,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] @@ -552,8 +571,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); @@ -591,34 +608,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = MolarEntropy.FromJoulesPerMoleKelvin(1); - Assert.True(v.Equals(MolarEntropy.FromJoulesPerMoleKelvin(1), JoulesPerMoleKelvinTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(MolarEntropy.Zero, JoulesPerMoleKelvinTolerance, ComparisonType.Relative)); - Assert.True(MolarEntropy.FromJoulesPerMoleKelvin(100).Equals(MolarEntropy.FromJoulesPerMoleKelvin(120), 0.3, ComparisonType.Relative)); - Assert.False(MolarEntropy.FromJoulesPerMoleKelvin(100).Equals(MolarEntropy.FromJoulesPerMoleKelvin(120), 0.1, ComparisonType.Relative)); + MolarEntropy joulepermolekelvin = MolarEntropy.FromJoulesPerMoleKelvin(1); + Assert.False(joulepermolekelvin.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = MolarEntropy.FromJoulesPerMoleKelvin(1); - Assert.Throws(() => v.Equals(MolarEntropy.FromJoulesPerMoleKelvin(1), -1, ComparisonType.Relative)); + MolarEntropy joulepermolekelvin = MolarEntropy.FromJoulesPerMoleKelvin(1); + Assert.False(joulepermolekelvin.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - MolarEntropy joulepermolekelvin = MolarEntropy.FromJoulesPerMoleKelvin(1); - Assert.False(joulepermolekelvin.Equals(new object())); + var quantity = MolarEntropy.FromJoulesPerMoleKelvin(firstValue); + var otherQuantity = MolarEntropy.FromJoulesPerMoleKelvin(secondValue); + MolarEntropy maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - MolarEntropy joulepermolekelvin = MolarEntropy.FromJoulesPerMoleKelvin(1); - Assert.False(joulepermolekelvin.Equals(null)); + var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1); + var negativeTolerance = MolarEntropy.FromJoulesPerMoleKelvin(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -637,6 +663,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() { @@ -699,158 +737,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(MolarEntropy))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MolarEntropyUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal(MolarEntropy.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal(MolarEntropy.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal(new {MolarEntropy.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 f540b48233..cd8372c5b5 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarFlowTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarFlowTestsBase.g.cs @@ -128,7 +128,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new MolarFlow(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -141,15 +141,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void MolarFlow_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + MolarFlowUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new MolarFlow(1, MolarFlowUnit.MolePerSecond); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(MolarFlow.Zero, quantityInfo.Zero); Assert.Equal("MolarFlow", quantityInfo.Name); + Assert.Equal(MolarFlow.Zero, quantityInfo.Zero); + Assert.Equal(MolarFlow.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(MolarFlow.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -171,39 +189,39 @@ public void MolePerSecondToMolarFlowUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = MolarFlow.From(1, MolarFlowUnit.KilomolePerHour); - AssertEx.EqualTolerance(1, quantity00.KilomolesPerHour, KilomolesPerHourTolerance); + Assert.Equal(1, quantity00.KilomolesPerHour); Assert.Equal(MolarFlowUnit.KilomolePerHour, quantity00.Unit); var quantity01 = MolarFlow.From(1, MolarFlowUnit.KilomolePerMinute); - AssertEx.EqualTolerance(1, quantity01.KilomolesPerMinute, KilomolesPerMinuteTolerance); + Assert.Equal(1, quantity01.KilomolesPerMinute); Assert.Equal(MolarFlowUnit.KilomolePerMinute, quantity01.Unit); var quantity02 = MolarFlow.From(1, MolarFlowUnit.KilomolePerSecond); - AssertEx.EqualTolerance(1, quantity02.KilomolesPerSecond, KilomolesPerSecondTolerance); + Assert.Equal(1, quantity02.KilomolesPerSecond); Assert.Equal(MolarFlowUnit.KilomolePerSecond, quantity02.Unit); var quantity03 = MolarFlow.From(1, MolarFlowUnit.MolePerHour); - AssertEx.EqualTolerance(1, quantity03.MolesPerHour, MolesPerHourTolerance); + Assert.Equal(1, quantity03.MolesPerHour); Assert.Equal(MolarFlowUnit.MolePerHour, quantity03.Unit); var quantity04 = MolarFlow.From(1, MolarFlowUnit.MolePerMinute); - AssertEx.EqualTolerance(1, quantity04.MolesPerMinute, MolesPerMinuteTolerance); + Assert.Equal(1, quantity04.MolesPerMinute); Assert.Equal(MolarFlowUnit.MolePerMinute, quantity04.Unit); var quantity05 = MolarFlow.From(1, MolarFlowUnit.MolePerSecond); - AssertEx.EqualTolerance(1, quantity05.MolesPerSecond, MolesPerSecondTolerance); + Assert.Equal(1, quantity05.MolesPerSecond); Assert.Equal(MolarFlowUnit.MolePerSecond, quantity05.Unit); var quantity06 = MolarFlow.From(1, MolarFlowUnit.PoundMolePerHour); - AssertEx.EqualTolerance(1, quantity06.PoundMolesPerHour, PoundMolesPerHourTolerance); + Assert.Equal(1, quantity06.PoundMolesPerHour); Assert.Equal(MolarFlowUnit.PoundMolePerHour, quantity06.Unit); var quantity07 = MolarFlow.From(1, MolarFlowUnit.PoundMolePerMinute); - AssertEx.EqualTolerance(1, quantity07.PoundMolesPerMinute, PoundMolesPerMinuteTolerance); + Assert.Equal(1, quantity07.PoundMolesPerMinute); Assert.Equal(MolarFlowUnit.PoundMolePerMinute, quantity07.Unit); var quantity08 = MolarFlow.From(1, MolarFlowUnit.PoundMolePerSecond); - AssertEx.EqualTolerance(1, quantity08.PoundMolesPerSecond, PoundMolesPerSecondTolerance); + Assert.Equal(1, quantity08.PoundMolesPerSecond); Assert.Equal(MolarFlowUnit.PoundMolePerSecond, quantity08.Unit); } @@ -347,131 +365,40 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 kkmol/h", MolarFlowUnit.KilomolePerHour, 4.2)] + [InlineData("en-US", "4.2 kmol/min", MolarFlowUnit.KilomolePerMinute, 4.2)] + [InlineData("en-US", "4.2 kmol/s", MolarFlowUnit.KilomolePerSecond, 4.2)] + [InlineData("en-US", "4.2 kmol/h", MolarFlowUnit.MolePerHour, 4.2)] + [InlineData("en-US", "4.2 mol/min", MolarFlowUnit.MolePerMinute, 4.2)] + [InlineData("en-US", "4.2 mol/s", MolarFlowUnit.MolePerSecond, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = MolarFlow.Parse("1 kkmol/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilomolesPerHour, KilomolesPerHourTolerance); - Assert.Equal(MolarFlowUnit.KilomolePerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarFlow.Parse("1 kmol/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilomolesPerMinute, KilomolesPerMinuteTolerance); - Assert.Equal(MolarFlowUnit.KilomolePerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarFlow.Parse("1 kmol/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilomolesPerSecond, KilomolesPerSecondTolerance); - Assert.Equal(MolarFlowUnit.KilomolePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarFlow.Parse("1 kmol/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MolesPerHour, MolesPerHourTolerance); - Assert.Equal(MolarFlowUnit.MolePerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarFlow.Parse("1 mol/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MolesPerMinute, MolesPerMinuteTolerance); - Assert.Equal(MolarFlowUnit.MolePerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarFlow.Parse("1 mol/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MolesPerSecond, MolesPerSecondTolerance); - Assert.Equal(MolarFlowUnit.MolePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarFlow.Parse("1 lbmol/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundMolesPerHour, PoundMolesPerHourTolerance); - Assert.Equal(MolarFlowUnit.PoundMolePerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarFlow.Parse("1 lbmol/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundMolesPerMinute, PoundMolesPerMinuteTolerance); - Assert.Equal(MolarFlowUnit.PoundMolePerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarFlow.Parse("1 lbmol/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundMolesPerSecond, PoundMolesPerSecondTolerance); - Assert.Equal(MolarFlowUnit.PoundMolePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = MolarFlow.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 kkmol/h", MolarFlowUnit.KilomolePerHour, 4.2)] + [InlineData("en-US", "4.2 kmol/min", MolarFlowUnit.KilomolePerMinute, 4.2)] + [InlineData("en-US", "4.2 kmol/s", MolarFlowUnit.KilomolePerSecond, 4.2)] + [InlineData("en-US", "4.2 kmol/h", MolarFlowUnit.MolePerHour, 4.2)] + [InlineData("en-US", "4.2 mol/min", MolarFlowUnit.MolePerMinute, 4.2)] + [InlineData("en-US", "4.2 mol/s", MolarFlowUnit.MolePerSecond, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(MolarFlow.TryParse("1 kkmol/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilomolesPerHour, KilomolesPerHourTolerance); - Assert.Equal(MolarFlowUnit.KilomolePerHour, parsed.Unit); - } - - { - Assert.True(MolarFlow.TryParse("1 kmol/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilomolesPerMinute, KilomolesPerMinuteTolerance); - Assert.Equal(MolarFlowUnit.KilomolePerMinute, parsed.Unit); - } - - { - Assert.True(MolarFlow.TryParse("1 kmol/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilomolesPerSecond, KilomolesPerSecondTolerance); - Assert.Equal(MolarFlowUnit.KilomolePerSecond, parsed.Unit); - } - - { - Assert.True(MolarFlow.TryParse("1 kmol/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MolesPerHour, MolesPerHourTolerance); - Assert.Equal(MolarFlowUnit.MolePerHour, parsed.Unit); - } - - { - Assert.True(MolarFlow.TryParse("1 mol/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MolesPerMinute, MolesPerMinuteTolerance); - Assert.Equal(MolarFlowUnit.MolePerMinute, parsed.Unit); - } - - { - Assert.True(MolarFlow.TryParse("1 mol/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MolesPerSecond, MolesPerSecondTolerance); - Assert.Equal(MolarFlowUnit.MolePerSecond, parsed.Unit); - } - - { - Assert.True(MolarFlow.TryParse("1 lbmol/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundMolesPerHour, PoundMolesPerHourTolerance); - Assert.Equal(MolarFlowUnit.PoundMolePerHour, parsed.Unit); - } - - { - Assert.True(MolarFlow.TryParse("1 lbmol/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundMolesPerMinute, PoundMolesPerMinuteTolerance); - Assert.Equal(MolarFlowUnit.PoundMolePerMinute, parsed.Unit); - } - - { - Assert.True(MolarFlow.TryParse("1 lbmol/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundMolesPerSecond, PoundMolesPerSecondTolerance); - Assert.Equal(MolarFlowUnit.PoundMolePerSecond, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(MolarFlow.TryParse(quantityString, out MolarFlow parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -612,6 +539,35 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, MolarF Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", MolarFlowUnit.KilomolePerHour, "kkmol/h")] + [InlineData("en-US", MolarFlowUnit.KilomolePerMinute, "kmol/min")] + [InlineData("en-US", MolarFlowUnit.KilomolePerSecond, "kmol/s")] + [InlineData("en-US", MolarFlowUnit.MolePerHour, "kmol/h")] + [InlineData("en-US", MolarFlowUnit.MolePerMinute, "mol/min")] + [InlineData("en-US", MolarFlowUnit.MolePerSecond, "mol/s")] + [InlineData("en-US", MolarFlowUnit.PoundMolePerHour, "lbmol/h")] + [InlineData("en-US", MolarFlowUnit.PoundMolePerMinute, "lbmol/min")] + [InlineData("en-US", MolarFlowUnit.PoundMolePerSecond, "lbmol/s")] + public void GetAbbreviationForCulture(string culture, MolarFlowUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = MolarFlow.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(MolarFlow.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = MolarFlow.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(MolarFlowUnit unit) @@ -642,6 +598,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); }); } @@ -665,40 +622,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] @@ -744,8 +703,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); @@ -783,34 +740,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = MolarFlow.FromMolesPerSecond(1); - Assert.True(v.Equals(MolarFlow.FromMolesPerSecond(1), MolesPerSecondTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(MolarFlow.Zero, MolesPerSecondTolerance, ComparisonType.Relative)); - Assert.True(MolarFlow.FromMolesPerSecond(100).Equals(MolarFlow.FromMolesPerSecond(120), 0.3, ComparisonType.Relative)); - Assert.False(MolarFlow.FromMolesPerSecond(100).Equals(MolarFlow.FromMolesPerSecond(120), 0.1, ComparisonType.Relative)); + MolarFlow molepersecond = MolarFlow.FromMolesPerSecond(1); + Assert.False(molepersecond.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = MolarFlow.FromMolesPerSecond(1); - Assert.Throws(() => v.Equals(MolarFlow.FromMolesPerSecond(1), -1, ComparisonType.Relative)); + MolarFlow molepersecond = MolarFlow.FromMolesPerSecond(1); + Assert.False(molepersecond.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - MolarFlow molepersecond = MolarFlow.FromMolesPerSecond(1); - Assert.False(molepersecond.Equals(new object())); + var quantity = MolarFlow.FromMolesPerSecond(firstValue); + var otherQuantity = MolarFlow.FromMolesPerSecond(secondValue); + MolarFlow maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - MolarFlow molepersecond = MolarFlow.FromMolesPerSecond(1); - Assert.False(molepersecond.Equals(null)); + var quantity = MolarFlow.FromMolesPerSecond(1); + var negativeTolerance = MolarFlow.FromMolesPerSecond(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -829,6 +795,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() { @@ -903,158 +881,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = MolarFlow.FromMolesPerSecond(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = MolarFlow.FromMolesPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = MolarFlow.FromMolesPerSecond(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = MolarFlow.FromMolesPerSecond(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = MolarFlow.FromMolesPerSecond(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = MolarFlow.FromMolesPerSecond(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = MolarFlow.FromMolesPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = MolarFlow.FromMolesPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = MolarFlow.FromMolesPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = MolarFlow.FromMolesPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = MolarFlow.FromMolesPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = MolarFlow.FromMolesPerSecond(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = MolarFlow.FromMolesPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = MolarFlow.FromMolesPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = MolarFlow.FromMolesPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = MolarFlow.FromMolesPerSecond(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(MolarFlow))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = MolarFlow.FromMolesPerSecond(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MolarFlowUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = MolarFlow.FromMolesPerSecond(1.0); - Assert.Equal(MolarFlow.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = MolarFlow.FromMolesPerSecond(1.0); - Assert.Equal(MolarFlow.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = MolarFlow.FromMolesPerSecond(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = MolarFlow.FromMolesPerSecond(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = MolarFlow.FromMolesPerSecond(1.0); - Assert.Equal(new {MolarFlow.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 8d3859ffbb..ff284caa2c 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarMassTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarMassTestsBase.g.cs @@ -144,7 +144,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new MolarMass(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -157,15 +157,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void MolarMass_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + MolarMassUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new MolarMass(1, MolarMassUnit.KilogramPerMole); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(MolarMass.Zero, quantityInfo.Zero); Assert.Equal("MolarMass", quantityInfo.Name); + Assert.Equal(MolarMass.Zero, quantityInfo.Zero); + Assert.Equal(MolarMass.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(MolarMass.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + [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] @@ -191,55 +209,55 @@ public void KilogramPerMoleToMolarMassUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = MolarMass.From(1, MolarMassUnit.CentigramPerMole); - AssertEx.EqualTolerance(1, quantity00.CentigramsPerMole, CentigramsPerMoleTolerance); + Assert.Equal(1, quantity00.CentigramsPerMole); Assert.Equal(MolarMassUnit.CentigramPerMole, quantity00.Unit); var quantity01 = MolarMass.From(1, MolarMassUnit.DecagramPerMole); - AssertEx.EqualTolerance(1, quantity01.DecagramsPerMole, DecagramsPerMoleTolerance); + Assert.Equal(1, quantity01.DecagramsPerMole); Assert.Equal(MolarMassUnit.DecagramPerMole, quantity01.Unit); var quantity02 = MolarMass.From(1, MolarMassUnit.DecigramPerMole); - AssertEx.EqualTolerance(1, quantity02.DecigramsPerMole, DecigramsPerMoleTolerance); + Assert.Equal(1, quantity02.DecigramsPerMole); Assert.Equal(MolarMassUnit.DecigramPerMole, quantity02.Unit); var quantity03 = MolarMass.From(1, MolarMassUnit.GramPerMole); - AssertEx.EqualTolerance(1, quantity03.GramsPerMole, GramsPerMoleTolerance); + Assert.Equal(1, quantity03.GramsPerMole); Assert.Equal(MolarMassUnit.GramPerMole, quantity03.Unit); var quantity04 = MolarMass.From(1, MolarMassUnit.HectogramPerMole); - AssertEx.EqualTolerance(1, quantity04.HectogramsPerMole, HectogramsPerMoleTolerance); + Assert.Equal(1, quantity04.HectogramsPerMole); Assert.Equal(MolarMassUnit.HectogramPerMole, quantity04.Unit); var quantity05 = MolarMass.From(1, MolarMassUnit.KilogramPerKilomole); - AssertEx.EqualTolerance(1, quantity05.KilogramsPerKilomole, KilogramsPerKilomoleTolerance); + Assert.Equal(1, quantity05.KilogramsPerKilomole); Assert.Equal(MolarMassUnit.KilogramPerKilomole, quantity05.Unit); var quantity06 = MolarMass.From(1, MolarMassUnit.KilogramPerMole); - AssertEx.EqualTolerance(1, quantity06.KilogramsPerMole, KilogramsPerMoleTolerance); + Assert.Equal(1, quantity06.KilogramsPerMole); Assert.Equal(MolarMassUnit.KilogramPerMole, quantity06.Unit); var quantity07 = MolarMass.From(1, MolarMassUnit.KilopoundPerMole); - AssertEx.EqualTolerance(1, quantity07.KilopoundsPerMole, KilopoundsPerMoleTolerance); + Assert.Equal(1, quantity07.KilopoundsPerMole); Assert.Equal(MolarMassUnit.KilopoundPerMole, quantity07.Unit); var quantity08 = MolarMass.From(1, MolarMassUnit.MegapoundPerMole); - AssertEx.EqualTolerance(1, quantity08.MegapoundsPerMole, MegapoundsPerMoleTolerance); + Assert.Equal(1, quantity08.MegapoundsPerMole); Assert.Equal(MolarMassUnit.MegapoundPerMole, quantity08.Unit); var quantity09 = MolarMass.From(1, MolarMassUnit.MicrogramPerMole); - AssertEx.EqualTolerance(1, quantity09.MicrogramsPerMole, MicrogramsPerMoleTolerance); + Assert.Equal(1, quantity09.MicrogramsPerMole); Assert.Equal(MolarMassUnit.MicrogramPerMole, quantity09.Unit); var quantity10 = MolarMass.From(1, MolarMassUnit.MilligramPerMole); - AssertEx.EqualTolerance(1, quantity10.MilligramsPerMole, MilligramsPerMoleTolerance); + Assert.Equal(1, quantity10.MilligramsPerMole); Assert.Equal(MolarMassUnit.MilligramPerMole, quantity10.Unit); var quantity11 = MolarMass.From(1, MolarMassUnit.NanogramPerMole); - AssertEx.EqualTolerance(1, quantity11.NanogramsPerMole, NanogramsPerMoleTolerance); + Assert.Equal(1, quantity11.NanogramsPerMole); Assert.Equal(MolarMassUnit.NanogramPerMole, quantity11.Unit); var quantity12 = MolarMass.From(1, MolarMassUnit.PoundPerMole); - AssertEx.EqualTolerance(1, quantity12.PoundsPerMole, PoundsPerMoleTolerance); + Assert.Equal(1, quantity12.PoundsPerMole); Assert.Equal(MolarMassUnit.PoundPerMole, quantity12.Unit); } @@ -387,339 +405,72 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 cg/mol", MolarMassUnit.CentigramPerMole, 4.2)] + [InlineData("en-US", "4.2 dag/mol", MolarMassUnit.DecagramPerMole, 4.2)] + [InlineData("en-US", "4.2 dg/mol", MolarMassUnit.DecigramPerMole, 4.2)] + [InlineData("en-US", "4.2 g/mol", MolarMassUnit.GramPerMole, 4.2)] + [InlineData("en-US", "4.2 hg/mol", MolarMassUnit.HectogramPerMole, 4.2)] + [InlineData("en-US", "4.2 kg/kmol", MolarMassUnit.KilogramPerKilomole, 4.2)] + [InlineData("en-US", "4.2 kg/mol", MolarMassUnit.KilogramPerMole, 4.2)] + [InlineData("en-US", "4.2 klb/mol", MolarMassUnit.KilopoundPerMole, 4.2)] + [InlineData("en-US", "4.2 Mlb/mol", MolarMassUnit.MegapoundPerMole, 4.2)] + [InlineData("en-US", "4.2 µg/mol", MolarMassUnit.MicrogramPerMole, 4.2)] + [InlineData("en-US", "4.2 mg/mol", MolarMassUnit.MilligramPerMole, 4.2)] + [InlineData("en-US", "4.2 ng/mol", MolarMassUnit.NanogramPerMole, 4.2)] + [InlineData("en-US", "4.2 lb/mol", MolarMassUnit.PoundPerMole, 4.2)] + [InlineData("ru-RU", "4,2 сг/моль", MolarMassUnit.CentigramPerMole, 4.2)] + [InlineData("ru-RU", "4,2 даг/моль", MolarMassUnit.DecagramPerMole, 4.2)] + [InlineData("ru-RU", "4,2 дг/моль", MolarMassUnit.DecigramPerMole, 4.2)] + [InlineData("ru-RU", "4,2 г/моль", MolarMassUnit.GramPerMole, 4.2)] + [InlineData("ru-RU", "4,2 гг/моль", MolarMassUnit.HectogramPerMole, 4.2)] + [InlineData("ru-RU", "4,2 кг/моль", MolarMassUnit.KilogramPerMole, 4.2)] + [InlineData("ru-RU", "4,2 кфунт/моль", MolarMassUnit.KilopoundPerMole, 4.2)] + [InlineData("ru-RU", "4,2 Мфунт/моль", MolarMassUnit.MegapoundPerMole, 4.2)] + [InlineData("ru-RU", "4,2 мкг/моль", MolarMassUnit.MicrogramPerMole, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = MolarMass.Parse("1 cg/mol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentigramsPerMole, CentigramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.CentigramPerMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarMass.Parse("1 сг/моль", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CentigramsPerMole, CentigramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.CentigramPerMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarMass.Parse("1 dag/mol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecagramsPerMole, DecagramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.DecagramPerMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarMass.Parse("1 даг/моль", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.DecagramsPerMole, DecagramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.DecagramPerMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarMass.Parse("1 dg/mol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecigramsPerMole, DecigramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.DecigramPerMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarMass.Parse("1 дг/моль", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.DecigramsPerMole, DecigramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.DecigramPerMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarMass.Parse("1 g/mol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerMole, GramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.GramPerMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarMass.Parse("1 г/моль", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.GramsPerMole, GramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.GramPerMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarMass.Parse("1 hg/mol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.HectogramsPerMole, HectogramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.HectogramPerMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarMass.Parse("1 гг/моль", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.HectogramsPerMole, HectogramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.HectogramPerMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarMass.Parse("1 kg/kmol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerKilomole, KilogramsPerKilomoleTolerance); - Assert.Equal(MolarMassUnit.KilogramPerKilomole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarMass.Parse("1 kg/mol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerMole, KilogramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.KilogramPerMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarMass.Parse("1 кг/моль", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerMole, KilogramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.KilogramPerMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarMass.Parse("1 klb/mol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsPerMole, KilopoundsPerMoleTolerance); - Assert.Equal(MolarMassUnit.KilopoundPerMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarMass.Parse("1 кфунт/моль", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilopoundsPerMole, KilopoundsPerMoleTolerance); - Assert.Equal(MolarMassUnit.KilopoundPerMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarMass.Parse("1 Mlb/mol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegapoundsPerMole, MegapoundsPerMoleTolerance); - Assert.Equal(MolarMassUnit.MegapoundPerMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarMass.Parse("1 Мфунт/моль", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MegapoundsPerMole, MegapoundsPerMoleTolerance); - Assert.Equal(MolarMassUnit.MegapoundPerMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarMass.Parse("1 µg/mol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerMole, MicrogramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.MicrogramPerMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarMass.Parse("1 мкг/моль", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerMole, MicrogramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.MicrogramPerMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarMass.Parse("1 mg/mol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilligramsPerMole, MilligramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.MilligramPerMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarMass.Parse("1 мг/моль", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MilligramsPerMole, MilligramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.MilligramPerMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarMass.Parse("1 ng/mol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanogramsPerMole, NanogramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.NanogramPerMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarMass.Parse("1 нг/моль", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.NanogramsPerMole, NanogramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.NanogramPerMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarMass.Parse("1 lb/mol", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerMole, PoundsPerMoleTolerance); - Assert.Equal(MolarMassUnit.PoundPerMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = MolarMass.Parse("1 фунт/моль", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.PoundsPerMole, PoundsPerMoleTolerance); - Assert.Equal(MolarMassUnit.PoundPerMole, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = MolarMass.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 cg/mol", MolarMassUnit.CentigramPerMole, 4.2)] + [InlineData("en-US", "4.2 dag/mol", MolarMassUnit.DecagramPerMole, 4.2)] + [InlineData("en-US", "4.2 dg/mol", MolarMassUnit.DecigramPerMole, 4.2)] + [InlineData("en-US", "4.2 g/mol", MolarMassUnit.GramPerMole, 4.2)] + [InlineData("en-US", "4.2 hg/mol", MolarMassUnit.HectogramPerMole, 4.2)] + [InlineData("en-US", "4.2 kg/kmol", MolarMassUnit.KilogramPerKilomole, 4.2)] + [InlineData("en-US", "4.2 kg/mol", MolarMassUnit.KilogramPerMole, 4.2)] + [InlineData("en-US", "4.2 klb/mol", MolarMassUnit.KilopoundPerMole, 4.2)] + [InlineData("en-US", "4.2 Mlb/mol", MolarMassUnit.MegapoundPerMole, 4.2)] + [InlineData("en-US", "4.2 µg/mol", MolarMassUnit.MicrogramPerMole, 4.2)] + [InlineData("en-US", "4.2 mg/mol", MolarMassUnit.MilligramPerMole, 4.2)] + [InlineData("en-US", "4.2 ng/mol", MolarMassUnit.NanogramPerMole, 4.2)] + [InlineData("en-US", "4.2 lb/mol", MolarMassUnit.PoundPerMole, 4.2)] + [InlineData("ru-RU", "4,2 сг/моль", MolarMassUnit.CentigramPerMole, 4.2)] + [InlineData("ru-RU", "4,2 даг/моль", MolarMassUnit.DecagramPerMole, 4.2)] + [InlineData("ru-RU", "4,2 дг/моль", MolarMassUnit.DecigramPerMole, 4.2)] + [InlineData("ru-RU", "4,2 г/моль", MolarMassUnit.GramPerMole, 4.2)] + [InlineData("ru-RU", "4,2 гг/моль", MolarMassUnit.HectogramPerMole, 4.2)] + [InlineData("ru-RU", "4,2 кг/моль", MolarMassUnit.KilogramPerMole, 4.2)] + [InlineData("ru-RU", "4,2 кфунт/моль", MolarMassUnit.KilopoundPerMole, 4.2)] + [InlineData("ru-RU", "4,2 Мфунт/моль", MolarMassUnit.MegapoundPerMole, 4.2)] + [InlineData("ru-RU", "4,2 мкг/моль", MolarMassUnit.MicrogramPerMole, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(MolarMass.TryParse("1 cg/mol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentigramsPerMole, CentigramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.CentigramPerMole, parsed.Unit); - } - - { - Assert.True(MolarMass.TryParse("1 сг/моль", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentigramsPerMole, CentigramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.CentigramPerMole, parsed.Unit); - } - - { - Assert.True(MolarMass.TryParse("1 dag/mol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecagramsPerMole, DecagramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.DecagramPerMole, parsed.Unit); - } - - { - Assert.True(MolarMass.TryParse("1 даг/моль", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecagramsPerMole, DecagramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.DecagramPerMole, parsed.Unit); - } - - { - Assert.True(MolarMass.TryParse("1 dg/mol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecigramsPerMole, DecigramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.DecigramPerMole, parsed.Unit); - } - - { - Assert.True(MolarMass.TryParse("1 дг/моль", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecigramsPerMole, DecigramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.DecigramPerMole, parsed.Unit); - } - - { - Assert.True(MolarMass.TryParse("1 g/mol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerMole, GramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.GramPerMole, parsed.Unit); - } - - { - Assert.True(MolarMass.TryParse("1 г/моль", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerMole, GramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.GramPerMole, parsed.Unit); - } - - { - Assert.True(MolarMass.TryParse("1 hg/mol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HectogramsPerMole, HectogramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.HectogramPerMole, parsed.Unit); - } - - { - Assert.True(MolarMass.TryParse("1 гг/моль", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HectogramsPerMole, HectogramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.HectogramPerMole, parsed.Unit); - } - - { - Assert.True(MolarMass.TryParse("1 kg/kmol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerKilomole, KilogramsPerKilomoleTolerance); - Assert.Equal(MolarMassUnit.KilogramPerKilomole, parsed.Unit); - } - - { - Assert.True(MolarMass.TryParse("1 kg/mol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerMole, KilogramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.KilogramPerMole, parsed.Unit); - } - - { - Assert.True(MolarMass.TryParse("1 кг/моль", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerMole, KilogramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.KilogramPerMole, parsed.Unit); - } - - { - Assert.True(MolarMass.TryParse("1 klb/mol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsPerMole, KilopoundsPerMoleTolerance); - Assert.Equal(MolarMassUnit.KilopoundPerMole, parsed.Unit); - } - - { - Assert.True(MolarMass.TryParse("1 кфунт/моль", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsPerMole, KilopoundsPerMoleTolerance); - Assert.Equal(MolarMassUnit.KilopoundPerMole, parsed.Unit); - } - - { - Assert.True(MolarMass.TryParse("1 Mlb/mol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegapoundsPerMole, MegapoundsPerMoleTolerance); - Assert.Equal(MolarMassUnit.MegapoundPerMole, parsed.Unit); - } - - { - Assert.True(MolarMass.TryParse("1 Мфунт/моль", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegapoundsPerMole, MegapoundsPerMoleTolerance); - Assert.Equal(MolarMassUnit.MegapoundPerMole, parsed.Unit); - } - - { - Assert.True(MolarMass.TryParse("1 µg/mol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerMole, MicrogramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.MicrogramPerMole, parsed.Unit); - } - - { - Assert.True(MolarMass.TryParse("1 мкг/моль", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrogramsPerMole, MicrogramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.MicrogramPerMole, parsed.Unit); - } - - { - Assert.True(MolarMass.TryParse("1 mg/mol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligramsPerMole, MilligramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.MilligramPerMole, parsed.Unit); - } - - { - Assert.True(MolarMass.TryParse("1 мг/моль", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilligramsPerMole, MilligramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.MilligramPerMole, parsed.Unit); - } - - { - Assert.True(MolarMass.TryParse("1 ng/mol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanogramsPerMole, NanogramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.NanogramPerMole, parsed.Unit); - } - - { - Assert.True(MolarMass.TryParse("1 нг/моль", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanogramsPerMole, NanogramsPerMoleTolerance); - Assert.Equal(MolarMassUnit.NanogramPerMole, parsed.Unit); - } - - { - Assert.True(MolarMass.TryParse("1 lb/mol", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerMole, PoundsPerMoleTolerance); - Assert.Equal(MolarMassUnit.PoundPerMole, parsed.Unit); - } - - { - Assert.True(MolarMass.TryParse("1 фунт/моль", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerMole, PoundsPerMoleTolerance); - Assert.Equal(MolarMassUnit.PoundPerMole, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(MolarMass.TryParse(quantityString, out MolarMass parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -940,6 +691,51 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, MolarM Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", MolarMassUnit.CentigramPerMole, "cg/mol")] + [InlineData("en-US", MolarMassUnit.DecagramPerMole, "dag/mol")] + [InlineData("en-US", MolarMassUnit.DecigramPerMole, "dg/mol")] + [InlineData("en-US", MolarMassUnit.GramPerMole, "g/mol")] + [InlineData("en-US", MolarMassUnit.HectogramPerMole, "hg/mol")] + [InlineData("en-US", MolarMassUnit.KilogramPerKilomole, "kg/kmol")] + [InlineData("en-US", MolarMassUnit.KilogramPerMole, "kg/mol")] + [InlineData("en-US", MolarMassUnit.KilopoundPerMole, "klb/mol")] + [InlineData("en-US", MolarMassUnit.MegapoundPerMole, "Mlb/mol")] + [InlineData("en-US", MolarMassUnit.MicrogramPerMole, "µg/mol")] + [InlineData("en-US", MolarMassUnit.MilligramPerMole, "mg/mol")] + [InlineData("en-US", MolarMassUnit.NanogramPerMole, "ng/mol")] + [InlineData("en-US", MolarMassUnit.PoundPerMole, "lb/mol")] + [InlineData("ru-RU", MolarMassUnit.CentigramPerMole, "сг/моль")] + [InlineData("ru-RU", MolarMassUnit.DecagramPerMole, "даг/моль")] + [InlineData("ru-RU", MolarMassUnit.DecigramPerMole, "дг/моль")] + [InlineData("ru-RU", MolarMassUnit.GramPerMole, "г/моль")] + [InlineData("ru-RU", MolarMassUnit.HectogramPerMole, "гг/моль")] + [InlineData("ru-RU", MolarMassUnit.KilogramPerMole, "кг/моль")] + [InlineData("ru-RU", MolarMassUnit.KilopoundPerMole, "кфунт/моль")] + [InlineData("ru-RU", MolarMassUnit.MegapoundPerMole, "Мфунт/моль")] + [InlineData("ru-RU", MolarMassUnit.MicrogramPerMole, "мкг/моль")] + [InlineData("ru-RU", MolarMassUnit.MilligramPerMole, "мг/моль")] + [InlineData("ru-RU", MolarMassUnit.NanogramPerMole, "нг/моль")] + [InlineData("ru-RU", MolarMassUnit.PoundPerMole, "фунт/моль")] + public void GetAbbreviationForCulture(string culture, MolarMassUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = MolarMass.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(MolarMass.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = MolarMass.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(MolarMassUnit unit) @@ -970,6 +766,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); }); } @@ -993,44 +790,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] @@ -1076,8 +875,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); @@ -1114,23 +911,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = MolarMass.FromKilogramsPerMole(1); - Assert.True(v.Equals(MolarMass.FromKilogramsPerMole(1), KilogramsPerMoleTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(MolarMass.Zero, KilogramsPerMoleTolerance, ComparisonType.Relative)); - Assert.True(MolarMass.FromKilogramsPerMole(100).Equals(MolarMass.FromKilogramsPerMole(120), 0.3, ComparisonType.Relative)); - Assert.False(MolarMass.FromKilogramsPerMole(100).Equals(MolarMass.FromKilogramsPerMole(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = MolarMass.FromKilogramsPerMole(1); - Assert.Throws(() => v.Equals(MolarMass.FromKilogramsPerMole(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1145,6 +925,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(kilogrampermole.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = MolarMass.FromKilogramsPerMole(1); + var negativeTolerance = MolarMass.FromKilogramsPerMole(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1161,6 +967,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() { @@ -1243,158 +1061,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(MolarMass))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MolarMassUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal(MolarMass.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal(MolarMass.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal(new {MolarMass.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 3154ffaea6..36384e8f50 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarityTestsBase.g.cs @@ -136,7 +136,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Molarity(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -149,15 +149,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Molarity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + MolarityUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Molarity(1, MolarityUnit.MolePerCubicMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Molarity.Zero, quantityInfo.Zero); Assert.Equal("Molarity", quantityInfo.Name); + Assert.Equal(Molarity.Zero, quantityInfo.Zero); + Assert.Equal(Molarity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Molarity.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void MolarityInfo_CreateWithCustomUnitInfos() + { + MolarityUnit[] expectedUnits = [MolarityUnit.MolePerCubicMeter]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -181,47 +199,47 @@ public void MolePerCubicMeterToMolarityUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Molarity.From(1, MolarityUnit.CentimolePerLiter); - AssertEx.EqualTolerance(1, quantity00.CentimolesPerLiter, CentimolesPerLiterTolerance); + Assert.Equal(1, quantity00.CentimolesPerLiter); Assert.Equal(MolarityUnit.CentimolePerLiter, quantity00.Unit); var quantity01 = Molarity.From(1, MolarityUnit.DecimolePerLiter); - AssertEx.EqualTolerance(1, quantity01.DecimolesPerLiter, DecimolesPerLiterTolerance); + Assert.Equal(1, quantity01.DecimolesPerLiter); Assert.Equal(MolarityUnit.DecimolePerLiter, quantity01.Unit); var quantity02 = Molarity.From(1, MolarityUnit.FemtomolePerLiter); - AssertEx.EqualTolerance(1, quantity02.FemtomolesPerLiter, FemtomolesPerLiterTolerance); + Assert.Equal(1, quantity02.FemtomolesPerLiter); Assert.Equal(MolarityUnit.FemtomolePerLiter, quantity02.Unit); var quantity03 = Molarity.From(1, MolarityUnit.KilomolePerCubicMeter); - AssertEx.EqualTolerance(1, quantity03.KilomolesPerCubicMeter, KilomolesPerCubicMeterTolerance); + Assert.Equal(1, quantity03.KilomolesPerCubicMeter); Assert.Equal(MolarityUnit.KilomolePerCubicMeter, quantity03.Unit); var quantity04 = Molarity.From(1, MolarityUnit.MicromolePerLiter); - AssertEx.EqualTolerance(1, quantity04.MicromolesPerLiter, MicromolesPerLiterTolerance); + Assert.Equal(1, quantity04.MicromolesPerLiter); Assert.Equal(MolarityUnit.MicromolePerLiter, quantity04.Unit); var quantity05 = Molarity.From(1, MolarityUnit.MillimolePerLiter); - AssertEx.EqualTolerance(1, quantity05.MillimolesPerLiter, MillimolesPerLiterTolerance); + Assert.Equal(1, quantity05.MillimolesPerLiter); Assert.Equal(MolarityUnit.MillimolePerLiter, quantity05.Unit); var quantity06 = Molarity.From(1, MolarityUnit.MolePerCubicMeter); - AssertEx.EqualTolerance(1, quantity06.MolesPerCubicMeter, MolesPerCubicMeterTolerance); + Assert.Equal(1, quantity06.MolesPerCubicMeter); Assert.Equal(MolarityUnit.MolePerCubicMeter, quantity06.Unit); var quantity07 = Molarity.From(1, MolarityUnit.MolePerLiter); - AssertEx.EqualTolerance(1, quantity07.MolesPerLiter, MolesPerLiterTolerance); + Assert.Equal(1, quantity07.MolesPerLiter); Assert.Equal(MolarityUnit.MolePerLiter, quantity07.Unit); var quantity08 = Molarity.From(1, MolarityUnit.NanomolePerLiter); - AssertEx.EqualTolerance(1, quantity08.NanomolesPerLiter, NanomolesPerLiterTolerance); + Assert.Equal(1, quantity08.NanomolesPerLiter); Assert.Equal(MolarityUnit.NanomolePerLiter, quantity08.Unit); var quantity09 = Molarity.From(1, MolarityUnit.PicomolePerLiter); - AssertEx.EqualTolerance(1, quantity09.PicomolesPerLiter, PicomolesPerLiterTolerance); + Assert.Equal(1, quantity09.PicomolesPerLiter); Assert.Equal(MolarityUnit.PicomolePerLiter, quantity09.Unit); var quantity10 = Molarity.From(1, MolarityUnit.PoundMolePerCubicFoot); - AssertEx.EqualTolerance(1, quantity10.PoundMolesPerCubicFoot, PoundMolesPerCubicFootTolerance); + Assert.Equal(1, quantity10.PoundMolesPerCubicFoot); Assert.Equal(MolarityUnit.PoundMolePerCubicFoot, quantity10.Unit); } @@ -367,261 +385,60 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 cmol/l", MolarityUnit.CentimolePerLiter, 4.2)] + [InlineData("en-US", "4.2 cM", MolarityUnit.CentimolePerLiter, 4.2)] + [InlineData("en-US", "4.2 dmol/l", MolarityUnit.DecimolePerLiter, 4.2)] + [InlineData("en-US", "4.2 dM", MolarityUnit.DecimolePerLiter, 4.2)] + [InlineData("en-US", "4.2 fmol/l", MolarityUnit.FemtomolePerLiter, 4.2)] + [InlineData("en-US", "4.2 fM", MolarityUnit.FemtomolePerLiter, 4.2)] + [InlineData("en-US", "4.2 kmol/m³", MolarityUnit.KilomolePerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 µmol/l", MolarityUnit.MicromolePerLiter, 4.2)] + [InlineData("en-US", "4.2 µM", MolarityUnit.MicromolePerLiter, 4.2)] + [InlineData("en-US", "4.2 mmol/l", MolarityUnit.MillimolePerLiter, 4.2)] + [InlineData("en-US", "4.2 mM", MolarityUnit.MillimolePerLiter, 4.2)] + [InlineData("en-US", "4.2 mol/m³", MolarityUnit.MolePerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 mol/l", MolarityUnit.MolePerLiter, 4.2)] + [InlineData("en-US", "4.2 M", MolarityUnit.MolePerLiter, 4.2)] + [InlineData("en-US", "4.2 nmol/l", MolarityUnit.NanomolePerLiter, 4.2)] + [InlineData("en-US", "4.2 nM", MolarityUnit.NanomolePerLiter, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = Molarity.Parse("1 cmol/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentimolesPerLiter, CentimolesPerLiterTolerance); - Assert.Equal(MolarityUnit.CentimolePerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Molarity.Parse("1 cM", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentimolesPerLiter, CentimolesPerLiterTolerance); - Assert.Equal(MolarityUnit.CentimolePerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Molarity.Parse("1 dmol/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecimolesPerLiter, DecimolesPerLiterTolerance); - Assert.Equal(MolarityUnit.DecimolePerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Molarity.Parse("1 dM", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecimolesPerLiter, DecimolesPerLiterTolerance); - Assert.Equal(MolarityUnit.DecimolePerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Molarity.Parse("1 fmol/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.FemtomolesPerLiter, FemtomolesPerLiterTolerance); - Assert.Equal(MolarityUnit.FemtomolePerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Molarity.Parse("1 fM", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.FemtomolesPerLiter, FemtomolesPerLiterTolerance); - Assert.Equal(MolarityUnit.FemtomolePerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Molarity.Parse("1 kmol/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilomolesPerCubicMeter, KilomolesPerCubicMeterTolerance); - Assert.Equal(MolarityUnit.KilomolePerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Molarity.Parse("1 µmol/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicromolesPerLiter, MicromolesPerLiterTolerance); - Assert.Equal(MolarityUnit.MicromolePerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Molarity.Parse("1 µM", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicromolesPerLiter, MicromolesPerLiterTolerance); - Assert.Equal(MolarityUnit.MicromolePerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Molarity.Parse("1 mmol/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillimolesPerLiter, MillimolesPerLiterTolerance); - Assert.Equal(MolarityUnit.MillimolePerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Molarity.Parse("1 mM", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillimolesPerLiter, MillimolesPerLiterTolerance); - Assert.Equal(MolarityUnit.MillimolePerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Molarity.Parse("1 mol/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MolesPerCubicMeter, MolesPerCubicMeterTolerance); - Assert.Equal(MolarityUnit.MolePerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Molarity.Parse("1 mol/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MolesPerLiter, MolesPerLiterTolerance); - Assert.Equal(MolarityUnit.MolePerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Molarity.Parse("1 M", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MolesPerLiter, MolesPerLiterTolerance); - Assert.Equal(MolarityUnit.MolePerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Molarity.Parse("1 nmol/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanomolesPerLiter, NanomolesPerLiterTolerance); - Assert.Equal(MolarityUnit.NanomolePerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Molarity.Parse("1 nM", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanomolesPerLiter, NanomolesPerLiterTolerance); - Assert.Equal(MolarityUnit.NanomolePerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Molarity.Parse("1 pmol/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PicomolesPerLiter, PicomolesPerLiterTolerance); - Assert.Equal(MolarityUnit.PicomolePerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Molarity.Parse("1 pM", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PicomolesPerLiter, PicomolesPerLiterTolerance); - Assert.Equal(MolarityUnit.PicomolePerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Molarity.Parse("1 lbmol/ft³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundMolesPerCubicFoot, PoundMolesPerCubicFootTolerance); - Assert.Equal(MolarityUnit.PoundMolePerCubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Molarity.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 cmol/l", MolarityUnit.CentimolePerLiter, 4.2)] + [InlineData("en-US", "4.2 cM", MolarityUnit.CentimolePerLiter, 4.2)] + [InlineData("en-US", "4.2 dmol/l", MolarityUnit.DecimolePerLiter, 4.2)] + [InlineData("en-US", "4.2 dM", MolarityUnit.DecimolePerLiter, 4.2)] + [InlineData("en-US", "4.2 fmol/l", MolarityUnit.FemtomolePerLiter, 4.2)] + [InlineData("en-US", "4.2 fM", MolarityUnit.FemtomolePerLiter, 4.2)] + [InlineData("en-US", "4.2 kmol/m³", MolarityUnit.KilomolePerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 µmol/l", MolarityUnit.MicromolePerLiter, 4.2)] + [InlineData("en-US", "4.2 µM", MolarityUnit.MicromolePerLiter, 4.2)] + [InlineData("en-US", "4.2 mmol/l", MolarityUnit.MillimolePerLiter, 4.2)] + [InlineData("en-US", "4.2 mM", MolarityUnit.MillimolePerLiter, 4.2)] + [InlineData("en-US", "4.2 mol/m³", MolarityUnit.MolePerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 mol/l", MolarityUnit.MolePerLiter, 4.2)] + [InlineData("en-US", "4.2 M", MolarityUnit.MolePerLiter, 4.2)] + [InlineData("en-US", "4.2 nmol/l", MolarityUnit.NanomolePerLiter, 4.2)] + [InlineData("en-US", "4.2 nM", MolarityUnit.NanomolePerLiter, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(Molarity.TryParse("1 cmol/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentimolesPerLiter, CentimolesPerLiterTolerance); - Assert.Equal(MolarityUnit.CentimolePerLiter, parsed.Unit); - } - - { - Assert.True(Molarity.TryParse("1 cM", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentimolesPerLiter, CentimolesPerLiterTolerance); - Assert.Equal(MolarityUnit.CentimolePerLiter, parsed.Unit); - } - - { - Assert.True(Molarity.TryParse("1 dmol/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecimolesPerLiter, DecimolesPerLiterTolerance); - Assert.Equal(MolarityUnit.DecimolePerLiter, parsed.Unit); - } - - { - Assert.True(Molarity.TryParse("1 dM", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecimolesPerLiter, DecimolesPerLiterTolerance); - Assert.Equal(MolarityUnit.DecimolePerLiter, parsed.Unit); - } - - { - Assert.True(Molarity.TryParse("1 fmol/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.FemtomolesPerLiter, FemtomolesPerLiterTolerance); - Assert.Equal(MolarityUnit.FemtomolePerLiter, parsed.Unit); - } - - { - Assert.True(Molarity.TryParse("1 fM", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.FemtomolesPerLiter, FemtomolesPerLiterTolerance); - Assert.Equal(MolarityUnit.FemtomolePerLiter, parsed.Unit); - } - - { - Assert.True(Molarity.TryParse("1 kmol/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilomolesPerCubicMeter, KilomolesPerCubicMeterTolerance); - Assert.Equal(MolarityUnit.KilomolePerCubicMeter, parsed.Unit); - } - - { - Assert.True(Molarity.TryParse("1 µmol/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicromolesPerLiter, MicromolesPerLiterTolerance); - Assert.Equal(MolarityUnit.MicromolePerLiter, parsed.Unit); - } - - { - Assert.True(Molarity.TryParse("1 µM", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicromolesPerLiter, MicromolesPerLiterTolerance); - Assert.Equal(MolarityUnit.MicromolePerLiter, parsed.Unit); - } - - { - Assert.True(Molarity.TryParse("1 mmol/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimolesPerLiter, MillimolesPerLiterTolerance); - Assert.Equal(MolarityUnit.MillimolePerLiter, parsed.Unit); - } - - { - Assert.True(Molarity.TryParse("1 mM", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimolesPerLiter, MillimolesPerLiterTolerance); - Assert.Equal(MolarityUnit.MillimolePerLiter, parsed.Unit); - } - - { - Assert.True(Molarity.TryParse("1 mol/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MolesPerCubicMeter, MolesPerCubicMeterTolerance); - Assert.Equal(MolarityUnit.MolePerCubicMeter, parsed.Unit); - } - - { - Assert.True(Molarity.TryParse("1 mol/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MolesPerLiter, MolesPerLiterTolerance); - Assert.Equal(MolarityUnit.MolePerLiter, parsed.Unit); - } - - { - Assert.True(Molarity.TryParse("1 M", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MolesPerLiter, MolesPerLiterTolerance); - Assert.Equal(MolarityUnit.MolePerLiter, parsed.Unit); - } - - { - Assert.True(Molarity.TryParse("1 nmol/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanomolesPerLiter, NanomolesPerLiterTolerance); - Assert.Equal(MolarityUnit.NanomolePerLiter, parsed.Unit); - } - - { - Assert.True(Molarity.TryParse("1 nM", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanomolesPerLiter, NanomolesPerLiterTolerance); - Assert.Equal(MolarityUnit.NanomolePerLiter, parsed.Unit); - } - - { - Assert.True(Molarity.TryParse("1 pmol/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PicomolesPerLiter, PicomolesPerLiterTolerance); - Assert.Equal(MolarityUnit.PicomolePerLiter, parsed.Unit); - } - - { - Assert.True(Molarity.TryParse("1 pM", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PicomolesPerLiter, PicomolesPerLiterTolerance); - Assert.Equal(MolarityUnit.PicomolePerLiter, parsed.Unit); - } - - { - Assert.True(Molarity.TryParse("1 lbmol/ft³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundMolesPerCubicFoot, PoundMolesPerCubicFootTolerance); - Assert.Equal(MolarityUnit.PoundMolePerCubicFoot, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Molarity.TryParse(quantityString, out Molarity parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -842,6 +659,37 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Molari Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", MolarityUnit.CentimolePerLiter, "cmol/l")] + [InlineData("en-US", MolarityUnit.DecimolePerLiter, "dmol/l")] + [InlineData("en-US", MolarityUnit.FemtomolePerLiter, "fmol/l")] + [InlineData("en-US", MolarityUnit.KilomolePerCubicMeter, "kmol/m³")] + [InlineData("en-US", MolarityUnit.MicromolePerLiter, "µmol/l")] + [InlineData("en-US", MolarityUnit.MillimolePerLiter, "mmol/l")] + [InlineData("en-US", MolarityUnit.MolePerCubicMeter, "mol/m³")] + [InlineData("en-US", MolarityUnit.MolePerLiter, "mol/l")] + [InlineData("en-US", MolarityUnit.NanomolePerLiter, "nmol/l")] + [InlineData("en-US", MolarityUnit.PicomolePerLiter, "pmol/l")] + [InlineData("en-US", MolarityUnit.PoundMolePerCubicFoot, "lbmol/ft³")] + public void GetAbbreviationForCulture(string culture, MolarityUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Molarity.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Molarity.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Molarity.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(MolarityUnit unit) @@ -872,6 +720,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); }); } @@ -895,42 +744,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] @@ -976,8 +827,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); @@ -1014,23 +863,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = Molarity.FromMolesPerCubicMeter(1); - Assert.True(v.Equals(Molarity.FromMolesPerCubicMeter(1), MolesPerCubicMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Molarity.Zero, MolesPerCubicMeterTolerance, ComparisonType.Relative)); - Assert.True(Molarity.FromMolesPerCubicMeter(100).Equals(Molarity.FromMolesPerCubicMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(Molarity.FromMolesPerCubicMeter(100).Equals(Molarity.FromMolesPerCubicMeter(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = Molarity.FromMolesPerCubicMeter(1); - Assert.Throws(() => v.Equals(Molarity.FromMolesPerCubicMeter(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1045,6 +877,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(molepercubicmeter.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = Molarity.FromMolesPerCubicMeter(1); + var negativeTolerance = Molarity.FromMolesPerCubicMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1061,6 +919,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() { @@ -1139,158 +1009,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Molarity))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(MolarityUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal(Molarity.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal(Molarity.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal(new {Molarity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 c03925b221..805214e37a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PermeabilityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PermeabilityTestsBase.g.cs @@ -96,7 +96,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Permeability(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -109,15 +109,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Permeability_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + PermeabilityUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Permeability(1, PermeabilityUnit.HenryPerMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Permeability.Zero, quantityInfo.Zero); Assert.Equal("Permeability", quantityInfo.Name); + Assert.Equal(Permeability.Zero, quantityInfo.Zero); + Assert.Equal(Permeability.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Permeability.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -131,7 +149,7 @@ public void HenryPerMeterToPermeabilityUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Permeability.From(1, PermeabilityUnit.HenryPerMeter); - AssertEx.EqualTolerance(1, quantity00.HenriesPerMeter, HenriesPerMeterTolerance); + Assert.Equal(1, quantity00.HenriesPerMeter); Assert.Equal(PermeabilityUnit.HenryPerMeter, quantity00.Unit); } @@ -267,27 +285,24 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 H/m", PermeabilityUnit.HenryPerMeter, 4.2)] + public void Parse(string culture, string quantityString, PermeabilityUnit expectedUnit, decimal expectedValue) { - try - { - var parsed = Permeability.Parse("1 H/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.HenriesPerMeter, HenriesPerMeterTolerance); - Assert.Equal(PermeabilityUnit.HenryPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Permeability.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 H/m", PermeabilityUnit.HenryPerMeter, 4.2)] + public void TryParse(string culture, string quantityString, PermeabilityUnit expectedUnit, decimal expectedValue) { - { - Assert.True(Permeability.TryParse("1 H/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HenriesPerMeter, HenriesPerMeterTolerance); - Assert.Equal(PermeabilityUnit.HenryPerMeter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Permeability.TryParse(quantityString, out Permeability parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -364,6 +379,27 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Permea Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", PermeabilityUnit.HenryPerMeter, "H/m")] + public void GetAbbreviationForCulture(string culture, PermeabilityUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Permeability.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Permeability.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Permeability.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(PermeabilityUnit unit) @@ -394,6 +430,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); }); } @@ -417,32 +454,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] @@ -488,7 +527,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); @@ -526,34 +564,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = Permeability.FromHenriesPerMeter(1); - Assert.True(v.Equals(Permeability.FromHenriesPerMeter(1), HenriesPerMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Permeability.Zero, HenriesPerMeterTolerance, ComparisonType.Relative)); - Assert.True(Permeability.FromHenriesPerMeter(100).Equals(Permeability.FromHenriesPerMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(Permeability.FromHenriesPerMeter(100).Equals(Permeability.FromHenriesPerMeter(120), 0.1, ComparisonType.Relative)); + Permeability henrypermeter = Permeability.FromHenriesPerMeter(1); + Assert.False(henrypermeter.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = Permeability.FromHenriesPerMeter(1); - Assert.Throws(() => v.Equals(Permeability.FromHenriesPerMeter(1), -1, ComparisonType.Relative)); + Permeability henrypermeter = Permeability.FromHenriesPerMeter(1); + Assert.False(henrypermeter.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - Permeability henrypermeter = Permeability.FromHenriesPerMeter(1); - Assert.False(henrypermeter.Equals(new object())); + var quantity = Permeability.FromHenriesPerMeter(firstValue); + var otherQuantity = Permeability.FromHenriesPerMeter(secondValue); + Permeability maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - Permeability henrypermeter = Permeability.FromHenriesPerMeter(1); - Assert.False(henrypermeter.Equals(null)); + var quantity = Permeability.FromHenriesPerMeter(1); + var negativeTolerance = Permeability.FromHenriesPerMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -572,6 +619,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() { @@ -630,158 +689,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Permeability))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(PermeabilityUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal(Permeability.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal(Permeability.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal(new {Permeability.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 9a275f2ee1..dc259b6854 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PermittivityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PermittivityTestsBase.g.cs @@ -96,7 +96,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Permittivity(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -109,15 +109,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Permittivity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + PermittivityUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Permittivity(1, PermittivityUnit.FaradPerMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Permittivity.Zero, quantityInfo.Zero); Assert.Equal("Permittivity", quantityInfo.Name); + Assert.Equal(Permittivity.Zero, quantityInfo.Zero); + Assert.Equal(Permittivity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Permittivity.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -131,7 +149,7 @@ public void FaradPerMeterToPermittivityUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Permittivity.From(1, PermittivityUnit.FaradPerMeter); - AssertEx.EqualTolerance(1, quantity00.FaradsPerMeter, FaradsPerMeterTolerance); + Assert.Equal(1, quantity00.FaradsPerMeter); Assert.Equal(PermittivityUnit.FaradPerMeter, quantity00.Unit); } @@ -267,27 +285,24 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 F/m", PermittivityUnit.FaradPerMeter, 4.2)] + public void Parse(string culture, string quantityString, PermittivityUnit expectedUnit, decimal expectedValue) { - try - { - var parsed = Permittivity.Parse("1 F/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.FaradsPerMeter, FaradsPerMeterTolerance); - Assert.Equal(PermittivityUnit.FaradPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Permittivity.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 F/m", PermittivityUnit.FaradPerMeter, 4.2)] + public void TryParse(string culture, string quantityString, PermittivityUnit expectedUnit, decimal expectedValue) { - { - Assert.True(Permittivity.TryParse("1 F/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.FaradsPerMeter, FaradsPerMeterTolerance); - Assert.Equal(PermittivityUnit.FaradPerMeter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Permittivity.TryParse(quantityString, out Permittivity parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -364,6 +379,27 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Permit Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", PermittivityUnit.FaradPerMeter, "F/m")] + public void GetAbbreviationForCulture(string culture, PermittivityUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Permittivity.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Permittivity.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Permittivity.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(PermittivityUnit unit) @@ -394,6 +430,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); }); } @@ -417,32 +454,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] @@ -488,7 +527,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); @@ -526,34 +564,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = Permittivity.FromFaradsPerMeter(1); - Assert.True(v.Equals(Permittivity.FromFaradsPerMeter(1), FaradsPerMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Permittivity.Zero, FaradsPerMeterTolerance, ComparisonType.Relative)); - Assert.True(Permittivity.FromFaradsPerMeter(100).Equals(Permittivity.FromFaradsPerMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(Permittivity.FromFaradsPerMeter(100).Equals(Permittivity.FromFaradsPerMeter(120), 0.1, ComparisonType.Relative)); + Permittivity faradpermeter = Permittivity.FromFaradsPerMeter(1); + Assert.False(faradpermeter.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = Permittivity.FromFaradsPerMeter(1); - Assert.Throws(() => v.Equals(Permittivity.FromFaradsPerMeter(1), -1, ComparisonType.Relative)); + Permittivity faradpermeter = Permittivity.FromFaradsPerMeter(1); + Assert.False(faradpermeter.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - Permittivity faradpermeter = Permittivity.FromFaradsPerMeter(1); - Assert.False(faradpermeter.Equals(new object())); + var quantity = Permittivity.FromFaradsPerMeter(firstValue); + var otherQuantity = Permittivity.FromFaradsPerMeter(secondValue); + Permittivity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - Permittivity faradpermeter = Permittivity.FromFaradsPerMeter(1); - Assert.False(faradpermeter.Equals(null)); + var quantity = Permittivity.FromFaradsPerMeter(1); + var negativeTolerance = Permittivity.FromFaradsPerMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -572,6 +619,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() { @@ -630,158 +689,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Permittivity))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(PermittivityUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal(Permittivity.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal(Permittivity.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal(new {Permittivity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 54c44e64d2..381837d590 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PorousMediumPermeabilityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PorousMediumPermeabilityTestsBase.g.cs @@ -112,7 +112,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new PorousMediumPermeability(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -125,15 +125,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void PorousMediumPermeability_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + PorousMediumPermeabilityUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new PorousMediumPermeability(1, PorousMediumPermeabilityUnit.SquareMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(PorousMediumPermeability.Zero, quantityInfo.Zero); Assert.Equal("PorousMediumPermeability", quantityInfo.Name); + Assert.Equal(PorousMediumPermeability.Zero, quantityInfo.Zero); + Assert.Equal(PorousMediumPermeability.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(PorousMediumPermeability.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void PorousMediumPermeabilityInfo_CreateWithCustomUnitInfos() + { + PorousMediumPermeabilityUnit[] expectedUnits = [PorousMediumPermeabilityUnit.SquareMeter]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -151,23 +169,23 @@ public void SquareMeterToPorousMediumPermeabilityUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = PorousMediumPermeability.From(1, PorousMediumPermeabilityUnit.Darcy); - AssertEx.EqualTolerance(1, quantity00.Darcys, DarcysTolerance); + Assert.Equal(1, quantity00.Darcys); Assert.Equal(PorousMediumPermeabilityUnit.Darcy, quantity00.Unit); var quantity01 = PorousMediumPermeability.From(1, PorousMediumPermeabilityUnit.Microdarcy); - AssertEx.EqualTolerance(1, quantity01.Microdarcys, MicrodarcysTolerance); + Assert.Equal(1, quantity01.Microdarcys); Assert.Equal(PorousMediumPermeabilityUnit.Microdarcy, quantity01.Unit); var quantity02 = PorousMediumPermeability.From(1, PorousMediumPermeabilityUnit.Millidarcy); - AssertEx.EqualTolerance(1, quantity02.Millidarcys, MillidarcysTolerance); + Assert.Equal(1, quantity02.Millidarcys); Assert.Equal(PorousMediumPermeabilityUnit.Millidarcy, quantity02.Unit); var quantity03 = PorousMediumPermeability.From(1, PorousMediumPermeabilityUnit.SquareCentimeter); - AssertEx.EqualTolerance(1, quantity03.SquareCentimeters, SquareCentimetersTolerance); + Assert.Equal(1, quantity03.SquareCentimeters); Assert.Equal(PorousMediumPermeabilityUnit.SquareCentimeter, quantity03.Unit); var quantity04 = PorousMediumPermeability.From(1, PorousMediumPermeabilityUnit.SquareMeter); - AssertEx.EqualTolerance(1, quantity04.SquareMeters, SquareMetersTolerance); + Assert.Equal(1, quantity04.SquareMeters); Assert.Equal(PorousMediumPermeabilityUnit.SquareMeter, quantity04.Unit); } @@ -307,79 +325,32 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 D", PorousMediumPermeabilityUnit.Darcy, 4.2)] + [InlineData("en-US", "4.2 µD", PorousMediumPermeabilityUnit.Microdarcy, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = PorousMediumPermeability.Parse("1 D", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Darcys, DarcysTolerance); - Assert.Equal(PorousMediumPermeabilityUnit.Darcy, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PorousMediumPermeability.Parse("1 µD", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microdarcys, MicrodarcysTolerance); - Assert.Equal(PorousMediumPermeabilityUnit.Microdarcy, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PorousMediumPermeability.Parse("1 mD", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millidarcys, MillidarcysTolerance); - Assert.Equal(PorousMediumPermeabilityUnit.Millidarcy, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PorousMediumPermeability.Parse("1 cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SquareCentimeters, SquareCentimetersTolerance); - Assert.Equal(PorousMediumPermeabilityUnit.SquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PorousMediumPermeability.Parse("1 m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SquareMeters, SquareMetersTolerance); - Assert.Equal(PorousMediumPermeabilityUnit.SquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = PorousMediumPermeability.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 D", PorousMediumPermeabilityUnit.Darcy, 4.2)] + [InlineData("en-US", "4.2 µD", PorousMediumPermeabilityUnit.Microdarcy, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(PorousMediumPermeability.TryParse("1 D", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Darcys, DarcysTolerance); - Assert.Equal(PorousMediumPermeabilityUnit.Darcy, parsed.Unit); - } - - { - Assert.True(PorousMediumPermeability.TryParse("1 µD", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microdarcys, MicrodarcysTolerance); - Assert.Equal(PorousMediumPermeabilityUnit.Microdarcy, parsed.Unit); - } - - { - Assert.True(PorousMediumPermeability.TryParse("1 mD", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Millidarcys, MillidarcysTolerance); - Assert.Equal(PorousMediumPermeabilityUnit.Millidarcy, parsed.Unit); - } - - { - Assert.True(PorousMediumPermeability.TryParse("1 cm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareCentimeters, SquareCentimetersTolerance); - Assert.Equal(PorousMediumPermeabilityUnit.SquareCentimeter, parsed.Unit); - } - - { - Assert.True(PorousMediumPermeability.TryParse("1 m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareMeters, SquareMetersTolerance); - Assert.Equal(PorousMediumPermeabilityUnit.SquareMeter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(PorousMediumPermeability.TryParse(quantityString, out PorousMediumPermeability parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -488,6 +459,31 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Porous Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", PorousMediumPermeabilityUnit.Darcy, "D")] + [InlineData("en-US", PorousMediumPermeabilityUnit.Microdarcy, "µD")] + [InlineData("en-US", PorousMediumPermeabilityUnit.Millidarcy, "mD")] + [InlineData("en-US", PorousMediumPermeabilityUnit.SquareCentimeter, "cm²")] + [InlineData("en-US", PorousMediumPermeabilityUnit.SquareMeter, "m²")] + public void GetAbbreviationForCulture(string culture, PorousMediumPermeabilityUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = PorousMediumPermeability.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(PorousMediumPermeability.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = PorousMediumPermeability.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(PorousMediumPermeabilityUnit unit) @@ -518,6 +514,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); }); } @@ -541,36 +538,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] @@ -616,8 +615,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); @@ -655,34 +652,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = PorousMediumPermeability.FromSquareMeters(1); - Assert.True(v.Equals(PorousMediumPermeability.FromSquareMeters(1), SquareMetersTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(PorousMediumPermeability.Zero, SquareMetersTolerance, ComparisonType.Relative)); - Assert.True(PorousMediumPermeability.FromSquareMeters(100).Equals(PorousMediumPermeability.FromSquareMeters(120), 0.3, ComparisonType.Relative)); - Assert.False(PorousMediumPermeability.FromSquareMeters(100).Equals(PorousMediumPermeability.FromSquareMeters(120), 0.1, ComparisonType.Relative)); + PorousMediumPermeability squaremeter = PorousMediumPermeability.FromSquareMeters(1); + Assert.False(squaremeter.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = PorousMediumPermeability.FromSquareMeters(1); - Assert.Throws(() => v.Equals(PorousMediumPermeability.FromSquareMeters(1), -1, ComparisonType.Relative)); + PorousMediumPermeability squaremeter = PorousMediumPermeability.FromSquareMeters(1); + Assert.False(squaremeter.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - PorousMediumPermeability squaremeter = PorousMediumPermeability.FromSquareMeters(1); - Assert.False(squaremeter.Equals(new object())); + var quantity = PorousMediumPermeability.FromSquareMeters(firstValue); + var otherQuantity = PorousMediumPermeability.FromSquareMeters(secondValue); + PorousMediumPermeability maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - PorousMediumPermeability squaremeter = PorousMediumPermeability.FromSquareMeters(1); - Assert.False(squaremeter.Equals(null)); + var quantity = PorousMediumPermeability.FromSquareMeters(1); + var negativeTolerance = PorousMediumPermeability.FromSquareMeters(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -701,6 +707,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() { @@ -767,158 +785,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(PorousMediumPermeability))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(PorousMediumPermeabilityUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal(PorousMediumPermeability.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal(PorousMediumPermeability.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal(new {PorousMediumPermeability.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 65c5bf70a8..1547514d14 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PowerDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PowerDensityTestsBase.g.cs @@ -268,7 +268,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new PowerDensity(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -281,15 +281,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void PowerDensity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + PowerDensityUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new PowerDensity(1, PowerDensityUnit.WattPerCubicMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(PowerDensity.Zero, quantityInfo.Zero); Assert.Equal("PowerDensity", quantityInfo.Name); + Assert.Equal(PowerDensity.Zero, quantityInfo.Zero); + Assert.Equal(PowerDensity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(PowerDensity.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void PowerDensityInfo_CreateWithCustomUnitInfos() + { + PowerDensityUnit[] expectedUnits = [PowerDensityUnit.WattPerCubicMeter]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -346,179 +364,179 @@ public void WattPerCubicMeterToPowerDensityUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = PowerDensity.From(1, PowerDensityUnit.DecawattPerCubicFoot); - AssertEx.EqualTolerance(1, quantity00.DecawattsPerCubicFoot, DecawattsPerCubicFootTolerance); + Assert.Equal(1, quantity00.DecawattsPerCubicFoot); Assert.Equal(PowerDensityUnit.DecawattPerCubicFoot, quantity00.Unit); var quantity01 = PowerDensity.From(1, PowerDensityUnit.DecawattPerCubicInch); - AssertEx.EqualTolerance(1, quantity01.DecawattsPerCubicInch, DecawattsPerCubicInchTolerance); + Assert.Equal(1, quantity01.DecawattsPerCubicInch); Assert.Equal(PowerDensityUnit.DecawattPerCubicInch, quantity01.Unit); var quantity02 = PowerDensity.From(1, PowerDensityUnit.DecawattPerCubicMeter); - AssertEx.EqualTolerance(1, quantity02.DecawattsPerCubicMeter, DecawattsPerCubicMeterTolerance); + Assert.Equal(1, quantity02.DecawattsPerCubicMeter); Assert.Equal(PowerDensityUnit.DecawattPerCubicMeter, quantity02.Unit); var quantity03 = PowerDensity.From(1, PowerDensityUnit.DecawattPerLiter); - AssertEx.EqualTolerance(1, quantity03.DecawattsPerLiter, DecawattsPerLiterTolerance); + Assert.Equal(1, quantity03.DecawattsPerLiter); Assert.Equal(PowerDensityUnit.DecawattPerLiter, quantity03.Unit); var quantity04 = PowerDensity.From(1, PowerDensityUnit.DeciwattPerCubicFoot); - AssertEx.EqualTolerance(1, quantity04.DeciwattsPerCubicFoot, DeciwattsPerCubicFootTolerance); + Assert.Equal(1, quantity04.DeciwattsPerCubicFoot); Assert.Equal(PowerDensityUnit.DeciwattPerCubicFoot, quantity04.Unit); var quantity05 = PowerDensity.From(1, PowerDensityUnit.DeciwattPerCubicInch); - AssertEx.EqualTolerance(1, quantity05.DeciwattsPerCubicInch, DeciwattsPerCubicInchTolerance); + Assert.Equal(1, quantity05.DeciwattsPerCubicInch); Assert.Equal(PowerDensityUnit.DeciwattPerCubicInch, quantity05.Unit); var quantity06 = PowerDensity.From(1, PowerDensityUnit.DeciwattPerCubicMeter); - AssertEx.EqualTolerance(1, quantity06.DeciwattsPerCubicMeter, DeciwattsPerCubicMeterTolerance); + Assert.Equal(1, quantity06.DeciwattsPerCubicMeter); Assert.Equal(PowerDensityUnit.DeciwattPerCubicMeter, quantity06.Unit); var quantity07 = PowerDensity.From(1, PowerDensityUnit.DeciwattPerLiter); - AssertEx.EqualTolerance(1, quantity07.DeciwattsPerLiter, DeciwattsPerLiterTolerance); + Assert.Equal(1, quantity07.DeciwattsPerLiter); Assert.Equal(PowerDensityUnit.DeciwattPerLiter, quantity07.Unit); var quantity08 = PowerDensity.From(1, PowerDensityUnit.GigawattPerCubicFoot); - AssertEx.EqualTolerance(1, quantity08.GigawattsPerCubicFoot, GigawattsPerCubicFootTolerance); + Assert.Equal(1, quantity08.GigawattsPerCubicFoot); Assert.Equal(PowerDensityUnit.GigawattPerCubicFoot, quantity08.Unit); var quantity09 = PowerDensity.From(1, PowerDensityUnit.GigawattPerCubicInch); - AssertEx.EqualTolerance(1, quantity09.GigawattsPerCubicInch, GigawattsPerCubicInchTolerance); + Assert.Equal(1, quantity09.GigawattsPerCubicInch); Assert.Equal(PowerDensityUnit.GigawattPerCubicInch, quantity09.Unit); var quantity10 = PowerDensity.From(1, PowerDensityUnit.GigawattPerCubicMeter); - AssertEx.EqualTolerance(1, quantity10.GigawattsPerCubicMeter, GigawattsPerCubicMeterTolerance); + Assert.Equal(1, quantity10.GigawattsPerCubicMeter); Assert.Equal(PowerDensityUnit.GigawattPerCubicMeter, quantity10.Unit); var quantity11 = PowerDensity.From(1, PowerDensityUnit.GigawattPerLiter); - AssertEx.EqualTolerance(1, quantity11.GigawattsPerLiter, GigawattsPerLiterTolerance); + Assert.Equal(1, quantity11.GigawattsPerLiter); Assert.Equal(PowerDensityUnit.GigawattPerLiter, quantity11.Unit); var quantity12 = PowerDensity.From(1, PowerDensityUnit.KilowattPerCubicFoot); - AssertEx.EqualTolerance(1, quantity12.KilowattsPerCubicFoot, KilowattsPerCubicFootTolerance); + Assert.Equal(1, quantity12.KilowattsPerCubicFoot); Assert.Equal(PowerDensityUnit.KilowattPerCubicFoot, quantity12.Unit); var quantity13 = PowerDensity.From(1, PowerDensityUnit.KilowattPerCubicInch); - AssertEx.EqualTolerance(1, quantity13.KilowattsPerCubicInch, KilowattsPerCubicInchTolerance); + Assert.Equal(1, quantity13.KilowattsPerCubicInch); Assert.Equal(PowerDensityUnit.KilowattPerCubicInch, quantity13.Unit); var quantity14 = PowerDensity.From(1, PowerDensityUnit.KilowattPerCubicMeter); - AssertEx.EqualTolerance(1, quantity14.KilowattsPerCubicMeter, KilowattsPerCubicMeterTolerance); + Assert.Equal(1, quantity14.KilowattsPerCubicMeter); Assert.Equal(PowerDensityUnit.KilowattPerCubicMeter, quantity14.Unit); var quantity15 = PowerDensity.From(1, PowerDensityUnit.KilowattPerLiter); - AssertEx.EqualTolerance(1, quantity15.KilowattsPerLiter, KilowattsPerLiterTolerance); + Assert.Equal(1, quantity15.KilowattsPerLiter); Assert.Equal(PowerDensityUnit.KilowattPerLiter, quantity15.Unit); var quantity16 = PowerDensity.From(1, PowerDensityUnit.MegawattPerCubicFoot); - AssertEx.EqualTolerance(1, quantity16.MegawattsPerCubicFoot, MegawattsPerCubicFootTolerance); + Assert.Equal(1, quantity16.MegawattsPerCubicFoot); Assert.Equal(PowerDensityUnit.MegawattPerCubicFoot, quantity16.Unit); var quantity17 = PowerDensity.From(1, PowerDensityUnit.MegawattPerCubicInch); - AssertEx.EqualTolerance(1, quantity17.MegawattsPerCubicInch, MegawattsPerCubicInchTolerance); + Assert.Equal(1, quantity17.MegawattsPerCubicInch); Assert.Equal(PowerDensityUnit.MegawattPerCubicInch, quantity17.Unit); var quantity18 = PowerDensity.From(1, PowerDensityUnit.MegawattPerCubicMeter); - AssertEx.EqualTolerance(1, quantity18.MegawattsPerCubicMeter, MegawattsPerCubicMeterTolerance); + Assert.Equal(1, quantity18.MegawattsPerCubicMeter); Assert.Equal(PowerDensityUnit.MegawattPerCubicMeter, quantity18.Unit); var quantity19 = PowerDensity.From(1, PowerDensityUnit.MegawattPerLiter); - AssertEx.EqualTolerance(1, quantity19.MegawattsPerLiter, MegawattsPerLiterTolerance); + Assert.Equal(1, quantity19.MegawattsPerLiter); Assert.Equal(PowerDensityUnit.MegawattPerLiter, quantity19.Unit); var quantity20 = PowerDensity.From(1, PowerDensityUnit.MicrowattPerCubicFoot); - AssertEx.EqualTolerance(1, quantity20.MicrowattsPerCubicFoot, MicrowattsPerCubicFootTolerance); + Assert.Equal(1, quantity20.MicrowattsPerCubicFoot); Assert.Equal(PowerDensityUnit.MicrowattPerCubicFoot, quantity20.Unit); var quantity21 = PowerDensity.From(1, PowerDensityUnit.MicrowattPerCubicInch); - AssertEx.EqualTolerance(1, quantity21.MicrowattsPerCubicInch, MicrowattsPerCubicInchTolerance); + Assert.Equal(1, quantity21.MicrowattsPerCubicInch); Assert.Equal(PowerDensityUnit.MicrowattPerCubicInch, quantity21.Unit); var quantity22 = PowerDensity.From(1, PowerDensityUnit.MicrowattPerCubicMeter); - AssertEx.EqualTolerance(1, quantity22.MicrowattsPerCubicMeter, MicrowattsPerCubicMeterTolerance); + Assert.Equal(1, quantity22.MicrowattsPerCubicMeter); Assert.Equal(PowerDensityUnit.MicrowattPerCubicMeter, quantity22.Unit); var quantity23 = PowerDensity.From(1, PowerDensityUnit.MicrowattPerLiter); - AssertEx.EqualTolerance(1, quantity23.MicrowattsPerLiter, MicrowattsPerLiterTolerance); + Assert.Equal(1, quantity23.MicrowattsPerLiter); Assert.Equal(PowerDensityUnit.MicrowattPerLiter, quantity23.Unit); var quantity24 = PowerDensity.From(1, PowerDensityUnit.MilliwattPerCubicFoot); - AssertEx.EqualTolerance(1, quantity24.MilliwattsPerCubicFoot, MilliwattsPerCubicFootTolerance); + Assert.Equal(1, quantity24.MilliwattsPerCubicFoot); Assert.Equal(PowerDensityUnit.MilliwattPerCubicFoot, quantity24.Unit); var quantity25 = PowerDensity.From(1, PowerDensityUnit.MilliwattPerCubicInch); - AssertEx.EqualTolerance(1, quantity25.MilliwattsPerCubicInch, MilliwattsPerCubicInchTolerance); + Assert.Equal(1, quantity25.MilliwattsPerCubicInch); Assert.Equal(PowerDensityUnit.MilliwattPerCubicInch, quantity25.Unit); var quantity26 = PowerDensity.From(1, PowerDensityUnit.MilliwattPerCubicMeter); - AssertEx.EqualTolerance(1, quantity26.MilliwattsPerCubicMeter, MilliwattsPerCubicMeterTolerance); + Assert.Equal(1, quantity26.MilliwattsPerCubicMeter); Assert.Equal(PowerDensityUnit.MilliwattPerCubicMeter, quantity26.Unit); var quantity27 = PowerDensity.From(1, PowerDensityUnit.MilliwattPerLiter); - AssertEx.EqualTolerance(1, quantity27.MilliwattsPerLiter, MilliwattsPerLiterTolerance); + Assert.Equal(1, quantity27.MilliwattsPerLiter); Assert.Equal(PowerDensityUnit.MilliwattPerLiter, quantity27.Unit); var quantity28 = PowerDensity.From(1, PowerDensityUnit.NanowattPerCubicFoot); - AssertEx.EqualTolerance(1, quantity28.NanowattsPerCubicFoot, NanowattsPerCubicFootTolerance); + Assert.Equal(1, quantity28.NanowattsPerCubicFoot); Assert.Equal(PowerDensityUnit.NanowattPerCubicFoot, quantity28.Unit); var quantity29 = PowerDensity.From(1, PowerDensityUnit.NanowattPerCubicInch); - AssertEx.EqualTolerance(1, quantity29.NanowattsPerCubicInch, NanowattsPerCubicInchTolerance); + Assert.Equal(1, quantity29.NanowattsPerCubicInch); Assert.Equal(PowerDensityUnit.NanowattPerCubicInch, quantity29.Unit); var quantity30 = PowerDensity.From(1, PowerDensityUnit.NanowattPerCubicMeter); - AssertEx.EqualTolerance(1, quantity30.NanowattsPerCubicMeter, NanowattsPerCubicMeterTolerance); + Assert.Equal(1, quantity30.NanowattsPerCubicMeter); Assert.Equal(PowerDensityUnit.NanowattPerCubicMeter, quantity30.Unit); var quantity31 = PowerDensity.From(1, PowerDensityUnit.NanowattPerLiter); - AssertEx.EqualTolerance(1, quantity31.NanowattsPerLiter, NanowattsPerLiterTolerance); + Assert.Equal(1, quantity31.NanowattsPerLiter); Assert.Equal(PowerDensityUnit.NanowattPerLiter, quantity31.Unit); var quantity32 = PowerDensity.From(1, PowerDensityUnit.PicowattPerCubicFoot); - AssertEx.EqualTolerance(1, quantity32.PicowattsPerCubicFoot, PicowattsPerCubicFootTolerance); + Assert.Equal(1, quantity32.PicowattsPerCubicFoot); Assert.Equal(PowerDensityUnit.PicowattPerCubicFoot, quantity32.Unit); var quantity33 = PowerDensity.From(1, PowerDensityUnit.PicowattPerCubicInch); - AssertEx.EqualTolerance(1, quantity33.PicowattsPerCubicInch, PicowattsPerCubicInchTolerance); + Assert.Equal(1, quantity33.PicowattsPerCubicInch); Assert.Equal(PowerDensityUnit.PicowattPerCubicInch, quantity33.Unit); var quantity34 = PowerDensity.From(1, PowerDensityUnit.PicowattPerCubicMeter); - AssertEx.EqualTolerance(1, quantity34.PicowattsPerCubicMeter, PicowattsPerCubicMeterTolerance); + Assert.Equal(1, quantity34.PicowattsPerCubicMeter); Assert.Equal(PowerDensityUnit.PicowattPerCubicMeter, quantity34.Unit); var quantity35 = PowerDensity.From(1, PowerDensityUnit.PicowattPerLiter); - AssertEx.EqualTolerance(1, quantity35.PicowattsPerLiter, PicowattsPerLiterTolerance); + Assert.Equal(1, quantity35.PicowattsPerLiter); Assert.Equal(PowerDensityUnit.PicowattPerLiter, quantity35.Unit); var quantity36 = PowerDensity.From(1, PowerDensityUnit.TerawattPerCubicFoot); - AssertEx.EqualTolerance(1, quantity36.TerawattsPerCubicFoot, TerawattsPerCubicFootTolerance); + Assert.Equal(1, quantity36.TerawattsPerCubicFoot); Assert.Equal(PowerDensityUnit.TerawattPerCubicFoot, quantity36.Unit); var quantity37 = PowerDensity.From(1, PowerDensityUnit.TerawattPerCubicInch); - AssertEx.EqualTolerance(1, quantity37.TerawattsPerCubicInch, TerawattsPerCubicInchTolerance); + Assert.Equal(1, quantity37.TerawattsPerCubicInch); Assert.Equal(PowerDensityUnit.TerawattPerCubicInch, quantity37.Unit); var quantity38 = PowerDensity.From(1, PowerDensityUnit.TerawattPerCubicMeter); - AssertEx.EqualTolerance(1, quantity38.TerawattsPerCubicMeter, TerawattsPerCubicMeterTolerance); + Assert.Equal(1, quantity38.TerawattsPerCubicMeter); Assert.Equal(PowerDensityUnit.TerawattPerCubicMeter, quantity38.Unit); var quantity39 = PowerDensity.From(1, PowerDensityUnit.TerawattPerLiter); - AssertEx.EqualTolerance(1, quantity39.TerawattsPerLiter, TerawattsPerLiterTolerance); + Assert.Equal(1, quantity39.TerawattsPerLiter); Assert.Equal(PowerDensityUnit.TerawattPerLiter, quantity39.Unit); var quantity40 = PowerDensity.From(1, PowerDensityUnit.WattPerCubicFoot); - AssertEx.EqualTolerance(1, quantity40.WattsPerCubicFoot, WattsPerCubicFootTolerance); + Assert.Equal(1, quantity40.WattsPerCubicFoot); Assert.Equal(PowerDensityUnit.WattPerCubicFoot, quantity40.Unit); var quantity41 = PowerDensity.From(1, PowerDensityUnit.WattPerCubicInch); - AssertEx.EqualTolerance(1, quantity41.WattsPerCubicInch, WattsPerCubicInchTolerance); + Assert.Equal(1, quantity41.WattsPerCubicInch); Assert.Equal(PowerDensityUnit.WattPerCubicInch, quantity41.Unit); var quantity42 = PowerDensity.From(1, PowerDensityUnit.WattPerCubicMeter); - AssertEx.EqualTolerance(1, quantity42.WattsPerCubicMeter, WattsPerCubicMeterTolerance); + Assert.Equal(1, quantity42.WattsPerCubicMeter); Assert.Equal(PowerDensityUnit.WattPerCubicMeter, quantity42.Unit); var quantity43 = PowerDensity.From(1, PowerDensityUnit.WattPerLiter); - AssertEx.EqualTolerance(1, quantity43.WattsPerLiter, WattsPerLiterTolerance); + Assert.Equal(1, quantity43.WattsPerLiter); Assert.Equal(PowerDensityUnit.WattPerLiter, quantity43.Unit); } @@ -697,538 +715,110 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 daW/ft³", PowerDensityUnit.DecawattPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 daW/in³", PowerDensityUnit.DecawattPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 daW/m³", PowerDensityUnit.DecawattPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 daW/l", PowerDensityUnit.DecawattPerLiter, 4.2)] + [InlineData("en-US", "4.2 dW/ft³", PowerDensityUnit.DeciwattPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 dW/in³", PowerDensityUnit.DeciwattPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 dW/m³", PowerDensityUnit.DeciwattPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 dW/l", PowerDensityUnit.DeciwattPerLiter, 4.2)] + [InlineData("en-US", "4.2 GW/ft³", PowerDensityUnit.GigawattPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 GW/in³", PowerDensityUnit.GigawattPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 GW/m³", PowerDensityUnit.GigawattPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 GW/l", PowerDensityUnit.GigawattPerLiter, 4.2)] + [InlineData("en-US", "4.2 kW/ft³", PowerDensityUnit.KilowattPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 kW/in³", PowerDensityUnit.KilowattPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 kW/m³", PowerDensityUnit.KilowattPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 kW/l", PowerDensityUnit.KilowattPerLiter, 4.2)] + [InlineData("en-US", "4.2 MW/ft³", PowerDensityUnit.MegawattPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 MW/in³", PowerDensityUnit.MegawattPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 MW/m³", PowerDensityUnit.MegawattPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 MW/l", PowerDensityUnit.MegawattPerLiter, 4.2)] + [InlineData("en-US", "4.2 µW/ft³", PowerDensityUnit.MicrowattPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 µW/in³", PowerDensityUnit.MicrowattPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 µW/m³", PowerDensityUnit.MicrowattPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 µW/l", PowerDensityUnit.MicrowattPerLiter, 4.2)] + [InlineData("en-US", "4.2 mW/ft³", PowerDensityUnit.MilliwattPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 mW/in³", PowerDensityUnit.MilliwattPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 mW/m³", PowerDensityUnit.MilliwattPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 mW/l", PowerDensityUnit.MilliwattPerLiter, 4.2)] + [InlineData("en-US", "4.2 nW/ft³", PowerDensityUnit.NanowattPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 nW/in³", PowerDensityUnit.NanowattPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 nW/m³", PowerDensityUnit.NanowattPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 nW/l", PowerDensityUnit.NanowattPerLiter, 4.2)] + [InlineData("en-US", "4.2 pW/ft³", PowerDensityUnit.PicowattPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 pW/in³", PowerDensityUnit.PicowattPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 pW/m³", PowerDensityUnit.PicowattPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 pW/l", PowerDensityUnit.PicowattPerLiter, 4.2)] + [InlineData("en-US", "4.2 TW/ft³", PowerDensityUnit.TerawattPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 TW/in³", PowerDensityUnit.TerawattPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 TW/m³", PowerDensityUnit.TerawattPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 TW/l", PowerDensityUnit.TerawattPerLiter, 4.2)] + [InlineData("en-US", "4.2 W/ft³", PowerDensityUnit.WattPerCubicFoot, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = PowerDensity.Parse("1 daW/ft³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecawattsPerCubicFoot, DecawattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.DecawattPerCubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 daW/in³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecawattsPerCubicInch, DecawattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.DecawattPerCubicInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 daW/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecawattsPerCubicMeter, DecawattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.DecawattPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 daW/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecawattsPerLiter, DecawattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.DecawattPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 dW/ft³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DeciwattsPerCubicFoot, DeciwattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.DeciwattPerCubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 dW/in³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DeciwattsPerCubicInch, DeciwattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.DeciwattPerCubicInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 dW/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DeciwattsPerCubicMeter, DeciwattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.DeciwattPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 dW/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DeciwattsPerLiter, DeciwattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.DeciwattPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 GW/ft³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GigawattsPerCubicFoot, GigawattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.GigawattPerCubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 GW/in³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GigawattsPerCubicInch, GigawattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.GigawattPerCubicInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 GW/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GigawattsPerCubicMeter, GigawattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.GigawattPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 GW/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GigawattsPerLiter, GigawattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.GigawattPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 kW/ft³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilowattsPerCubicFoot, KilowattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.KilowattPerCubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 kW/in³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilowattsPerCubicInch, KilowattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.KilowattPerCubicInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 kW/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilowattsPerCubicMeter, KilowattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.KilowattPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 kW/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilowattsPerLiter, KilowattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.KilowattPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 MW/ft³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegawattsPerCubicFoot, MegawattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.MegawattPerCubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 MW/in³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegawattsPerCubicInch, MegawattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.MegawattPerCubicInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 MW/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegawattsPerCubicMeter, MegawattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.MegawattPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 MW/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegawattsPerLiter, MegawattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.MegawattPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 µW/ft³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrowattsPerCubicFoot, MicrowattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.MicrowattPerCubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 µW/in³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrowattsPerCubicInch, MicrowattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.MicrowattPerCubicInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 µW/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrowattsPerCubicMeter, MicrowattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.MicrowattPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 µW/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrowattsPerLiter, MicrowattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.MicrowattPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 mW/ft³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilliwattsPerCubicFoot, MilliwattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.MilliwattPerCubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 mW/in³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilliwattsPerCubicInch, MilliwattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.MilliwattPerCubicInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 mW/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilliwattsPerCubicMeter, MilliwattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.MilliwattPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 mW/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilliwattsPerLiter, MilliwattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.MilliwattPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 nW/ft³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanowattsPerCubicFoot, NanowattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.NanowattPerCubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 nW/in³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanowattsPerCubicInch, NanowattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.NanowattPerCubicInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 nW/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanowattsPerCubicMeter, NanowattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.NanowattPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 nW/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanowattsPerLiter, NanowattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.NanowattPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 pW/ft³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PicowattsPerCubicFoot, PicowattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.PicowattPerCubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 pW/in³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PicowattsPerCubicInch, PicowattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.PicowattPerCubicInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 pW/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PicowattsPerCubicMeter, PicowattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.PicowattPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 pW/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PicowattsPerLiter, PicowattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.PicowattPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 TW/ft³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TerawattsPerCubicFoot, TerawattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.TerawattPerCubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 TW/in³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TerawattsPerCubicInch, TerawattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.TerawattPerCubicInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 TW/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TerawattsPerCubicMeter, TerawattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.TerawattPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 TW/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TerawattsPerLiter, TerawattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.TerawattPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 W/ft³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WattsPerCubicFoot, WattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.WattPerCubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 W/in³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WattsPerCubicInch, WattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.WattPerCubicInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 W/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WattsPerCubicMeter, WattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.WattPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerDensity.Parse("1 W/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WattsPerLiter, WattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.WattPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = PowerDensity.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 daW/ft³", PowerDensityUnit.DecawattPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 daW/in³", PowerDensityUnit.DecawattPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 daW/m³", PowerDensityUnit.DecawattPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 daW/l", PowerDensityUnit.DecawattPerLiter, 4.2)] + [InlineData("en-US", "4.2 dW/ft³", PowerDensityUnit.DeciwattPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 dW/in³", PowerDensityUnit.DeciwattPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 dW/m³", PowerDensityUnit.DeciwattPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 dW/l", PowerDensityUnit.DeciwattPerLiter, 4.2)] + [InlineData("en-US", "4.2 GW/ft³", PowerDensityUnit.GigawattPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 GW/in³", PowerDensityUnit.GigawattPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 GW/m³", PowerDensityUnit.GigawattPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 GW/l", PowerDensityUnit.GigawattPerLiter, 4.2)] + [InlineData("en-US", "4.2 kW/ft³", PowerDensityUnit.KilowattPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 kW/in³", PowerDensityUnit.KilowattPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 kW/m³", PowerDensityUnit.KilowattPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 kW/l", PowerDensityUnit.KilowattPerLiter, 4.2)] + [InlineData("en-US", "4.2 MW/ft³", PowerDensityUnit.MegawattPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 MW/in³", PowerDensityUnit.MegawattPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 MW/m³", PowerDensityUnit.MegawattPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 MW/l", PowerDensityUnit.MegawattPerLiter, 4.2)] + [InlineData("en-US", "4.2 µW/ft³", PowerDensityUnit.MicrowattPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 µW/in³", PowerDensityUnit.MicrowattPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 µW/m³", PowerDensityUnit.MicrowattPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 µW/l", PowerDensityUnit.MicrowattPerLiter, 4.2)] + [InlineData("en-US", "4.2 mW/ft³", PowerDensityUnit.MilliwattPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 mW/in³", PowerDensityUnit.MilliwattPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 mW/m³", PowerDensityUnit.MilliwattPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 mW/l", PowerDensityUnit.MilliwattPerLiter, 4.2)] + [InlineData("en-US", "4.2 nW/ft³", PowerDensityUnit.NanowattPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 nW/in³", PowerDensityUnit.NanowattPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 nW/m³", PowerDensityUnit.NanowattPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 nW/l", PowerDensityUnit.NanowattPerLiter, 4.2)] + [InlineData("en-US", "4.2 pW/ft³", PowerDensityUnit.PicowattPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 pW/in³", PowerDensityUnit.PicowattPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 pW/m³", PowerDensityUnit.PicowattPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 pW/l", PowerDensityUnit.PicowattPerLiter, 4.2)] + [InlineData("en-US", "4.2 TW/ft³", PowerDensityUnit.TerawattPerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 TW/in³", PowerDensityUnit.TerawattPerCubicInch, 4.2)] + [InlineData("en-US", "4.2 TW/m³", PowerDensityUnit.TerawattPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 TW/l", PowerDensityUnit.TerawattPerLiter, 4.2)] + [InlineData("en-US", "4.2 W/ft³", PowerDensityUnit.WattPerCubicFoot, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(PowerDensity.TryParse("1 daW/ft³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecawattsPerCubicFoot, DecawattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.DecawattPerCubicFoot, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 daW/in³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecawattsPerCubicInch, DecawattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.DecawattPerCubicInch, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 daW/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecawattsPerCubicMeter, DecawattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.DecawattPerCubicMeter, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 daW/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecawattsPerLiter, DecawattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.DecawattPerLiter, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 dW/ft³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DeciwattsPerCubicFoot, DeciwattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.DeciwattPerCubicFoot, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 dW/in³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DeciwattsPerCubicInch, DeciwattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.DeciwattPerCubicInch, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 dW/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DeciwattsPerCubicMeter, DeciwattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.DeciwattPerCubicMeter, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 dW/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DeciwattsPerLiter, DeciwattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.DeciwattPerLiter, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 GW/ft³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigawattsPerCubicFoot, GigawattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.GigawattPerCubicFoot, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 GW/in³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigawattsPerCubicInch, GigawattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.GigawattPerCubicInch, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 GW/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigawattsPerCubicMeter, GigawattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.GigawattPerCubicMeter, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 GW/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigawattsPerLiter, GigawattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.GigawattPerLiter, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 kW/ft³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilowattsPerCubicFoot, KilowattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.KilowattPerCubicFoot, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 kW/in³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilowattsPerCubicInch, KilowattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.KilowattPerCubicInch, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 kW/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilowattsPerCubicMeter, KilowattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.KilowattPerCubicMeter, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 kW/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilowattsPerLiter, KilowattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.KilowattPerLiter, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 µW/ft³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrowattsPerCubicFoot, MicrowattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.MicrowattPerCubicFoot, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 µW/in³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrowattsPerCubicInch, MicrowattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.MicrowattPerCubicInch, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 µW/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrowattsPerCubicMeter, MicrowattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.MicrowattPerCubicMeter, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 µW/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrowattsPerLiter, MicrowattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.MicrowattPerLiter, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 nW/ft³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanowattsPerCubicFoot, NanowattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.NanowattPerCubicFoot, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 nW/in³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanowattsPerCubicInch, NanowattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.NanowattPerCubicInch, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 nW/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanowattsPerCubicMeter, NanowattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.NanowattPerCubicMeter, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 nW/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanowattsPerLiter, NanowattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.NanowattPerLiter, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 pW/ft³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PicowattsPerCubicFoot, PicowattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.PicowattPerCubicFoot, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 pW/in³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PicowattsPerCubicInch, PicowattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.PicowattPerCubicInch, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 pW/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PicowattsPerCubicMeter, PicowattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.PicowattPerCubicMeter, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 pW/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PicowattsPerLiter, PicowattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.PicowattPerLiter, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 TW/ft³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TerawattsPerCubicFoot, TerawattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.TerawattPerCubicFoot, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 TW/in³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TerawattsPerCubicInch, TerawattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.TerawattPerCubicInch, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 TW/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TerawattsPerCubicMeter, TerawattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.TerawattPerCubicMeter, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 TW/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TerawattsPerLiter, TerawattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.TerawattPerLiter, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 W/ft³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattsPerCubicFoot, WattsPerCubicFootTolerance); - Assert.Equal(PowerDensityUnit.WattPerCubicFoot, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 W/in³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattsPerCubicInch, WattsPerCubicInchTolerance); - Assert.Equal(PowerDensityUnit.WattPerCubicInch, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 W/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattsPerCubicMeter, WattsPerCubicMeterTolerance); - Assert.Equal(PowerDensityUnit.WattPerCubicMeter, parsed.Unit); - } - - { - Assert.True(PowerDensity.TryParse("1 W/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattsPerLiter, WattsPerLiterTolerance); - Assert.Equal(PowerDensityUnit.WattPerLiter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(PowerDensity.TryParse(quantityString, out PowerDensity parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -1649,6 +1239,70 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, PowerD Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", PowerDensityUnit.DecawattPerCubicFoot, "daW/ft³")] + [InlineData("en-US", PowerDensityUnit.DecawattPerCubicInch, "daW/in³")] + [InlineData("en-US", PowerDensityUnit.DecawattPerCubicMeter, "daW/m³")] + [InlineData("en-US", PowerDensityUnit.DecawattPerLiter, "daW/l")] + [InlineData("en-US", PowerDensityUnit.DeciwattPerCubicFoot, "dW/ft³")] + [InlineData("en-US", PowerDensityUnit.DeciwattPerCubicInch, "dW/in³")] + [InlineData("en-US", PowerDensityUnit.DeciwattPerCubicMeter, "dW/m³")] + [InlineData("en-US", PowerDensityUnit.DeciwattPerLiter, "dW/l")] + [InlineData("en-US", PowerDensityUnit.GigawattPerCubicFoot, "GW/ft³")] + [InlineData("en-US", PowerDensityUnit.GigawattPerCubicInch, "GW/in³")] + [InlineData("en-US", PowerDensityUnit.GigawattPerCubicMeter, "GW/m³")] + [InlineData("en-US", PowerDensityUnit.GigawattPerLiter, "GW/l")] + [InlineData("en-US", PowerDensityUnit.KilowattPerCubicFoot, "kW/ft³")] + [InlineData("en-US", PowerDensityUnit.KilowattPerCubicInch, "kW/in³")] + [InlineData("en-US", PowerDensityUnit.KilowattPerCubicMeter, "kW/m³")] + [InlineData("en-US", PowerDensityUnit.KilowattPerLiter, "kW/l")] + [InlineData("en-US", PowerDensityUnit.MegawattPerCubicFoot, "MW/ft³")] + [InlineData("en-US", PowerDensityUnit.MegawattPerCubicInch, "MW/in³")] + [InlineData("en-US", PowerDensityUnit.MegawattPerCubicMeter, "MW/m³")] + [InlineData("en-US", PowerDensityUnit.MegawattPerLiter, "MW/l")] + [InlineData("en-US", PowerDensityUnit.MicrowattPerCubicFoot, "µW/ft³")] + [InlineData("en-US", PowerDensityUnit.MicrowattPerCubicInch, "µW/in³")] + [InlineData("en-US", PowerDensityUnit.MicrowattPerCubicMeter, "µW/m³")] + [InlineData("en-US", PowerDensityUnit.MicrowattPerLiter, "µW/l")] + [InlineData("en-US", PowerDensityUnit.MilliwattPerCubicFoot, "mW/ft³")] + [InlineData("en-US", PowerDensityUnit.MilliwattPerCubicInch, "mW/in³")] + [InlineData("en-US", PowerDensityUnit.MilliwattPerCubicMeter, "mW/m³")] + [InlineData("en-US", PowerDensityUnit.MilliwattPerLiter, "mW/l")] + [InlineData("en-US", PowerDensityUnit.NanowattPerCubicFoot, "nW/ft³")] + [InlineData("en-US", PowerDensityUnit.NanowattPerCubicInch, "nW/in³")] + [InlineData("en-US", PowerDensityUnit.NanowattPerCubicMeter, "nW/m³")] + [InlineData("en-US", PowerDensityUnit.NanowattPerLiter, "nW/l")] + [InlineData("en-US", PowerDensityUnit.PicowattPerCubicFoot, "pW/ft³")] + [InlineData("en-US", PowerDensityUnit.PicowattPerCubicInch, "pW/in³")] + [InlineData("en-US", PowerDensityUnit.PicowattPerCubicMeter, "pW/m³")] + [InlineData("en-US", PowerDensityUnit.PicowattPerLiter, "pW/l")] + [InlineData("en-US", PowerDensityUnit.TerawattPerCubicFoot, "TW/ft³")] + [InlineData("en-US", PowerDensityUnit.TerawattPerCubicInch, "TW/in³")] + [InlineData("en-US", PowerDensityUnit.TerawattPerCubicMeter, "TW/m³")] + [InlineData("en-US", PowerDensityUnit.TerawattPerLiter, "TW/l")] + [InlineData("en-US", PowerDensityUnit.WattPerCubicFoot, "W/ft³")] + [InlineData("en-US", PowerDensityUnit.WattPerCubicInch, "W/in³")] + [InlineData("en-US", PowerDensityUnit.WattPerCubicMeter, "W/m³")] + [InlineData("en-US", PowerDensityUnit.WattPerLiter, "W/l")] + public void GetAbbreviationForCulture(string culture, PowerDensityUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = PowerDensity.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(PowerDensity.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = PowerDensity.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(PowerDensityUnit unit) @@ -1679,6 +1333,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); }); } @@ -1702,75 +1357,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] @@ -1816,8 +1473,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); @@ -1854,23 +1509,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = PowerDensity.FromWattsPerCubicMeter(1); - Assert.True(v.Equals(PowerDensity.FromWattsPerCubicMeter(1), WattsPerCubicMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(PowerDensity.Zero, WattsPerCubicMeterTolerance, ComparisonType.Relative)); - Assert.True(PowerDensity.FromWattsPerCubicMeter(100).Equals(PowerDensity.FromWattsPerCubicMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(PowerDensity.FromWattsPerCubicMeter(100).Equals(PowerDensity.FromWattsPerCubicMeter(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = PowerDensity.FromWattsPerCubicMeter(1); - Assert.Throws(() => v.Equals(PowerDensity.FromWattsPerCubicMeter(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1885,6 +1523,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(wattpercubicmeter.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = PowerDensity.FromWattsPerCubicMeter(1); + var negativeTolerance = PowerDensity.FromWattsPerCubicMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1901,6 +1565,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() { @@ -2045,158 +1721,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(PowerDensity))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(PowerDensityUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal(PowerDensity.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal(PowerDensity.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal(new {PowerDensity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 6d91953ce4..6a09f3c601 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PowerRatioTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PowerRatioTestsBase.g.cs @@ -92,15 +92,33 @@ public void Ctor_WithNaNValue_DoNotThrowsArgumentException() [Fact] public void PowerRatio_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + PowerRatioUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new PowerRatio(1, PowerRatioUnit.DecibelWatt); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(PowerRatio.Zero, quantityInfo.Zero); Assert.Equal("PowerRatio", quantityInfo.Name); + Assert.Equal(PowerRatio.Zero, quantityInfo.Zero); + Assert.Equal(PowerRatio.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(PowerRatio.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void PowerRatioInfo_CreateWithCustomUnitInfos() + { + PowerRatioUnit[] expectedUnits = [PowerRatioUnit.DecibelWatt]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -115,11 +133,11 @@ public void DecibelWattToPowerRatioUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = PowerRatio.From(1, PowerRatioUnit.DecibelMilliwatt); - AssertEx.EqualTolerance(1, quantity00.DecibelMilliwatts, DecibelMilliwattsTolerance); + Assert.Equal(1, quantity00.DecibelMilliwatts); Assert.Equal(PowerRatioUnit.DecibelMilliwatt, quantity00.Unit); var quantity01 = PowerRatio.From(1, PowerRatioUnit.DecibelWatt); - AssertEx.EqualTolerance(1, quantity01.DecibelWatts, DecibelWattsTolerance); + Assert.Equal(1, quantity01.DecibelWatts); Assert.Equal(PowerRatioUnit.DecibelWatt, quantity01.Unit); } @@ -217,53 +235,28 @@ public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() }); } - [Fact] - public void Parse() + [Theory] + [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, decimal expectedValue) { - try - { - var parsed = PowerRatio.Parse("1 dBmW", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecibelMilliwatts, DecibelMilliwattsTolerance); - Assert.Equal(PowerRatioUnit.DecibelMilliwatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerRatio.Parse("1 dBm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecibelMilliwatts, DecibelMilliwattsTolerance); - Assert.Equal(PowerRatioUnit.DecibelMilliwatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PowerRatio.Parse("1 dBW", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecibelWatts, DecibelWattsTolerance); - Assert.Equal(PowerRatioUnit.DecibelWatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = PowerRatio.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [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, decimal expectedValue) { - { - Assert.True(PowerRatio.TryParse("1 dBmW", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecibelMilliwatts, DecibelMilliwattsTolerance); - Assert.Equal(PowerRatioUnit.DecibelMilliwatt, parsed.Unit); - } - - { - Assert.True(PowerRatio.TryParse("1 dBm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecibelMilliwatts, DecibelMilliwattsTolerance); - Assert.Equal(PowerRatioUnit.DecibelMilliwatt, parsed.Unit); - } - - { - Assert.True(PowerRatio.TryParse("1 dBW", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecibelWatts, DecibelWattsTolerance); - Assert.Equal(PowerRatioUnit.DecibelWatt, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(PowerRatio.TryParse(quantityString, out PowerRatio parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -356,6 +349,28 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, PowerR Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", PowerRatioUnit.DecibelMilliwatt, "dBmW")] + [InlineData("en-US", PowerRatioUnit.DecibelWatt, "dBW")] + public void GetAbbreviationForCulture(string culture, PowerRatioUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = PowerRatio.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(PowerRatio.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = PowerRatio.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(PowerRatioUnit unit) @@ -386,6 +401,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 +425,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 +503,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); @@ -524,34 +540,45 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = PowerRatio.FromDecibelWatts(1); - Assert.True(v.Equals(PowerRatio.FromDecibelWatts(1), DecibelWattsTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(PowerRatio.Zero, DecibelWattsTolerance, ComparisonType.Relative)); - Assert.True(PowerRatio.FromDecibelWatts(100).Equals(PowerRatio.FromDecibelWatts(120), 0.3, ComparisonType.Relative)); - Assert.False(PowerRatio.FromDecibelWatts(100).Equals(PowerRatio.FromDecibelWatts(120), 0.1, ComparisonType.Relative)); + PowerRatio decibelwatt = PowerRatio.FromDecibelWatts(1); + Assert.False(decibelwatt.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = PowerRatio.FromDecibelWatts(1); - Assert.Throws(() => v.Equals(PowerRatio.FromDecibelWatts(1), -1, ComparisonType.Relative)); + PowerRatio decibelwatt = PowerRatio.FromDecibelWatts(1); + Assert.False(decibelwatt.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - PowerRatio decibelwatt = PowerRatio.FromDecibelWatts(1); - Assert.False(decibelwatt.Equals(new object())); + var quantity = PowerRatio.FromDecibelWatts(firstValue); + var otherQuantity = PowerRatio.FromDecibelWatts(secondValue); + PowerRatio maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + // note: it's currently not possible to test this due to the rounding error from (quantity - otherQuantity) + // Assert.True(quantity.Equals(otherQuantity, maxTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_DoesNotThrowArgumentOutOfRangeException() { - PowerRatio decibelwatt = PowerRatio.FromDecibelWatts(1); - Assert.False(decibelwatt.Equals(null)); + // note: unlike with vector quantities- a small tolerance maybe positive in one unit and negative in another + var quantity = PowerRatio.FromDecibelWatts(1); + var negativeTolerance = PowerRatio.FromDecibelWatts(-1); + Assert.True(quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -570,6 +597,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() { @@ -630,158 +669,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(PowerRatio))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(PowerRatioUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal(PowerRatio.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal(PowerRatio.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal(new {PowerRatio.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 a58c390dde..eb7ab0d83c 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PowerTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PowerTestsBase.g.cs @@ -200,7 +200,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Power(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -213,15 +213,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Power_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + PowerUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Power(1, PowerUnit.Watt); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Power.Zero, quantityInfo.Zero); Assert.Equal("Power", quantityInfo.Name); + Assert.Equal(Power.Zero, quantityInfo.Zero); + Assert.Equal(Power.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Power.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + [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] @@ -261,111 +279,111 @@ public void WattToPowerUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Power.From(1, PowerUnit.BoilerHorsepower); - AssertEx.EqualTolerance(1, quantity00.BoilerHorsepower, BoilerHorsepowerTolerance); + Assert.Equal(1, quantity00.BoilerHorsepower); Assert.Equal(PowerUnit.BoilerHorsepower, quantity00.Unit); var quantity01 = Power.From(1, PowerUnit.BritishThermalUnitPerHour); - AssertEx.EqualTolerance(1, quantity01.BritishThermalUnitsPerHour, BritishThermalUnitsPerHourTolerance); + Assert.Equal(1, quantity01.BritishThermalUnitsPerHour); Assert.Equal(PowerUnit.BritishThermalUnitPerHour, quantity01.Unit); var quantity02 = Power.From(1, PowerUnit.Decawatt); - AssertEx.EqualTolerance(1, quantity02.Decawatts, DecawattsTolerance); + Assert.Equal(1, quantity02.Decawatts); Assert.Equal(PowerUnit.Decawatt, quantity02.Unit); var quantity03 = Power.From(1, PowerUnit.Deciwatt); - AssertEx.EqualTolerance(1, quantity03.Deciwatts, DeciwattsTolerance); + Assert.Equal(1, quantity03.Deciwatts); Assert.Equal(PowerUnit.Deciwatt, quantity03.Unit); var quantity04 = Power.From(1, PowerUnit.ElectricalHorsepower); - AssertEx.EqualTolerance(1, quantity04.ElectricalHorsepower, ElectricalHorsepowerTolerance); + Assert.Equal(1, quantity04.ElectricalHorsepower); Assert.Equal(PowerUnit.ElectricalHorsepower, quantity04.Unit); var quantity05 = Power.From(1, PowerUnit.Femtowatt); - AssertEx.EqualTolerance(1, quantity05.Femtowatts, FemtowattsTolerance); + Assert.Equal(1, quantity05.Femtowatts); Assert.Equal(PowerUnit.Femtowatt, quantity05.Unit); var quantity06 = Power.From(1, PowerUnit.GigajoulePerHour); - AssertEx.EqualTolerance(1, quantity06.GigajoulesPerHour, GigajoulesPerHourTolerance); + Assert.Equal(1, quantity06.GigajoulesPerHour); Assert.Equal(PowerUnit.GigajoulePerHour, quantity06.Unit); var quantity07 = Power.From(1, PowerUnit.Gigawatt); - AssertEx.EqualTolerance(1, quantity07.Gigawatts, GigawattsTolerance); + Assert.Equal(1, quantity07.Gigawatts); Assert.Equal(PowerUnit.Gigawatt, quantity07.Unit); var quantity08 = Power.From(1, PowerUnit.HydraulicHorsepower); - AssertEx.EqualTolerance(1, quantity08.HydraulicHorsepower, HydraulicHorsepowerTolerance); + Assert.Equal(1, quantity08.HydraulicHorsepower); Assert.Equal(PowerUnit.HydraulicHorsepower, quantity08.Unit); var quantity09 = Power.From(1, PowerUnit.JoulePerHour); - AssertEx.EqualTolerance(1, quantity09.JoulesPerHour, JoulesPerHourTolerance); + Assert.Equal(1, quantity09.JoulesPerHour); Assert.Equal(PowerUnit.JoulePerHour, quantity09.Unit); var quantity10 = Power.From(1, PowerUnit.KilobritishThermalUnitPerHour); - AssertEx.EqualTolerance(1, quantity10.KilobritishThermalUnitsPerHour, KilobritishThermalUnitsPerHourTolerance); + Assert.Equal(1, quantity10.KilobritishThermalUnitsPerHour); Assert.Equal(PowerUnit.KilobritishThermalUnitPerHour, quantity10.Unit); var quantity11 = Power.From(1, PowerUnit.KilojoulePerHour); - AssertEx.EqualTolerance(1, quantity11.KilojoulesPerHour, KilojoulesPerHourTolerance); + Assert.Equal(1, quantity11.KilojoulesPerHour); Assert.Equal(PowerUnit.KilojoulePerHour, quantity11.Unit); var quantity12 = Power.From(1, PowerUnit.Kilowatt); - AssertEx.EqualTolerance(1, quantity12.Kilowatts, KilowattsTolerance); + Assert.Equal(1, quantity12.Kilowatts); Assert.Equal(PowerUnit.Kilowatt, quantity12.Unit); var quantity13 = Power.From(1, PowerUnit.MechanicalHorsepower); - AssertEx.EqualTolerance(1, quantity13.MechanicalHorsepower, MechanicalHorsepowerTolerance); + Assert.Equal(1, quantity13.MechanicalHorsepower); Assert.Equal(PowerUnit.MechanicalHorsepower, quantity13.Unit); var quantity14 = Power.From(1, PowerUnit.MegabritishThermalUnitPerHour); - AssertEx.EqualTolerance(1, quantity14.MegabritishThermalUnitsPerHour, MegabritishThermalUnitsPerHourTolerance); + Assert.Equal(1, quantity14.MegabritishThermalUnitsPerHour); Assert.Equal(PowerUnit.MegabritishThermalUnitPerHour, quantity14.Unit); var quantity15 = Power.From(1, PowerUnit.MegajoulePerHour); - AssertEx.EqualTolerance(1, quantity15.MegajoulesPerHour, MegajoulesPerHourTolerance); + Assert.Equal(1, quantity15.MegajoulesPerHour); Assert.Equal(PowerUnit.MegajoulePerHour, quantity15.Unit); var quantity16 = Power.From(1, PowerUnit.Megawatt); - AssertEx.EqualTolerance(1, quantity16.Megawatts, MegawattsTolerance); + Assert.Equal(1, quantity16.Megawatts); Assert.Equal(PowerUnit.Megawatt, quantity16.Unit); var quantity17 = Power.From(1, PowerUnit.MetricHorsepower); - AssertEx.EqualTolerance(1, quantity17.MetricHorsepower, MetricHorsepowerTolerance); + Assert.Equal(1, quantity17.MetricHorsepower); Assert.Equal(PowerUnit.MetricHorsepower, quantity17.Unit); var quantity18 = Power.From(1, PowerUnit.Microwatt); - AssertEx.EqualTolerance(1, quantity18.Microwatts, MicrowattsTolerance); + Assert.Equal(1, quantity18.Microwatts); Assert.Equal(PowerUnit.Microwatt, quantity18.Unit); var quantity19 = Power.From(1, PowerUnit.MillijoulePerHour); - AssertEx.EqualTolerance(1, quantity19.MillijoulesPerHour, MillijoulesPerHourTolerance); + Assert.Equal(1, quantity19.MillijoulesPerHour); Assert.Equal(PowerUnit.MillijoulePerHour, quantity19.Unit); var quantity20 = Power.From(1, PowerUnit.Milliwatt); - AssertEx.EqualTolerance(1, quantity20.Milliwatts, MilliwattsTolerance); + Assert.Equal(1, quantity20.Milliwatts); Assert.Equal(PowerUnit.Milliwatt, quantity20.Unit); var quantity21 = Power.From(1, PowerUnit.Nanowatt); - AssertEx.EqualTolerance(1, quantity21.Nanowatts, NanowattsTolerance); + Assert.Equal(1, quantity21.Nanowatts); Assert.Equal(PowerUnit.Nanowatt, quantity21.Unit); var quantity22 = Power.From(1, PowerUnit.Petawatt); - AssertEx.EqualTolerance(1, quantity22.Petawatts, PetawattsTolerance); + Assert.Equal(1, quantity22.Petawatts); Assert.Equal(PowerUnit.Petawatt, quantity22.Unit); var quantity23 = Power.From(1, PowerUnit.Picowatt); - AssertEx.EqualTolerance(1, quantity23.Picowatts, PicowattsTolerance); + Assert.Equal(1, quantity23.Picowatts); Assert.Equal(PowerUnit.Picowatt, quantity23.Unit); var quantity24 = Power.From(1, PowerUnit.Terawatt); - AssertEx.EqualTolerance(1, quantity24.Terawatts, TerawattsTolerance); + Assert.Equal(1, quantity24.Terawatts); Assert.Equal(PowerUnit.Terawatt, quantity24.Unit); var quantity25 = Power.From(1, PowerUnit.TonOfRefrigeration); - AssertEx.EqualTolerance(1, quantity25.TonsOfRefrigeration, TonsOfRefrigerationTolerance); + Assert.Equal(1, quantity25.TonsOfRefrigeration); Assert.Equal(PowerUnit.TonOfRefrigeration, quantity25.Unit); var quantity26 = Power.From(1, PowerUnit.Watt); - AssertEx.EqualTolerance(1, quantity26.Watts, WattsTolerance); + Assert.Equal(1, quantity26.Watts); Assert.Equal(PowerUnit.Watt, quantity26.Unit); } @@ -527,368 +545,82 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 hp(S)", PowerUnit.BoilerHorsepower, 4.2)] + [InlineData("en-US", "4.2 Btu/h", PowerUnit.BritishThermalUnitPerHour, 4.2)] + [InlineData("en-US", "4.2 Btu/hr", PowerUnit.BritishThermalUnitPerHour, 4.2)] + [InlineData("en-US", "4.2 daW", PowerUnit.Decawatt, 4.2)] + [InlineData("en-US", "4.2 dW", PowerUnit.Deciwatt, 4.2)] + [InlineData("en-US", "4.2 hp(E)", PowerUnit.ElectricalHorsepower, 4.2)] + [InlineData("en-US", "4.2 fW", PowerUnit.Femtowatt, 4.2)] + [InlineData("en-US", "4.2 GJ/h", PowerUnit.GigajoulePerHour, 4.2)] + [InlineData("en-US", "4.2 GW", PowerUnit.Gigawatt, 4.2)] + [InlineData("en-US", "4.2 hp(H)", PowerUnit.HydraulicHorsepower, 4.2)] + [InlineData("en-US", "4.2 J/h", PowerUnit.JoulePerHour, 4.2)] + [InlineData("en-US", "4.2 kBtu/h", PowerUnit.KilobritishThermalUnitPerHour, 4.2)] + [InlineData("en-US", "4.2 kBtu/hr", PowerUnit.KilobritishThermalUnitPerHour, 4.2)] + [InlineData("en-US", "4.2 kJ/h", PowerUnit.KilojoulePerHour, 4.2)] + [InlineData("en-US", "4.2 kW", PowerUnit.Kilowatt, 4.2)] + [InlineData("en-US", "4.2 hp(I)", PowerUnit.MechanicalHorsepower, 4.2)] + [InlineData("en-US", "4.2 MBtu/h", PowerUnit.MegabritishThermalUnitPerHour, 4.2)] + [InlineData("en-US", "4.2 MBtu/hr", PowerUnit.MegabritishThermalUnitPerHour, 4.2)] + [InlineData("en-US", "4.2 MJ/h", PowerUnit.MegajoulePerHour, 4.2)] + [InlineData("en-US", "4.2 MW", PowerUnit.Megawatt, 4.2)] + [InlineData("en-US", "4.2 hp(M)", PowerUnit.MetricHorsepower, 4.2)] + [InlineData("en-US", "4.2 µW", PowerUnit.Microwatt, 4.2)] + [InlineData("en-US", "4.2 mJ/h", PowerUnit.MillijoulePerHour, 4.2)] + [InlineData("en-US", "4.2 mW", PowerUnit.Milliwatt, 4.2)] + [InlineData("en-US", "4.2 nW", PowerUnit.Nanowatt, 4.2)] + [InlineData("en-US", "4.2 PW", PowerUnit.Petawatt, 4.2)] + [InlineData("en-US", "4.2 pW", PowerUnit.Picowatt, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = Power.Parse("1 hp(S)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.BoilerHorsepower, BoilerHorsepowerTolerance); - Assert.Equal(PowerUnit.BoilerHorsepower, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 Btu/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.BritishThermalUnitsPerHour, BritishThermalUnitsPerHourTolerance); - Assert.Equal(PowerUnit.BritishThermalUnitPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 Btu/hr", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.BritishThermalUnitsPerHour, BritishThermalUnitsPerHourTolerance); - Assert.Equal(PowerUnit.BritishThermalUnitPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 daW", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Decawatts, DecawattsTolerance); - Assert.Equal(PowerUnit.Decawatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 dW", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Deciwatts, DeciwattsTolerance); - Assert.Equal(PowerUnit.Deciwatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 hp(E)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ElectricalHorsepower, ElectricalHorsepowerTolerance); - Assert.Equal(PowerUnit.ElectricalHorsepower, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 fW", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Femtowatts, FemtowattsTolerance); - Assert.Equal(PowerUnit.Femtowatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 GJ/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GigajoulesPerHour, GigajoulesPerHourTolerance); - Assert.Equal(PowerUnit.GigajoulePerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 GW", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Gigawatts, GigawattsTolerance); - Assert.Equal(PowerUnit.Gigawatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 hp(H)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.HydraulicHorsepower, HydraulicHorsepowerTolerance); - Assert.Equal(PowerUnit.HydraulicHorsepower, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 J/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.JoulesPerHour, JoulesPerHourTolerance); - Assert.Equal(PowerUnit.JoulePerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 kBtu/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilobritishThermalUnitsPerHour, KilobritishThermalUnitsPerHourTolerance); - Assert.Equal(PowerUnit.KilobritishThermalUnitPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 kBtu/hr", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilobritishThermalUnitsPerHour, KilobritishThermalUnitsPerHourTolerance); - Assert.Equal(PowerUnit.KilobritishThermalUnitPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 kJ/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilojoulesPerHour, KilojoulesPerHourTolerance); - Assert.Equal(PowerUnit.KilojoulePerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 kW", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilowatts, KilowattsTolerance); - Assert.Equal(PowerUnit.Kilowatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 hp(I)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MechanicalHorsepower, MechanicalHorsepowerTolerance); - Assert.Equal(PowerUnit.MechanicalHorsepower, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 MBtu/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegabritishThermalUnitsPerHour, MegabritishThermalUnitsPerHourTolerance); - Assert.Equal(PowerUnit.MegabritishThermalUnitPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 MBtu/hr", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegabritishThermalUnitsPerHour, MegabritishThermalUnitsPerHourTolerance); - Assert.Equal(PowerUnit.MegabritishThermalUnitPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 MJ/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegajoulesPerHour, MegajoulesPerHourTolerance); - Assert.Equal(PowerUnit.MegajoulePerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 MW", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megawatts, MegawattsTolerance); - Assert.Equal(PowerUnit.Megawatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 hp(M)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MetricHorsepower, MetricHorsepowerTolerance); - Assert.Equal(PowerUnit.MetricHorsepower, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 µW", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microwatts, MicrowattsTolerance); - Assert.Equal(PowerUnit.Microwatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 mJ/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillijoulesPerHour, MillijoulesPerHourTolerance); - Assert.Equal(PowerUnit.MillijoulePerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 mW", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Milliwatts, MilliwattsTolerance); - Assert.Equal(PowerUnit.Milliwatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 nW", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanowatts, NanowattsTolerance); - Assert.Equal(PowerUnit.Nanowatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 PW", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Petawatts, PetawattsTolerance); - Assert.Equal(PowerUnit.Petawatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 pW", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Picowatts, PicowattsTolerance); - Assert.Equal(PowerUnit.Picowatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 TW", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Terawatts, TerawattsTolerance); - Assert.Equal(PowerUnit.Terawatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 TR", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonsOfRefrigeration, TonsOfRefrigerationTolerance); - Assert.Equal(PowerUnit.TonOfRefrigeration, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Power.Parse("1 W", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Watts, WattsTolerance); - Assert.Equal(PowerUnit.Watt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Power.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 hp(S)", PowerUnit.BoilerHorsepower, 4.2)] + [InlineData("en-US", "4.2 Btu/h", PowerUnit.BritishThermalUnitPerHour, 4.2)] + [InlineData("en-US", "4.2 Btu/hr", PowerUnit.BritishThermalUnitPerHour, 4.2)] + [InlineData("en-US", "4.2 daW", PowerUnit.Decawatt, 4.2)] + [InlineData("en-US", "4.2 dW", PowerUnit.Deciwatt, 4.2)] + [InlineData("en-US", "4.2 hp(E)", PowerUnit.ElectricalHorsepower, 4.2)] + [InlineData("en-US", "4.2 fW", PowerUnit.Femtowatt, 4.2)] + [InlineData("en-US", "4.2 GJ/h", PowerUnit.GigajoulePerHour, 4.2)] + [InlineData("en-US", "4.2 GW", PowerUnit.Gigawatt, 4.2)] + [InlineData("en-US", "4.2 hp(H)", PowerUnit.HydraulicHorsepower, 4.2)] + [InlineData("en-US", "4.2 J/h", PowerUnit.JoulePerHour, 4.2)] + [InlineData("en-US", "4.2 kBtu/h", PowerUnit.KilobritishThermalUnitPerHour, 4.2)] + [InlineData("en-US", "4.2 kBtu/hr", PowerUnit.KilobritishThermalUnitPerHour, 4.2)] + [InlineData("en-US", "4.2 kJ/h", PowerUnit.KilojoulePerHour, 4.2)] + [InlineData("en-US", "4.2 kW", PowerUnit.Kilowatt, 4.2)] + [InlineData("en-US", "4.2 hp(I)", PowerUnit.MechanicalHorsepower, 4.2)] + [InlineData("en-US", "4.2 MBtu/h", PowerUnit.MegabritishThermalUnitPerHour, 4.2)] + [InlineData("en-US", "4.2 MBtu/hr", PowerUnit.MegabritishThermalUnitPerHour, 4.2)] + [InlineData("en-US", "4.2 MJ/h", PowerUnit.MegajoulePerHour, 4.2)] + [InlineData("en-US", "4.2 MW", PowerUnit.Megawatt, 4.2)] + [InlineData("en-US", "4.2 hp(M)", PowerUnit.MetricHorsepower, 4.2)] + [InlineData("en-US", "4.2 µW", PowerUnit.Microwatt, 4.2)] + [InlineData("en-US", "4.2 mJ/h", PowerUnit.MillijoulePerHour, 4.2)] + [InlineData("en-US", "4.2 mW", PowerUnit.Milliwatt, 4.2)] + [InlineData("en-US", "4.2 nW", PowerUnit.Nanowatt, 4.2)] + [InlineData("en-US", "4.2 PW", PowerUnit.Petawatt, 4.2)] + [InlineData("en-US", "4.2 pW", PowerUnit.Picowatt, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(Power.TryParse("1 hp(S)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BoilerHorsepower, BoilerHorsepowerTolerance); - Assert.Equal(PowerUnit.BoilerHorsepower, parsed.Unit); - } - - { - Assert.True(Power.TryParse("1 Btu/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BritishThermalUnitsPerHour, BritishThermalUnitsPerHourTolerance); - Assert.Equal(PowerUnit.BritishThermalUnitPerHour, parsed.Unit); - } - - { - Assert.True(Power.TryParse("1 Btu/hr", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BritishThermalUnitsPerHour, BritishThermalUnitsPerHourTolerance); - Assert.Equal(PowerUnit.BritishThermalUnitPerHour, parsed.Unit); - } - - { - Assert.True(Power.TryParse("1 daW", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Decawatts, DecawattsTolerance); - Assert.Equal(PowerUnit.Decawatt, parsed.Unit); - } - - { - Assert.True(Power.TryParse("1 dW", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Deciwatts, DeciwattsTolerance); - Assert.Equal(PowerUnit.Deciwatt, parsed.Unit); - } - - { - Assert.True(Power.TryParse("1 hp(E)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ElectricalHorsepower, ElectricalHorsepowerTolerance); - Assert.Equal(PowerUnit.ElectricalHorsepower, parsed.Unit); - } - - { - Assert.True(Power.TryParse("1 fW", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Femtowatts, FemtowattsTolerance); - Assert.Equal(PowerUnit.Femtowatt, parsed.Unit); - } - - { - Assert.True(Power.TryParse("1 GJ/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigajoulesPerHour, GigajoulesPerHourTolerance); - Assert.Equal(PowerUnit.GigajoulePerHour, parsed.Unit); - } - - { - Assert.True(Power.TryParse("1 GW", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gigawatts, GigawattsTolerance); - Assert.Equal(PowerUnit.Gigawatt, parsed.Unit); - } - - { - Assert.True(Power.TryParse("1 hp(H)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HydraulicHorsepower, HydraulicHorsepowerTolerance); - Assert.Equal(PowerUnit.HydraulicHorsepower, parsed.Unit); - } - - { - Assert.True(Power.TryParse("1 J/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.JoulesPerHour, JoulesPerHourTolerance); - Assert.Equal(PowerUnit.JoulePerHour, parsed.Unit); - } - - { - Assert.True(Power.TryParse("1 kBtu/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilobritishThermalUnitsPerHour, KilobritishThermalUnitsPerHourTolerance); - Assert.Equal(PowerUnit.KilobritishThermalUnitPerHour, parsed.Unit); - } - - { - Assert.True(Power.TryParse("1 kBtu/hr", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilobritishThermalUnitsPerHour, KilobritishThermalUnitsPerHourTolerance); - Assert.Equal(PowerUnit.KilobritishThermalUnitPerHour, parsed.Unit); - } - - { - Assert.True(Power.TryParse("1 kJ/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilojoulesPerHour, KilojoulesPerHourTolerance); - Assert.Equal(PowerUnit.KilojoulePerHour, parsed.Unit); - } - - { - Assert.True(Power.TryParse("1 kW", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilowatts, KilowattsTolerance); - Assert.Equal(PowerUnit.Kilowatt, parsed.Unit); - } - - { - Assert.True(Power.TryParse("1 hp(I)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MechanicalHorsepower, MechanicalHorsepowerTolerance); - Assert.Equal(PowerUnit.MechanicalHorsepower, parsed.Unit); - } - - { - Assert.True(Power.TryParse("1 MBtu/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegabritishThermalUnitsPerHour, MegabritishThermalUnitsPerHourTolerance); - Assert.Equal(PowerUnit.MegabritishThermalUnitPerHour, parsed.Unit); - } - - { - Assert.True(Power.TryParse("1 MBtu/hr", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegabritishThermalUnitsPerHour, MegabritishThermalUnitsPerHourTolerance); - Assert.Equal(PowerUnit.MegabritishThermalUnitPerHour, parsed.Unit); - } - - { - Assert.True(Power.TryParse("1 hp(M)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetricHorsepower, MetricHorsepowerTolerance); - Assert.Equal(PowerUnit.MetricHorsepower, parsed.Unit); - } - - { - Assert.True(Power.TryParse("1 µW", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microwatts, MicrowattsTolerance); - Assert.Equal(PowerUnit.Microwatt, parsed.Unit); - } - - { - Assert.True(Power.TryParse("1 nW", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanowatts, NanowattsTolerance); - Assert.Equal(PowerUnit.Nanowatt, parsed.Unit); - } - - { - Assert.True(Power.TryParse("1 TW", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Terawatts, TerawattsTolerance); - Assert.Equal(PowerUnit.Terawatt, parsed.Unit); - } - - { - Assert.True(Power.TryParse("1 TR", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonsOfRefrigeration, TonsOfRefrigerationTolerance); - Assert.Equal(PowerUnit.TonOfRefrigeration, parsed.Unit); - } - - { - Assert.True(Power.TryParse("1 W", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Watts, WattsTolerance); - Assert.Equal(PowerUnit.Watt, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Power.TryParse(quantityString, out Power parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -1197,6 +929,53 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, PowerU Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", PowerUnit.BoilerHorsepower, "hp(S)")] + [InlineData("en-US", PowerUnit.BritishThermalUnitPerHour, "Btu/h")] + [InlineData("en-US", PowerUnit.Decawatt, "daW")] + [InlineData("en-US", PowerUnit.Deciwatt, "dW")] + [InlineData("en-US", PowerUnit.ElectricalHorsepower, "hp(E)")] + [InlineData("en-US", PowerUnit.Femtowatt, "fW")] + [InlineData("en-US", PowerUnit.GigajoulePerHour, "GJ/h")] + [InlineData("en-US", PowerUnit.Gigawatt, "GW")] + [InlineData("en-US", PowerUnit.HydraulicHorsepower, "hp(H)")] + [InlineData("en-US", PowerUnit.JoulePerHour, "J/h")] + [InlineData("en-US", PowerUnit.KilobritishThermalUnitPerHour, "kBtu/h")] + [InlineData("en-US", PowerUnit.KilojoulePerHour, "kJ/h")] + [InlineData("en-US", PowerUnit.Kilowatt, "kW")] + [InlineData("en-US", PowerUnit.MechanicalHorsepower, "hp(I)")] + [InlineData("en-US", PowerUnit.MegabritishThermalUnitPerHour, "MBtu/h")] + [InlineData("en-US", PowerUnit.MegajoulePerHour, "MJ/h")] + [InlineData("en-US", PowerUnit.Megawatt, "MW")] + [InlineData("en-US", PowerUnit.MetricHorsepower, "hp(M)")] + [InlineData("en-US", PowerUnit.Microwatt, "µW")] + [InlineData("en-US", PowerUnit.MillijoulePerHour, "mJ/h")] + [InlineData("en-US", PowerUnit.Milliwatt, "mW")] + [InlineData("en-US", PowerUnit.Nanowatt, "nW")] + [InlineData("en-US", PowerUnit.Petawatt, "PW")] + [InlineData("en-US", PowerUnit.Picowatt, "pW")] + [InlineData("en-US", PowerUnit.Terawatt, "TW")] + [InlineData("en-US", PowerUnit.TonOfRefrigeration, "TR")] + [InlineData("en-US", PowerUnit.Watt, "W")] + public void GetAbbreviationForCulture(string culture, PowerUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Power.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Power.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Power.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(PowerUnit unit) @@ -1227,6 +1006,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); }); } @@ -1250,58 +1030,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] @@ -1347,8 +1129,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); @@ -1385,23 +1165,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = Power.FromWatts(1); - Assert.True(v.Equals(Power.FromWatts(1), WattsTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Power.Zero, WattsTolerance, ComparisonType.Relative)); - Assert.True(Power.FromWatts(100).Equals(Power.FromWatts(120), 0.3, ComparisonType.Relative)); - Assert.False(Power.FromWatts(100).Equals(Power.FromWatts(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = Power.FromWatts(1); - Assert.Throws(() => v.Equals(Power.FromWatts(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1416,6 +1179,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(watt.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = Power.FromWatts(1); + var negativeTolerance = Power.FromWatts(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1432,6 +1221,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() { @@ -1542,158 +1343,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Power.FromWatts(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Power.FromWatts(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Power.FromWatts(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Power.FromWatts(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Power.FromWatts(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Power.FromWatts(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Power.FromWatts(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Power.FromWatts(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Power.FromWatts(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Power.FromWatts(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Power.FromWatts(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Power.FromWatts(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Power.FromWatts(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Power.FromWatts(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Power.FromWatts(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Power.FromWatts(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Power))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Power.FromWatts(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(PowerUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Power.FromWatts(1.0); - Assert.Equal(Power.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Power.FromWatts(1.0); - Assert.Equal(Power.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Power.FromWatts(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Power.FromWatts(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Power.FromWatts(1.0); - Assert.Equal(new {Power.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 c1b2f8fbcd..ee2ad9ce38 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PressureChangeRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PressureChangeRateTestsBase.g.cs @@ -164,7 +164,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new PressureChangeRate(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -177,15 +177,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void PressureChangeRate_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + PressureChangeRateUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new PressureChangeRate(1, PressureChangeRateUnit.PascalPerSecond); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(PressureChangeRate.Zero, quantityInfo.Zero); Assert.Equal("PressureChangeRate", quantityInfo.Name); + Assert.Equal(PressureChangeRate.Zero, quantityInfo.Zero); + Assert.Equal(PressureChangeRate.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(PressureChangeRate.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -216,75 +234,75 @@ public void PascalPerSecondToPressureChangeRateUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = PressureChangeRate.From(1, PressureChangeRateUnit.AtmospherePerSecond); - AssertEx.EqualTolerance(1, quantity00.AtmospheresPerSecond, AtmospheresPerSecondTolerance); + Assert.Equal(1, quantity00.AtmospheresPerSecond); Assert.Equal(PressureChangeRateUnit.AtmospherePerSecond, quantity00.Unit); var quantity01 = PressureChangeRate.From(1, PressureChangeRateUnit.BarPerMinute); - AssertEx.EqualTolerance(1, quantity01.BarsPerMinute, BarsPerMinuteTolerance); + Assert.Equal(1, quantity01.BarsPerMinute); Assert.Equal(PressureChangeRateUnit.BarPerMinute, quantity01.Unit); var quantity02 = PressureChangeRate.From(1, PressureChangeRateUnit.BarPerSecond); - AssertEx.EqualTolerance(1, quantity02.BarsPerSecond, BarsPerSecondTolerance); + Assert.Equal(1, quantity02.BarsPerSecond); Assert.Equal(PressureChangeRateUnit.BarPerSecond, quantity02.Unit); var quantity03 = PressureChangeRate.From(1, PressureChangeRateUnit.KilopascalPerMinute); - AssertEx.EqualTolerance(1, quantity03.KilopascalsPerMinute, KilopascalsPerMinuteTolerance); + Assert.Equal(1, quantity03.KilopascalsPerMinute); Assert.Equal(PressureChangeRateUnit.KilopascalPerMinute, quantity03.Unit); var quantity04 = PressureChangeRate.From(1, PressureChangeRateUnit.KilopascalPerSecond); - AssertEx.EqualTolerance(1, quantity04.KilopascalsPerSecond, KilopascalsPerSecondTolerance); + Assert.Equal(1, quantity04.KilopascalsPerSecond); Assert.Equal(PressureChangeRateUnit.KilopascalPerSecond, quantity04.Unit); var quantity05 = PressureChangeRate.From(1, PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute); - AssertEx.EqualTolerance(1, quantity05.KilopoundsForcePerSquareInchPerMinute, KilopoundsForcePerSquareInchPerMinuteTolerance); + Assert.Equal(1, quantity05.KilopoundsForcePerSquareInchPerMinute); Assert.Equal(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, quantity05.Unit); var quantity06 = PressureChangeRate.From(1, PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond); - AssertEx.EqualTolerance(1, quantity06.KilopoundsForcePerSquareInchPerSecond, KilopoundsForcePerSquareInchPerSecondTolerance); + Assert.Equal(1, quantity06.KilopoundsForcePerSquareInchPerSecond); Assert.Equal(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, quantity06.Unit); var quantity07 = PressureChangeRate.From(1, PressureChangeRateUnit.MegapascalPerMinute); - AssertEx.EqualTolerance(1, quantity07.MegapascalsPerMinute, MegapascalsPerMinuteTolerance); + Assert.Equal(1, quantity07.MegapascalsPerMinute); Assert.Equal(PressureChangeRateUnit.MegapascalPerMinute, quantity07.Unit); var quantity08 = PressureChangeRate.From(1, PressureChangeRateUnit.MegapascalPerSecond); - AssertEx.EqualTolerance(1, quantity08.MegapascalsPerSecond, MegapascalsPerSecondTolerance); + Assert.Equal(1, quantity08.MegapascalsPerSecond); Assert.Equal(PressureChangeRateUnit.MegapascalPerSecond, quantity08.Unit); var quantity09 = PressureChangeRate.From(1, PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute); - AssertEx.EqualTolerance(1, quantity09.MegapoundsForcePerSquareInchPerMinute, MegapoundsForcePerSquareInchPerMinuteTolerance); + Assert.Equal(1, quantity09.MegapoundsForcePerSquareInchPerMinute); Assert.Equal(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, quantity09.Unit); var quantity10 = PressureChangeRate.From(1, PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond); - AssertEx.EqualTolerance(1, quantity10.MegapoundsForcePerSquareInchPerSecond, MegapoundsForcePerSquareInchPerSecondTolerance); + Assert.Equal(1, quantity10.MegapoundsForcePerSquareInchPerSecond); Assert.Equal(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, quantity10.Unit); var quantity11 = PressureChangeRate.From(1, PressureChangeRateUnit.MillibarPerMinute); - AssertEx.EqualTolerance(1, quantity11.MillibarsPerMinute, MillibarsPerMinuteTolerance); + Assert.Equal(1, quantity11.MillibarsPerMinute); Assert.Equal(PressureChangeRateUnit.MillibarPerMinute, quantity11.Unit); var quantity12 = PressureChangeRate.From(1, PressureChangeRateUnit.MillibarPerSecond); - AssertEx.EqualTolerance(1, quantity12.MillibarsPerSecond, MillibarsPerSecondTolerance); + Assert.Equal(1, quantity12.MillibarsPerSecond); Assert.Equal(PressureChangeRateUnit.MillibarPerSecond, quantity12.Unit); var quantity13 = PressureChangeRate.From(1, PressureChangeRateUnit.MillimeterOfMercuryPerSecond); - AssertEx.EqualTolerance(1, quantity13.MillimetersOfMercuryPerSecond, MillimetersOfMercuryPerSecondTolerance); + Assert.Equal(1, quantity13.MillimetersOfMercuryPerSecond); Assert.Equal(PressureChangeRateUnit.MillimeterOfMercuryPerSecond, quantity13.Unit); var quantity14 = PressureChangeRate.From(1, PressureChangeRateUnit.PascalPerMinute); - AssertEx.EqualTolerance(1, quantity14.PascalsPerMinute, PascalsPerMinuteTolerance); + Assert.Equal(1, quantity14.PascalsPerMinute); Assert.Equal(PressureChangeRateUnit.PascalPerMinute, quantity14.Unit); var quantity15 = PressureChangeRate.From(1, PressureChangeRateUnit.PascalPerSecond); - AssertEx.EqualTolerance(1, quantity15.PascalsPerSecond, PascalsPerSecondTolerance); + Assert.Equal(1, quantity15.PascalsPerSecond); Assert.Equal(PressureChangeRateUnit.PascalPerSecond, quantity15.Unit); var quantity16 = PressureChangeRate.From(1, PressureChangeRateUnit.PoundForcePerSquareInchPerMinute); - AssertEx.EqualTolerance(1, quantity16.PoundsForcePerSquareInchPerMinute, PoundsForcePerSquareInchPerMinuteTolerance); + Assert.Equal(1, quantity16.PoundsForcePerSquareInchPerMinute); Assert.Equal(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, quantity16.Unit); var quantity17 = PressureChangeRate.From(1, PressureChangeRateUnit.PoundForcePerSquareInchPerSecond); - AssertEx.EqualTolerance(1, quantity17.PoundsForcePerSquareInchPerSecond, PoundsForcePerSquareInchPerSecondTolerance); + Assert.Equal(1, quantity17.PoundsForcePerSquareInchPerSecond); Assert.Equal(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, quantity17.Unit); } @@ -437,638 +455,118 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 atm/s", PressureChangeRateUnit.AtmospherePerSecond, 4.2)] + [InlineData("en-US", "4.2 bar/min", PressureChangeRateUnit.BarPerMinute, 4.2)] + [InlineData("en-US", "4.2 bar/s", PressureChangeRateUnit.BarPerSecond, 4.2)] + [InlineData("en-US", "4.2 kPa/min", PressureChangeRateUnit.KilopascalPerMinute, 4.2)] + [InlineData("en-US", "4.2 kPa/s", PressureChangeRateUnit.KilopascalPerSecond, 4.2)] + [InlineData("en-US", "4.2 ksi/min", PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, 4.2)] + [InlineData("en-US", "4.2 kipf/in²/min", PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, 4.2)] + [InlineData("en-US", "4.2 ksi/s", PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, 4.2)] + [InlineData("en-US", "4.2 kipf/in²/s", PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, 4.2)] + [InlineData("en-US", "4.2 MPa/min", PressureChangeRateUnit.MegapascalPerMinute, 4.2)] + [InlineData("en-US", "4.2 MPa/s", PressureChangeRateUnit.MegapascalPerSecond, 4.2)] + [InlineData("en-US", "4.2 Mpsi/min", PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, 4.2)] + [InlineData("en-US", "4.2 Mlb/in²/min", PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, 4.2)] + [InlineData("en-US", "4.2 Mpsi/s", PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, 4.2)] + [InlineData("en-US", "4.2 Mlb/in²/s", PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, 4.2)] + [InlineData("en-US", "4.2 mbar/min", PressureChangeRateUnit.MillibarPerMinute, 4.2)] + [InlineData("en-US", "4.2 mbar/s", PressureChangeRateUnit.MillibarPerSecond, 4.2)] + [InlineData("en-US", "4.2 mmHg/s", PressureChangeRateUnit.MillimeterOfMercuryPerSecond, 4.2)] + [InlineData("en-US", "4.2 Pa/min", PressureChangeRateUnit.PascalPerMinute, 4.2)] + [InlineData("en-US", "4.2 Pa/s", PressureChangeRateUnit.PascalPerSecond, 4.2)] + [InlineData("en-US", "4.2 psi/min", PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, 4.2)] + [InlineData("en-US", "4.2 lb/in²/min", PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, 4.2)] + [InlineData("en-US", "4.2 psi/s", PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, 4.2)] + [InlineData("en-US", "4.2 lb/in²/s", PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 атм/с", PressureChangeRateUnit.AtmospherePerSecond, 4.2)] + [InlineData("ru-RU", "4,2 бар/мин", PressureChangeRateUnit.BarPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 бар/с", PressureChangeRateUnit.BarPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 кПа/мин", PressureChangeRateUnit.KilopascalPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 кПа/с", PressureChangeRateUnit.KilopascalPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 ksi/мин", PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 kipf/in²/мин", PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 ksi/с", PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 kipf/in²/с", PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 МПа/мин", PressureChangeRateUnit.MegapascalPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 МПа/с", PressureChangeRateUnit.MegapascalPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 Мpsi/мин", PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 Мlb/in²/мин", PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 Мpsi/с", PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 Мlb/in²/с", PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 мбар/мин", PressureChangeRateUnit.MillibarPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 мбар/с", PressureChangeRateUnit.MillibarPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 mmHg/с", PressureChangeRateUnit.MillimeterOfMercuryPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 Па/мин", PressureChangeRateUnit.PascalPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 Па/с", PressureChangeRateUnit.PascalPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 psi/мин", PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = PressureChangeRate.Parse("1 atm/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.AtmospheresPerSecond, AtmospheresPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.AtmospherePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 атм/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.AtmospheresPerSecond, AtmospheresPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.AtmospherePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 bar/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.BarsPerMinute, BarsPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.BarPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 бар/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.BarsPerMinute, BarsPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.BarPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 bar/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.BarsPerSecond, BarsPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.BarPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 бар/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.BarsPerSecond, BarsPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.BarPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 kPa/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopascalsPerMinute, KilopascalsPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.KilopascalPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 кПа/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilopascalsPerMinute, KilopascalsPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.KilopascalPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 kPa/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopascalsPerSecond, KilopascalsPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.KilopascalPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 кПа/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilopascalsPerSecond, KilopascalsPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.KilopascalPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 ksi/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareInchPerMinute, KilopoundsForcePerSquareInchPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 kipf/in²/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareInchPerMinute, KilopoundsForcePerSquareInchPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 ksi/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareInchPerMinute, KilopoundsForcePerSquareInchPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 kipf/in²/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareInchPerMinute, KilopoundsForcePerSquareInchPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 ksi/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareInchPerSecond, KilopoundsForcePerSquareInchPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 kipf/in²/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareInchPerSecond, KilopoundsForcePerSquareInchPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 ksi/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareInchPerSecond, KilopoundsForcePerSquareInchPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 kipf/in²/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareInchPerSecond, KilopoundsForcePerSquareInchPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 MPa/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegapascalsPerMinute, MegapascalsPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.MegapascalPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 МПа/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MegapascalsPerMinute, MegapascalsPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.MegapascalPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 MPa/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegapascalsPerSecond, MegapascalsPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.MegapascalPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 МПа/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MegapascalsPerSecond, MegapascalsPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.MegapascalPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 Mpsi/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegapoundsForcePerSquareInchPerMinute, MegapoundsForcePerSquareInchPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 Mlb/in²/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegapoundsForcePerSquareInchPerMinute, MegapoundsForcePerSquareInchPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 Мpsi/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MegapoundsForcePerSquareInchPerMinute, MegapoundsForcePerSquareInchPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 Мlb/in²/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MegapoundsForcePerSquareInchPerMinute, MegapoundsForcePerSquareInchPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 Mpsi/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegapoundsForcePerSquareInchPerSecond, MegapoundsForcePerSquareInchPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 Mlb/in²/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegapoundsForcePerSquareInchPerSecond, MegapoundsForcePerSquareInchPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 Мpsi/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MegapoundsForcePerSquareInchPerSecond, MegapoundsForcePerSquareInchPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 Мlb/in²/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MegapoundsForcePerSquareInchPerSecond, MegapoundsForcePerSquareInchPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 mbar/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillibarsPerMinute, MillibarsPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.MillibarPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 мбар/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MillibarsPerMinute, MillibarsPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.MillibarPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 mbar/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillibarsPerSecond, MillibarsPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.MillibarPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 мбар/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MillibarsPerSecond, MillibarsPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.MillibarPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 mmHg/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillimetersOfMercuryPerSecond, MillimetersOfMercuryPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.MillimeterOfMercuryPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 mmHg/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MillimetersOfMercuryPerSecond, MillimetersOfMercuryPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.MillimeterOfMercuryPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 Pa/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PascalsPerMinute, PascalsPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.PascalPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 Па/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.PascalsPerMinute, PascalsPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.PascalPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 Pa/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PascalsPerSecond, PascalsPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.PascalPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 Па/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.PascalsPerSecond, PascalsPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.PascalPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 psi/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareInchPerMinute, PoundsForcePerSquareInchPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 lb/in²/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareInchPerMinute, PoundsForcePerSquareInchPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 psi/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareInchPerMinute, PoundsForcePerSquareInchPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 lb/in²/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareInchPerMinute, PoundsForcePerSquareInchPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 psi/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareInchPerSecond, PoundsForcePerSquareInchPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 lb/in²/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareInchPerSecond, PoundsForcePerSquareInchPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 psi/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareInchPerSecond, PoundsForcePerSquareInchPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = PressureChangeRate.Parse("1 lb/in²/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareInchPerSecond, PoundsForcePerSquareInchPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = PressureChangeRate.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 atm/s", PressureChangeRateUnit.AtmospherePerSecond, 4.2)] + [InlineData("en-US", "4.2 bar/min", PressureChangeRateUnit.BarPerMinute, 4.2)] + [InlineData("en-US", "4.2 bar/s", PressureChangeRateUnit.BarPerSecond, 4.2)] + [InlineData("en-US", "4.2 kPa/min", PressureChangeRateUnit.KilopascalPerMinute, 4.2)] + [InlineData("en-US", "4.2 kPa/s", PressureChangeRateUnit.KilopascalPerSecond, 4.2)] + [InlineData("en-US", "4.2 ksi/min", PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, 4.2)] + [InlineData("en-US", "4.2 kipf/in²/min", PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, 4.2)] + [InlineData("en-US", "4.2 ksi/s", PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, 4.2)] + [InlineData("en-US", "4.2 kipf/in²/s", PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, 4.2)] + [InlineData("en-US", "4.2 MPa/min", PressureChangeRateUnit.MegapascalPerMinute, 4.2)] + [InlineData("en-US", "4.2 MPa/s", PressureChangeRateUnit.MegapascalPerSecond, 4.2)] + [InlineData("en-US", "4.2 Mpsi/min", PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, 4.2)] + [InlineData("en-US", "4.2 Mlb/in²/min", PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, 4.2)] + [InlineData("en-US", "4.2 Mpsi/s", PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, 4.2)] + [InlineData("en-US", "4.2 Mlb/in²/s", PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, 4.2)] + [InlineData("en-US", "4.2 mbar/min", PressureChangeRateUnit.MillibarPerMinute, 4.2)] + [InlineData("en-US", "4.2 mbar/s", PressureChangeRateUnit.MillibarPerSecond, 4.2)] + [InlineData("en-US", "4.2 mmHg/s", PressureChangeRateUnit.MillimeterOfMercuryPerSecond, 4.2)] + [InlineData("en-US", "4.2 Pa/min", PressureChangeRateUnit.PascalPerMinute, 4.2)] + [InlineData("en-US", "4.2 Pa/s", PressureChangeRateUnit.PascalPerSecond, 4.2)] + [InlineData("en-US", "4.2 psi/min", PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, 4.2)] + [InlineData("en-US", "4.2 lb/in²/min", PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, 4.2)] + [InlineData("en-US", "4.2 psi/s", PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, 4.2)] + [InlineData("en-US", "4.2 lb/in²/s", PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 атм/с", PressureChangeRateUnit.AtmospherePerSecond, 4.2)] + [InlineData("ru-RU", "4,2 бар/мин", PressureChangeRateUnit.BarPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 бар/с", PressureChangeRateUnit.BarPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 кПа/мин", PressureChangeRateUnit.KilopascalPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 кПа/с", PressureChangeRateUnit.KilopascalPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 ksi/мин", PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 kipf/in²/мин", PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 ksi/с", PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 kipf/in²/с", PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 МПа/мин", PressureChangeRateUnit.MegapascalPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 МПа/с", PressureChangeRateUnit.MegapascalPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 Мpsi/мин", PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 Мlb/in²/мин", PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 Мpsi/с", PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 Мlb/in²/с", PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 мбар/мин", PressureChangeRateUnit.MillibarPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 мбар/с", PressureChangeRateUnit.MillibarPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 mmHg/с", PressureChangeRateUnit.MillimeterOfMercuryPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 Па/мин", PressureChangeRateUnit.PascalPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 Па/с", PressureChangeRateUnit.PascalPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 psi/мин", PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(PressureChangeRate.TryParse("1 atm/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.AtmospheresPerSecond, AtmospheresPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.AtmospherePerSecond, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 атм/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.AtmospheresPerSecond, AtmospheresPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.AtmospherePerSecond, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 bar/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BarsPerMinute, BarsPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.BarPerMinute, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 бар/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BarsPerMinute, BarsPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.BarPerMinute, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 bar/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BarsPerSecond, BarsPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.BarPerSecond, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 бар/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BarsPerSecond, BarsPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.BarPerSecond, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 kPa/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopascalsPerMinute, KilopascalsPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.KilopascalPerMinute, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 кПа/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopascalsPerMinute, KilopascalsPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.KilopascalPerMinute, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 kPa/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopascalsPerSecond, KilopascalsPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.KilopascalPerSecond, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 кПа/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopascalsPerSecond, KilopascalsPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.KilopascalPerSecond, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 ksi/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareInchPerMinute, KilopoundsForcePerSquareInchPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 kipf/in²/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareInchPerMinute, KilopoundsForcePerSquareInchPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 ksi/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareInchPerMinute, KilopoundsForcePerSquareInchPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 kipf/in²/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareInchPerMinute, KilopoundsForcePerSquareInchPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 ksi/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareInchPerSecond, KilopoundsForcePerSquareInchPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 kipf/in²/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareInchPerSecond, KilopoundsForcePerSquareInchPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 ksi/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareInchPerSecond, KilopoundsForcePerSquareInchPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 kipf/in²/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareInchPerSecond, KilopoundsForcePerSquareInchPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 MPa/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegapascalsPerMinute, MegapascalsPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.MegapascalPerMinute, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 МПа/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegapascalsPerMinute, MegapascalsPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.MegapascalPerMinute, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 MPa/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegapascalsPerSecond, MegapascalsPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.MegapascalPerSecond, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 МПа/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegapascalsPerSecond, MegapascalsPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.MegapascalPerSecond, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 Mpsi/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegapoundsForcePerSquareInchPerMinute, MegapoundsForcePerSquareInchPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 Mlb/in²/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegapoundsForcePerSquareInchPerMinute, MegapoundsForcePerSquareInchPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 Мpsi/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegapoundsForcePerSquareInchPerMinute, MegapoundsForcePerSquareInchPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 Мlb/in²/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegapoundsForcePerSquareInchPerMinute, MegapoundsForcePerSquareInchPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 Mpsi/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegapoundsForcePerSquareInchPerSecond, MegapoundsForcePerSquareInchPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 Mlb/in²/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegapoundsForcePerSquareInchPerSecond, MegapoundsForcePerSquareInchPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 Мpsi/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegapoundsForcePerSquareInchPerSecond, MegapoundsForcePerSquareInchPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 Мlb/in²/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegapoundsForcePerSquareInchPerSecond, MegapoundsForcePerSquareInchPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 mbar/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillibarsPerMinute, MillibarsPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.MillibarPerMinute, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 мбар/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillibarsPerMinute, MillibarsPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.MillibarPerMinute, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 mbar/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillibarsPerSecond, MillibarsPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.MillibarPerSecond, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 мбар/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillibarsPerSecond, MillibarsPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.MillibarPerSecond, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 mmHg/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimetersOfMercuryPerSecond, MillimetersOfMercuryPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.MillimeterOfMercuryPerSecond, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 mmHg/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimetersOfMercuryPerSecond, MillimetersOfMercuryPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.MillimeterOfMercuryPerSecond, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 Pa/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PascalsPerMinute, PascalsPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.PascalPerMinute, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 Па/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PascalsPerMinute, PascalsPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.PascalPerMinute, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 Pa/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PascalsPerSecond, PascalsPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.PascalPerSecond, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 Па/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PascalsPerSecond, PascalsPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.PascalPerSecond, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 psi/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareInchPerMinute, PoundsForcePerSquareInchPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 lb/in²/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareInchPerMinute, PoundsForcePerSquareInchPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 psi/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareInchPerMinute, PoundsForcePerSquareInchPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 lb/in²/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareInchPerMinute, PoundsForcePerSquareInchPerMinuteTolerance); - Assert.Equal(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 psi/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareInchPerSecond, PoundsForcePerSquareInchPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 lb/in²/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareInchPerSecond, PoundsForcePerSquareInchPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 psi/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareInchPerSecond, PoundsForcePerSquareInchPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, parsed.Unit); - } - - { - Assert.True(PressureChangeRate.TryParse("1 lb/in²/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareInchPerSecond, PoundsForcePerSquareInchPerSecondTolerance); - Assert.Equal(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(PressureChangeRate.TryParse(quantityString, out PressureChangeRate parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -1425,6 +923,62 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Pressu Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", PressureChangeRateUnit.AtmospherePerSecond, "atm/s")] + [InlineData("en-US", PressureChangeRateUnit.BarPerMinute, "bar/min")] + [InlineData("en-US", PressureChangeRateUnit.BarPerSecond, "bar/s")] + [InlineData("en-US", PressureChangeRateUnit.KilopascalPerMinute, "kPa/min")] + [InlineData("en-US", PressureChangeRateUnit.KilopascalPerSecond, "kPa/s")] + [InlineData("en-US", PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, "ksi/min")] + [InlineData("en-US", PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, "ksi/s")] + [InlineData("en-US", PressureChangeRateUnit.MegapascalPerMinute, "MPa/min")] + [InlineData("en-US", PressureChangeRateUnit.MegapascalPerSecond, "MPa/s")] + [InlineData("en-US", PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, "Mpsi/min")] + [InlineData("en-US", PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, "Mpsi/s")] + [InlineData("en-US", PressureChangeRateUnit.MillibarPerMinute, "mbar/min")] + [InlineData("en-US", PressureChangeRateUnit.MillibarPerSecond, "mbar/s")] + [InlineData("en-US", PressureChangeRateUnit.MillimeterOfMercuryPerSecond, "mmHg/s")] + [InlineData("en-US", PressureChangeRateUnit.PascalPerMinute, "Pa/min")] + [InlineData("en-US", PressureChangeRateUnit.PascalPerSecond, "Pa/s")] + [InlineData("en-US", PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, "psi/min")] + [InlineData("en-US", PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, "psi/s")] + [InlineData("ru-RU", PressureChangeRateUnit.AtmospherePerSecond, "атм/с")] + [InlineData("ru-RU", PressureChangeRateUnit.BarPerMinute, "бар/мин")] + [InlineData("ru-RU", PressureChangeRateUnit.BarPerSecond, "бар/с")] + [InlineData("ru-RU", PressureChangeRateUnit.KilopascalPerMinute, "кПа/мин")] + [InlineData("ru-RU", PressureChangeRateUnit.KilopascalPerSecond, "кПа/с")] + [InlineData("ru-RU", PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, "ksi/мин")] + [InlineData("ru-RU", PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, "ksi/с")] + [InlineData("ru-RU", PressureChangeRateUnit.MegapascalPerMinute, "МПа/мин")] + [InlineData("ru-RU", PressureChangeRateUnit.MegapascalPerSecond, "МПа/с")] + [InlineData("ru-RU", PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, "Мpsi/мин")] + [InlineData("ru-RU", PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, "Мpsi/с")] + [InlineData("ru-RU", PressureChangeRateUnit.MillibarPerMinute, "мбар/мин")] + [InlineData("ru-RU", PressureChangeRateUnit.MillibarPerSecond, "мбар/с")] + [InlineData("ru-RU", PressureChangeRateUnit.MillimeterOfMercuryPerSecond, "mmHg/с")] + [InlineData("ru-RU", PressureChangeRateUnit.PascalPerMinute, "Па/мин")] + [InlineData("ru-RU", PressureChangeRateUnit.PascalPerSecond, "Па/с")] + [InlineData("ru-RU", PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, "psi/мин")] + [InlineData("ru-RU", PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, "psi/с")] + public void GetAbbreviationForCulture(string culture, PressureChangeRateUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = PressureChangeRate.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(PressureChangeRate.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = PressureChangeRate.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(PressureChangeRateUnit unit) @@ -1455,6 +1009,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); }); } @@ -1478,49 +1033,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] @@ -1566,8 +1123,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); @@ -1604,23 +1159,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = PressureChangeRate.FromPascalsPerSecond(1); - Assert.True(v.Equals(PressureChangeRate.FromPascalsPerSecond(1), PascalsPerSecondTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(PressureChangeRate.Zero, PascalsPerSecondTolerance, ComparisonType.Relative)); - Assert.True(PressureChangeRate.FromPascalsPerSecond(100).Equals(PressureChangeRate.FromPascalsPerSecond(120), 0.3, ComparisonType.Relative)); - Assert.False(PressureChangeRate.FromPascalsPerSecond(100).Equals(PressureChangeRate.FromPascalsPerSecond(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = PressureChangeRate.FromPascalsPerSecond(1); - Assert.Throws(() => v.Equals(PressureChangeRate.FromPascalsPerSecond(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1635,6 +1173,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(pascalpersecond.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = PressureChangeRate.FromPascalsPerSecond(1); + var negativeTolerance = PressureChangeRate.FromPascalsPerSecond(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1651,6 +1215,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() { @@ -1743,158 +1319,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(PressureChangeRate))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(PressureChangeRateUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal(PressureChangeRate.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal(PressureChangeRate.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal(new {PressureChangeRate.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 3d8ebec915..369d666549 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PressureTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PressureTestsBase.g.cs @@ -280,7 +280,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Pressure(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -293,15 +293,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Pressure_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + PressureUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Pressure(1, PressureUnit.Pascal); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Pressure.Zero, quantityInfo.Zero); Assert.Equal("Pressure", quantityInfo.Name); + Assert.Equal(Pressure.Zero, quantityInfo.Zero); + Assert.Equal(Pressure.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Pressure.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void PressureInfo_CreateWithCustomUnitInfos() + { + PressureUnit[] expectedUnits = [PressureUnit.Pascal]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -361,191 +379,191 @@ public void PascalToPressureUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Pressure.From(1, PressureUnit.Atmosphere); - AssertEx.EqualTolerance(1, quantity00.Atmospheres, AtmospheresTolerance); + Assert.Equal(1, quantity00.Atmospheres); Assert.Equal(PressureUnit.Atmosphere, quantity00.Unit); var quantity01 = Pressure.From(1, PressureUnit.Bar); - AssertEx.EqualTolerance(1, quantity01.Bars, BarsTolerance); + Assert.Equal(1, quantity01.Bars); Assert.Equal(PressureUnit.Bar, quantity01.Unit); var quantity02 = Pressure.From(1, PressureUnit.Centibar); - AssertEx.EqualTolerance(1, quantity02.Centibars, CentibarsTolerance); + Assert.Equal(1, quantity02.Centibars); Assert.Equal(PressureUnit.Centibar, quantity02.Unit); var quantity03 = Pressure.From(1, PressureUnit.CentimeterOfWaterColumn); - AssertEx.EqualTolerance(1, quantity03.CentimetersOfWaterColumn, CentimetersOfWaterColumnTolerance); + Assert.Equal(1, quantity03.CentimetersOfWaterColumn); Assert.Equal(PressureUnit.CentimeterOfWaterColumn, quantity03.Unit); var quantity04 = Pressure.From(1, PressureUnit.Decapascal); - AssertEx.EqualTolerance(1, quantity04.Decapascals, DecapascalsTolerance); + Assert.Equal(1, quantity04.Decapascals); Assert.Equal(PressureUnit.Decapascal, quantity04.Unit); var quantity05 = Pressure.From(1, PressureUnit.Decibar); - AssertEx.EqualTolerance(1, quantity05.Decibars, DecibarsTolerance); + Assert.Equal(1, quantity05.Decibars); Assert.Equal(PressureUnit.Decibar, quantity05.Unit); var quantity06 = Pressure.From(1, PressureUnit.DynePerSquareCentimeter); - AssertEx.EqualTolerance(1, quantity06.DynesPerSquareCentimeter, DynesPerSquareCentimeterTolerance); + Assert.Equal(1, quantity06.DynesPerSquareCentimeter); Assert.Equal(PressureUnit.DynePerSquareCentimeter, quantity06.Unit); var quantity07 = Pressure.From(1, PressureUnit.FootOfHead); - AssertEx.EqualTolerance(1, quantity07.FeetOfHead, FeetOfHeadTolerance); + Assert.Equal(1, quantity07.FeetOfHead); Assert.Equal(PressureUnit.FootOfHead, quantity07.Unit); var quantity08 = Pressure.From(1, PressureUnit.Gigapascal); - AssertEx.EqualTolerance(1, quantity08.Gigapascals, GigapascalsTolerance); + Assert.Equal(1, quantity08.Gigapascals); Assert.Equal(PressureUnit.Gigapascal, quantity08.Unit); var quantity09 = Pressure.From(1, PressureUnit.Hectopascal); - AssertEx.EqualTolerance(1, quantity09.Hectopascals, HectopascalsTolerance); + Assert.Equal(1, quantity09.Hectopascals); Assert.Equal(PressureUnit.Hectopascal, quantity09.Unit); var quantity10 = Pressure.From(1, PressureUnit.InchOfMercury); - AssertEx.EqualTolerance(1, quantity10.InchesOfMercury, InchesOfMercuryTolerance); + Assert.Equal(1, quantity10.InchesOfMercury); Assert.Equal(PressureUnit.InchOfMercury, quantity10.Unit); var quantity11 = Pressure.From(1, PressureUnit.InchOfWaterColumn); - AssertEx.EqualTolerance(1, quantity11.InchesOfWaterColumn, InchesOfWaterColumnTolerance); + Assert.Equal(1, quantity11.InchesOfWaterColumn); Assert.Equal(PressureUnit.InchOfWaterColumn, quantity11.Unit); var quantity12 = Pressure.From(1, PressureUnit.Kilobar); - AssertEx.EqualTolerance(1, quantity12.Kilobars, KilobarsTolerance); + Assert.Equal(1, quantity12.Kilobars); Assert.Equal(PressureUnit.Kilobar, quantity12.Unit); var quantity13 = Pressure.From(1, PressureUnit.KilogramForcePerSquareCentimeter); - AssertEx.EqualTolerance(1, quantity13.KilogramsForcePerSquareCentimeter, KilogramsForcePerSquareCentimeterTolerance); + Assert.Equal(1, quantity13.KilogramsForcePerSquareCentimeter); Assert.Equal(PressureUnit.KilogramForcePerSquareCentimeter, quantity13.Unit); var quantity14 = Pressure.From(1, PressureUnit.KilogramForcePerSquareMeter); - AssertEx.EqualTolerance(1, quantity14.KilogramsForcePerSquareMeter, KilogramsForcePerSquareMeterTolerance); + Assert.Equal(1, quantity14.KilogramsForcePerSquareMeter); Assert.Equal(PressureUnit.KilogramForcePerSquareMeter, quantity14.Unit); var quantity15 = Pressure.From(1, PressureUnit.KilogramForcePerSquareMillimeter); - AssertEx.EqualTolerance(1, quantity15.KilogramsForcePerSquareMillimeter, KilogramsForcePerSquareMillimeterTolerance); + Assert.Equal(1, quantity15.KilogramsForcePerSquareMillimeter); Assert.Equal(PressureUnit.KilogramForcePerSquareMillimeter, quantity15.Unit); var quantity16 = Pressure.From(1, PressureUnit.KilonewtonPerSquareCentimeter); - AssertEx.EqualTolerance(1, quantity16.KilonewtonsPerSquareCentimeter, KilonewtonsPerSquareCentimeterTolerance); + Assert.Equal(1, quantity16.KilonewtonsPerSquareCentimeter); Assert.Equal(PressureUnit.KilonewtonPerSquareCentimeter, quantity16.Unit); var quantity17 = Pressure.From(1, PressureUnit.KilonewtonPerSquareMeter); - AssertEx.EqualTolerance(1, quantity17.KilonewtonsPerSquareMeter, KilonewtonsPerSquareMeterTolerance); + Assert.Equal(1, quantity17.KilonewtonsPerSquareMeter); Assert.Equal(PressureUnit.KilonewtonPerSquareMeter, quantity17.Unit); var quantity18 = Pressure.From(1, PressureUnit.KilonewtonPerSquareMillimeter); - AssertEx.EqualTolerance(1, quantity18.KilonewtonsPerSquareMillimeter, KilonewtonsPerSquareMillimeterTolerance); + Assert.Equal(1, quantity18.KilonewtonsPerSquareMillimeter); Assert.Equal(PressureUnit.KilonewtonPerSquareMillimeter, quantity18.Unit); var quantity19 = Pressure.From(1, PressureUnit.Kilopascal); - AssertEx.EqualTolerance(1, quantity19.Kilopascals, KilopascalsTolerance); + Assert.Equal(1, quantity19.Kilopascals); Assert.Equal(PressureUnit.Kilopascal, quantity19.Unit); var quantity20 = Pressure.From(1, PressureUnit.KilopoundForcePerSquareFoot); - AssertEx.EqualTolerance(1, quantity20.KilopoundsForcePerSquareFoot, KilopoundsForcePerSquareFootTolerance); + Assert.Equal(1, quantity20.KilopoundsForcePerSquareFoot); Assert.Equal(PressureUnit.KilopoundForcePerSquareFoot, quantity20.Unit); var quantity21 = Pressure.From(1, PressureUnit.KilopoundForcePerSquareInch); - AssertEx.EqualTolerance(1, quantity21.KilopoundsForcePerSquareInch, KilopoundsForcePerSquareInchTolerance); + Assert.Equal(1, quantity21.KilopoundsForcePerSquareInch); Assert.Equal(PressureUnit.KilopoundForcePerSquareInch, quantity21.Unit); var quantity22 = Pressure.From(1, PressureUnit.KilopoundForcePerSquareMil); - AssertEx.EqualTolerance(1, quantity22.KilopoundsForcePerSquareMil, KilopoundsForcePerSquareMilTolerance); + Assert.Equal(1, quantity22.KilopoundsForcePerSquareMil); Assert.Equal(PressureUnit.KilopoundForcePerSquareMil, quantity22.Unit); var quantity23 = Pressure.From(1, PressureUnit.Megabar); - AssertEx.EqualTolerance(1, quantity23.Megabars, MegabarsTolerance); + Assert.Equal(1, quantity23.Megabars); Assert.Equal(PressureUnit.Megabar, quantity23.Unit); var quantity24 = Pressure.From(1, PressureUnit.MeganewtonPerSquareMeter); - AssertEx.EqualTolerance(1, quantity24.MeganewtonsPerSquareMeter, MeganewtonsPerSquareMeterTolerance); + Assert.Equal(1, quantity24.MeganewtonsPerSquareMeter); Assert.Equal(PressureUnit.MeganewtonPerSquareMeter, quantity24.Unit); var quantity25 = Pressure.From(1, PressureUnit.Megapascal); - AssertEx.EqualTolerance(1, quantity25.Megapascals, MegapascalsTolerance); + Assert.Equal(1, quantity25.Megapascals); Assert.Equal(PressureUnit.Megapascal, quantity25.Unit); var quantity26 = Pressure.From(1, PressureUnit.MeterOfHead); - AssertEx.EqualTolerance(1, quantity26.MetersOfHead, MetersOfHeadTolerance); + Assert.Equal(1, quantity26.MetersOfHead); Assert.Equal(PressureUnit.MeterOfHead, quantity26.Unit); var quantity27 = Pressure.From(1, PressureUnit.MeterOfWaterColumn); - AssertEx.EqualTolerance(1, quantity27.MetersOfWaterColumn, MetersOfWaterColumnTolerance); + Assert.Equal(1, quantity27.MetersOfWaterColumn); Assert.Equal(PressureUnit.MeterOfWaterColumn, quantity27.Unit); var quantity28 = Pressure.From(1, PressureUnit.Microbar); - AssertEx.EqualTolerance(1, quantity28.Microbars, MicrobarsTolerance); + Assert.Equal(1, quantity28.Microbars); Assert.Equal(PressureUnit.Microbar, quantity28.Unit); var quantity29 = Pressure.From(1, PressureUnit.Micropascal); - AssertEx.EqualTolerance(1, quantity29.Micropascals, MicropascalsTolerance); + Assert.Equal(1, quantity29.Micropascals); Assert.Equal(PressureUnit.Micropascal, quantity29.Unit); var quantity30 = Pressure.From(1, PressureUnit.Millibar); - AssertEx.EqualTolerance(1, quantity30.Millibars, MillibarsTolerance); + Assert.Equal(1, quantity30.Millibars); Assert.Equal(PressureUnit.Millibar, quantity30.Unit); var quantity31 = Pressure.From(1, PressureUnit.MillimeterOfMercury); - AssertEx.EqualTolerance(1, quantity31.MillimetersOfMercury, MillimetersOfMercuryTolerance); + Assert.Equal(1, quantity31.MillimetersOfMercury); Assert.Equal(PressureUnit.MillimeterOfMercury, quantity31.Unit); var quantity32 = Pressure.From(1, PressureUnit.MillimeterOfWaterColumn); - AssertEx.EqualTolerance(1, quantity32.MillimetersOfWaterColumn, MillimetersOfWaterColumnTolerance); + Assert.Equal(1, quantity32.MillimetersOfWaterColumn); Assert.Equal(PressureUnit.MillimeterOfWaterColumn, quantity32.Unit); var quantity33 = Pressure.From(1, PressureUnit.Millipascal); - AssertEx.EqualTolerance(1, quantity33.Millipascals, MillipascalsTolerance); + Assert.Equal(1, quantity33.Millipascals); Assert.Equal(PressureUnit.Millipascal, quantity33.Unit); var quantity34 = Pressure.From(1, PressureUnit.NewtonPerSquareCentimeter); - AssertEx.EqualTolerance(1, quantity34.NewtonsPerSquareCentimeter, NewtonsPerSquareCentimeterTolerance); + Assert.Equal(1, quantity34.NewtonsPerSquareCentimeter); Assert.Equal(PressureUnit.NewtonPerSquareCentimeter, quantity34.Unit); var quantity35 = Pressure.From(1, PressureUnit.NewtonPerSquareMeter); - AssertEx.EqualTolerance(1, quantity35.NewtonsPerSquareMeter, NewtonsPerSquareMeterTolerance); + Assert.Equal(1, quantity35.NewtonsPerSquareMeter); Assert.Equal(PressureUnit.NewtonPerSquareMeter, quantity35.Unit); var quantity36 = Pressure.From(1, PressureUnit.NewtonPerSquareMillimeter); - AssertEx.EqualTolerance(1, quantity36.NewtonsPerSquareMillimeter, NewtonsPerSquareMillimeterTolerance); + Assert.Equal(1, quantity36.NewtonsPerSquareMillimeter); Assert.Equal(PressureUnit.NewtonPerSquareMillimeter, quantity36.Unit); var quantity37 = Pressure.From(1, PressureUnit.Pascal); - AssertEx.EqualTolerance(1, quantity37.Pascals, PascalsTolerance); + Assert.Equal(1, quantity37.Pascals); Assert.Equal(PressureUnit.Pascal, quantity37.Unit); var quantity38 = Pressure.From(1, PressureUnit.PoundForcePerSquareFoot); - AssertEx.EqualTolerance(1, quantity38.PoundsForcePerSquareFoot, PoundsForcePerSquareFootTolerance); + Assert.Equal(1, quantity38.PoundsForcePerSquareFoot); Assert.Equal(PressureUnit.PoundForcePerSquareFoot, quantity38.Unit); var quantity39 = Pressure.From(1, PressureUnit.PoundForcePerSquareInch); - AssertEx.EqualTolerance(1, quantity39.PoundsForcePerSquareInch, PoundsForcePerSquareInchTolerance); + Assert.Equal(1, quantity39.PoundsForcePerSquareInch); Assert.Equal(PressureUnit.PoundForcePerSquareInch, quantity39.Unit); var quantity40 = Pressure.From(1, PressureUnit.PoundForcePerSquareMil); - AssertEx.EqualTolerance(1, quantity40.PoundsForcePerSquareMil, PoundsForcePerSquareMilTolerance); + Assert.Equal(1, quantity40.PoundsForcePerSquareMil); Assert.Equal(PressureUnit.PoundForcePerSquareMil, quantity40.Unit); var quantity41 = Pressure.From(1, PressureUnit.PoundPerInchSecondSquared); - AssertEx.EqualTolerance(1, quantity41.PoundsPerInchSecondSquared, PoundsPerInchSecondSquaredTolerance); + Assert.Equal(1, quantity41.PoundsPerInchSecondSquared); Assert.Equal(PressureUnit.PoundPerInchSecondSquared, quantity41.Unit); var quantity42 = Pressure.From(1, PressureUnit.TechnicalAtmosphere); - AssertEx.EqualTolerance(1, quantity42.TechnicalAtmospheres, TechnicalAtmospheresTolerance); + Assert.Equal(1, quantity42.TechnicalAtmospheres); Assert.Equal(PressureUnit.TechnicalAtmosphere, quantity42.Unit); var quantity43 = Pressure.From(1, PressureUnit.TonneForcePerSquareCentimeter); - AssertEx.EqualTolerance(1, quantity43.TonnesForcePerSquareCentimeter, TonnesForcePerSquareCentimeterTolerance); + Assert.Equal(1, quantity43.TonnesForcePerSquareCentimeter); Assert.Equal(PressureUnit.TonneForcePerSquareCentimeter, quantity43.Unit); var quantity44 = Pressure.From(1, PressureUnit.TonneForcePerSquareMeter); - AssertEx.EqualTolerance(1, quantity44.TonnesForcePerSquareMeter, TonnesForcePerSquareMeterTolerance); + Assert.Equal(1, quantity44.TonnesForcePerSquareMeter); Assert.Equal(PressureUnit.TonneForcePerSquareMeter, quantity44.Unit); var quantity45 = Pressure.From(1, PressureUnit.TonneForcePerSquareMillimeter); - AssertEx.EqualTolerance(1, quantity45.TonnesForcePerSquareMillimeter, TonnesForcePerSquareMillimeterTolerance); + Assert.Equal(1, quantity45.TonnesForcePerSquareMillimeter); Assert.Equal(PressureUnit.TonneForcePerSquareMillimeter, quantity45.Unit); var quantity46 = Pressure.From(1, PressureUnit.Torr); - AssertEx.EqualTolerance(1, quantity46.Torrs, TorrsTolerance); + Assert.Equal(1, quantity46.Torrs); Assert.Equal(PressureUnit.Torr, quantity46.Unit); } @@ -628,1288 +646,311 @@ public virtual void BaseUnit_HasSIBase() Assert.True(baseUnitInfo.BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } - [Fact] - public virtual void As_UnitSystem_SI_ReturnsQuantityInSIUnits() - { - var quantity = new Pressure(value: 1, unit: Pressure.BaseUnit); - var expectedValue = quantity.As(Pressure.Info.GetDefaultUnit(UnitSystem.SI)); - - var convertedValue = quantity.As(UnitSystem.SI); - - Assert.Equal(expectedValue, convertedValue); - } - - [Fact] - public void As_UnitSystem_ThrowsArgumentNullExceptionIfNull() - { - var quantity = new Pressure(value: 1, unit: Pressure.BaseUnit); - UnitSystem nullUnitSystem = null!; - Assert.Throws(() => quantity.As(nullUnitSystem)); - } - - [Fact] - public void As_UnitSystem_ThrowsArgumentExceptionIfNotSupported() - { - var quantity = new Pressure(value: 1, unit: Pressure.BaseUnit); - var unsupportedUnitSystem = new UnitSystem(UnsupportedBaseUnits); - Assert.Throws(() => quantity.As(unsupportedUnitSystem)); - } - - [Fact] - public virtual void ToUnit_UnitSystem_SI_ReturnsQuantityInSIUnits() - { - var quantity = new Pressure(value: 1, unit: Pressure.BaseUnit); - var expectedUnit = Pressure.Info.GetDefaultUnit(UnitSystem.SI); - var expectedValue = quantity.As(expectedUnit); - - Assert.Multiple(() => - { - Pressure quantityToConvert = quantity; - - Pressure convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); - - Assert.Equal(expectedUnit, convertedQuantity.Unit); - Assert.Equal(expectedValue, convertedQuantity.Value); - }, () => - { - IQuantity quantityToConvert = quantity; - - IQuantity convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); - - Assert.Equal(expectedUnit, convertedQuantity.Unit); - Assert.Equal(expectedValue, convertedQuantity.Value); - }, () => - { - IQuantity quantityToConvert = quantity; - - IQuantity convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); - - Assert.Equal(expectedUnit, convertedQuantity.Unit); - Assert.Equal(expectedValue, convertedQuantity.Value); - }); - } - - [Fact] - public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() - { - UnitSystem nullUnitSystem = null!; - Assert.Multiple(() => - { - var quantity = new Pressure(value: 1, unit: Pressure.BaseUnit); - Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); - }, () => - { - IQuantity quantity = new Pressure(value: 1, unit: Pressure.BaseUnit); - Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); - }, () => - { - IQuantity quantity = new Pressure(value: 1, unit: Pressure.BaseUnit); - Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); - }); - } - - [Fact] - public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() - { - var unsupportedUnitSystem = new UnitSystem(UnsupportedBaseUnits); - Assert.Multiple(() => - { - var quantity = new Pressure(value: 1, unit: Pressure.BaseUnit); - Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); - }, () => - { - IQuantity quantity = new Pressure(value: 1, unit: Pressure.BaseUnit); - Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); - }, () => - { - IQuantity quantity = new Pressure(value: 1, unit: Pressure.BaseUnit); - Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); - }); - } - - [Fact] - public void Parse() - { - try - { - var parsed = Pressure.Parse("1 atm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Atmospheres, AtmospheresTolerance); - Assert.Equal(PressureUnit.Atmosphere, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 атм", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Atmospheres, AtmospheresTolerance); - Assert.Equal(PressureUnit.Atmosphere, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 bar", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Bars, BarsTolerance); - Assert.Equal(PressureUnit.Bar, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 бар", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Bars, BarsTolerance); - Assert.Equal(PressureUnit.Bar, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 cbar", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Centibars, CentibarsTolerance); - Assert.Equal(PressureUnit.Centibar, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 сбар", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Centibars, CentibarsTolerance); - Assert.Equal(PressureUnit.Centibar, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 cmH₂O", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentimetersOfWaterColumn, CentimetersOfWaterColumnTolerance); - Assert.Equal(PressureUnit.CentimeterOfWaterColumn, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 cmH2O", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentimetersOfWaterColumn, CentimetersOfWaterColumnTolerance); - Assert.Equal(PressureUnit.CentimeterOfWaterColumn, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 cm wc", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentimetersOfWaterColumn, CentimetersOfWaterColumnTolerance); - Assert.Equal(PressureUnit.CentimeterOfWaterColumn, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 cm wg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentimetersOfWaterColumn, CentimetersOfWaterColumnTolerance); - Assert.Equal(PressureUnit.CentimeterOfWaterColumn, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 daPa", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Decapascals, DecapascalsTolerance); - Assert.Equal(PressureUnit.Decapascal, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 даПа", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Decapascals, DecapascalsTolerance); - Assert.Equal(PressureUnit.Decapascal, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 dbar", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Decibars, DecibarsTolerance); - Assert.Equal(PressureUnit.Decibar, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 дбар", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Decibars, DecibarsTolerance); - Assert.Equal(PressureUnit.Decibar, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 dyn/cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DynesPerSquareCentimeter, DynesPerSquareCentimeterTolerance); - Assert.Equal(PressureUnit.DynePerSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 ft of head", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.FeetOfHead, FeetOfHeadTolerance); - Assert.Equal(PressureUnit.FootOfHead, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 GPa", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Gigapascals, GigapascalsTolerance); - Assert.Equal(PressureUnit.Gigapascal, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 ГПа", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Gigapascals, GigapascalsTolerance); - Assert.Equal(PressureUnit.Gigapascal, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 hPa", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Hectopascals, HectopascalsTolerance); - Assert.Equal(PressureUnit.Hectopascal, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 гПа", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Hectopascals, HectopascalsTolerance); - Assert.Equal(PressureUnit.Hectopascal, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 inHg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InchesOfMercury, InchesOfMercuryTolerance); - Assert.Equal(PressureUnit.InchOfMercury, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 inH2O", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InchesOfWaterColumn, InchesOfWaterColumnTolerance); - Assert.Equal(PressureUnit.InchOfWaterColumn, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 inch wc", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InchesOfWaterColumn, InchesOfWaterColumnTolerance); - Assert.Equal(PressureUnit.InchOfWaterColumn, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 wc", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InchesOfWaterColumn, InchesOfWaterColumnTolerance); - Assert.Equal(PressureUnit.InchOfWaterColumn, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 kbar", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilobars, KilobarsTolerance); - Assert.Equal(PressureUnit.Kilobar, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 кбар", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Kilobars, KilobarsTolerance); - Assert.Equal(PressureUnit.Kilobar, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 kgf/cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerSquareCentimeter, KilogramsForcePerSquareCentimeterTolerance); - Assert.Equal(PressureUnit.KilogramForcePerSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 кгс/см²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerSquareCentimeter, KilogramsForcePerSquareCentimeterTolerance); - Assert.Equal(PressureUnit.KilogramForcePerSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 kgf/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerSquareMeter, KilogramsForcePerSquareMeterTolerance); - Assert.Equal(PressureUnit.KilogramForcePerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 кгс/м²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerSquareMeter, KilogramsForcePerSquareMeterTolerance); - Assert.Equal(PressureUnit.KilogramForcePerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 kgf/mm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerSquareMillimeter, KilogramsForcePerSquareMillimeterTolerance); - Assert.Equal(PressureUnit.KilogramForcePerSquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 кгс/мм²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerSquareMillimeter, KilogramsForcePerSquareMillimeterTolerance); - Assert.Equal(PressureUnit.KilogramForcePerSquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 kN/cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerSquareCentimeter, KilonewtonsPerSquareCentimeterTolerance); - Assert.Equal(PressureUnit.KilonewtonPerSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 кН/см²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerSquareCentimeter, KilonewtonsPerSquareCentimeterTolerance); - Assert.Equal(PressureUnit.KilonewtonPerSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 kN/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerSquareMeter, KilonewtonsPerSquareMeterTolerance); - Assert.Equal(PressureUnit.KilonewtonPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 кН/м²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerSquareMeter, KilonewtonsPerSquareMeterTolerance); - Assert.Equal(PressureUnit.KilonewtonPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 kN/mm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerSquareMillimeter, KilonewtonsPerSquareMillimeterTolerance); - Assert.Equal(PressureUnit.KilonewtonPerSquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 кН/мм²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerSquareMillimeter, KilonewtonsPerSquareMillimeterTolerance); - Assert.Equal(PressureUnit.KilonewtonPerSquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 kPa", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilopascals, KilopascalsTolerance); - Assert.Equal(PressureUnit.Kilopascal, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 кПа", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Kilopascals, KilopascalsTolerance); - Assert.Equal(PressureUnit.Kilopascal, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 kipf/ft²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareFoot, KilopoundsForcePerSquareFootTolerance); - Assert.Equal(PressureUnit.KilopoundForcePerSquareFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 ksi", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareInch, KilopoundsForcePerSquareInchTolerance); - Assert.Equal(PressureUnit.KilopoundForcePerSquareInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 kipf/in²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareInch, KilopoundsForcePerSquareInchTolerance); - Assert.Equal(PressureUnit.KilopoundForcePerSquareInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 ksi", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareInch, KilopoundsForcePerSquareInchTolerance); - Assert.Equal(PressureUnit.KilopoundForcePerSquareInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 kipf/in²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareInch, KilopoundsForcePerSquareInchTolerance); - Assert.Equal(PressureUnit.KilopoundForcePerSquareInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 kipf/mil²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareMil, KilopoundsForcePerSquareMilTolerance); - Assert.Equal(PressureUnit.KilopoundForcePerSquareMil, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 Mbar", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megabars, MegabarsTolerance); - Assert.Equal(PressureUnit.Megabar, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 Мбар", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Megabars, MegabarsTolerance); - Assert.Equal(PressureUnit.Megabar, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 MN/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MeganewtonsPerSquareMeter, MeganewtonsPerSquareMeterTolerance); - Assert.Equal(PressureUnit.MeganewtonPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 МН/м²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MeganewtonsPerSquareMeter, MeganewtonsPerSquareMeterTolerance); - Assert.Equal(PressureUnit.MeganewtonPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 MPa", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megapascals, MegapascalsTolerance); - Assert.Equal(PressureUnit.Megapascal, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 МПа", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Megapascals, MegapascalsTolerance); - Assert.Equal(PressureUnit.Megapascal, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 m of head", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MetersOfHead, MetersOfHeadTolerance); - Assert.Equal(PressureUnit.MeterOfHead, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 mH₂O", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MetersOfWaterColumn, MetersOfWaterColumnTolerance); - Assert.Equal(PressureUnit.MeterOfWaterColumn, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 mH2O", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MetersOfWaterColumn, MetersOfWaterColumnTolerance); - Assert.Equal(PressureUnit.MeterOfWaterColumn, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 m wc", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MetersOfWaterColumn, MetersOfWaterColumnTolerance); - Assert.Equal(PressureUnit.MeterOfWaterColumn, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 m wg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MetersOfWaterColumn, MetersOfWaterColumnTolerance); - Assert.Equal(PressureUnit.MeterOfWaterColumn, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 µbar", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microbars, MicrobarsTolerance); - Assert.Equal(PressureUnit.Microbar, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 мкбар", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Microbars, MicrobarsTolerance); - Assert.Equal(PressureUnit.Microbar, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 µPa", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Micropascals, MicropascalsTolerance); - Assert.Equal(PressureUnit.Micropascal, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 мкПа", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Micropascals, MicropascalsTolerance); - Assert.Equal(PressureUnit.Micropascal, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 mbar", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millibars, MillibarsTolerance); - Assert.Equal(PressureUnit.Millibar, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 мбар", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Millibars, MillibarsTolerance); - Assert.Equal(PressureUnit.Millibar, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 mmHg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillimetersOfMercury, MillimetersOfMercuryTolerance); - Assert.Equal(PressureUnit.MillimeterOfMercury, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 мм рт.ст.", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MillimetersOfMercury, MillimetersOfMercuryTolerance); - Assert.Equal(PressureUnit.MillimeterOfMercury, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 mmH₂O", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillimetersOfWaterColumn, MillimetersOfWaterColumnTolerance); - Assert.Equal(PressureUnit.MillimeterOfWaterColumn, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 mmH2O", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillimetersOfWaterColumn, MillimetersOfWaterColumnTolerance); - Assert.Equal(PressureUnit.MillimeterOfWaterColumn, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 mm wc", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillimetersOfWaterColumn, MillimetersOfWaterColumnTolerance); - Assert.Equal(PressureUnit.MillimeterOfWaterColumn, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 mm wg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillimetersOfWaterColumn, MillimetersOfWaterColumnTolerance); - Assert.Equal(PressureUnit.MillimeterOfWaterColumn, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 mPa", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millipascals, MillipascalsTolerance); - Assert.Equal(PressureUnit.Millipascal, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 мПа", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Millipascals, MillipascalsTolerance); - Assert.Equal(PressureUnit.Millipascal, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 N/cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonsPerSquareCentimeter, NewtonsPerSquareCentimeterTolerance); - Assert.Equal(PressureUnit.NewtonPerSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 Н/см²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.NewtonsPerSquareCentimeter, NewtonsPerSquareCentimeterTolerance); - Assert.Equal(PressureUnit.NewtonPerSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 N/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonsPerSquareMeter, NewtonsPerSquareMeterTolerance); - Assert.Equal(PressureUnit.NewtonPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 Н/м²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.NewtonsPerSquareMeter, NewtonsPerSquareMeterTolerance); - Assert.Equal(PressureUnit.NewtonPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 N/mm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonsPerSquareMillimeter, NewtonsPerSquareMillimeterTolerance); - Assert.Equal(PressureUnit.NewtonPerSquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 Н/мм²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.NewtonsPerSquareMillimeter, NewtonsPerSquareMillimeterTolerance); - Assert.Equal(PressureUnit.NewtonPerSquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 Pa", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Pascals, PascalsTolerance); - Assert.Equal(PressureUnit.Pascal, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 Па", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Pascals, PascalsTolerance); - Assert.Equal(PressureUnit.Pascal, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 lb/ft²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareFoot, PoundsForcePerSquareFootTolerance); - Assert.Equal(PressureUnit.PoundForcePerSquareFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 psi", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareInch, PoundsForcePerSquareInchTolerance); - Assert.Equal(PressureUnit.PoundForcePerSquareInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 lb/in²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareInch, PoundsForcePerSquareInchTolerance); - Assert.Equal(PressureUnit.PoundForcePerSquareInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 psi", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareInch, PoundsForcePerSquareInchTolerance); - Assert.Equal(PressureUnit.PoundForcePerSquareInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 lb/in²", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareInch, PoundsForcePerSquareInchTolerance); - Assert.Equal(PressureUnit.PoundForcePerSquareInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 lb/mil²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareMil, PoundsForcePerSquareMilTolerance); - Assert.Equal(PressureUnit.PoundForcePerSquareMil, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 lbs/mil²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareMil, PoundsForcePerSquareMilTolerance); - Assert.Equal(PressureUnit.PoundForcePerSquareMil, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 lbm/(in·s²)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerInchSecondSquared, PoundsPerInchSecondSquaredTolerance); - Assert.Equal(PressureUnit.PoundPerInchSecondSquared, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 lb/(in·s²)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsPerInchSecondSquared, PoundsPerInchSecondSquaredTolerance); - Assert.Equal(PressureUnit.PoundPerInchSecondSquared, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 at", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TechnicalAtmospheres, TechnicalAtmospheresTolerance); - Assert.Equal(PressureUnit.TechnicalAtmosphere, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 ат", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.TechnicalAtmospheres, TechnicalAtmospheresTolerance); - Assert.Equal(PressureUnit.TechnicalAtmosphere, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 tf/cm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonnesForcePerSquareCentimeter, TonnesForcePerSquareCentimeterTolerance); - Assert.Equal(PressureUnit.TonneForcePerSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 tf/m²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonnesForcePerSquareMeter, TonnesForcePerSquareMeterTolerance); - Assert.Equal(PressureUnit.TonneForcePerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 tf/mm²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonnesForcePerSquareMillimeter, TonnesForcePerSquareMillimeterTolerance); - Assert.Equal(PressureUnit.TonneForcePerSquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 torr", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Torrs, TorrsTolerance); - Assert.Equal(PressureUnit.Torr, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Pressure.Parse("1 торр", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Torrs, TorrsTolerance); - Assert.Equal(PressureUnit.Torr, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - } - - [Fact] - public void TryParse() - { - { - Assert.True(Pressure.TryParse("1 atm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Atmospheres, AtmospheresTolerance); - Assert.Equal(PressureUnit.Atmosphere, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 атм", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Atmospheres, AtmospheresTolerance); - Assert.Equal(PressureUnit.Atmosphere, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 bar", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Bars, BarsTolerance); - Assert.Equal(PressureUnit.Bar, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 бар", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Bars, BarsTolerance); - Assert.Equal(PressureUnit.Bar, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 cbar", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Centibars, CentibarsTolerance); - Assert.Equal(PressureUnit.Centibar, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 сбар", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Centibars, CentibarsTolerance); - Assert.Equal(PressureUnit.Centibar, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 cmH₂O", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentimetersOfWaterColumn, CentimetersOfWaterColumnTolerance); - Assert.Equal(PressureUnit.CentimeterOfWaterColumn, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 cmH2O", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentimetersOfWaterColumn, CentimetersOfWaterColumnTolerance); - Assert.Equal(PressureUnit.CentimeterOfWaterColumn, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 cm wc", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentimetersOfWaterColumn, CentimetersOfWaterColumnTolerance); - Assert.Equal(PressureUnit.CentimeterOfWaterColumn, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 cm wg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentimetersOfWaterColumn, CentimetersOfWaterColumnTolerance); - Assert.Equal(PressureUnit.CentimeterOfWaterColumn, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 daPa", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Decapascals, DecapascalsTolerance); - Assert.Equal(PressureUnit.Decapascal, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 даПа", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Decapascals, DecapascalsTolerance); - Assert.Equal(PressureUnit.Decapascal, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 dbar", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Decibars, DecibarsTolerance); - Assert.Equal(PressureUnit.Decibar, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 дбар", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Decibars, DecibarsTolerance); - Assert.Equal(PressureUnit.Decibar, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 dyn/cm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DynesPerSquareCentimeter, DynesPerSquareCentimeterTolerance); - Assert.Equal(PressureUnit.DynePerSquareCentimeter, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 ft of head", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.FeetOfHead, FeetOfHeadTolerance); - Assert.Equal(PressureUnit.FootOfHead, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 GPa", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gigapascals, GigapascalsTolerance); - Assert.Equal(PressureUnit.Gigapascal, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 hPa", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Hectopascals, HectopascalsTolerance); - Assert.Equal(PressureUnit.Hectopascal, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 inHg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InchesOfMercury, InchesOfMercuryTolerance); - Assert.Equal(PressureUnit.InchOfMercury, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 inH2O", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InchesOfWaterColumn, InchesOfWaterColumnTolerance); - Assert.Equal(PressureUnit.InchOfWaterColumn, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 inch wc", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InchesOfWaterColumn, InchesOfWaterColumnTolerance); - Assert.Equal(PressureUnit.InchOfWaterColumn, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 wc", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InchesOfWaterColumn, InchesOfWaterColumnTolerance); - Assert.Equal(PressureUnit.InchOfWaterColumn, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 kbar", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilobars, KilobarsTolerance); - Assert.Equal(PressureUnit.Kilobar, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 кбар", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilobars, KilobarsTolerance); - Assert.Equal(PressureUnit.Kilobar, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 kgf/cm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerSquareCentimeter, KilogramsForcePerSquareCentimeterTolerance); - Assert.Equal(PressureUnit.KilogramForcePerSquareCentimeter, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 кгс/см²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerSquareCentimeter, KilogramsForcePerSquareCentimeterTolerance); - Assert.Equal(PressureUnit.KilogramForcePerSquareCentimeter, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 kgf/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerSquareMeter, KilogramsForcePerSquareMeterTolerance); - Assert.Equal(PressureUnit.KilogramForcePerSquareMeter, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 кгс/м²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerSquareMeter, KilogramsForcePerSquareMeterTolerance); - Assert.Equal(PressureUnit.KilogramForcePerSquareMeter, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 kgf/mm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerSquareMillimeter, KilogramsForcePerSquareMillimeterTolerance); - Assert.Equal(PressureUnit.KilogramForcePerSquareMillimeter, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 кгс/мм²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerSquareMillimeter, KilogramsForcePerSquareMillimeterTolerance); - Assert.Equal(PressureUnit.KilogramForcePerSquareMillimeter, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 kN/cm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerSquareCentimeter, KilonewtonsPerSquareCentimeterTolerance); - Assert.Equal(PressureUnit.KilonewtonPerSquareCentimeter, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 кН/см²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerSquareCentimeter, KilonewtonsPerSquareCentimeterTolerance); - Assert.Equal(PressureUnit.KilonewtonPerSquareCentimeter, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 kN/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerSquareMeter, KilonewtonsPerSquareMeterTolerance); - Assert.Equal(PressureUnit.KilonewtonPerSquareMeter, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 кН/м²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerSquareMeter, KilonewtonsPerSquareMeterTolerance); - Assert.Equal(PressureUnit.KilonewtonPerSquareMeter, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 kN/mm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerSquareMillimeter, KilonewtonsPerSquareMillimeterTolerance); - Assert.Equal(PressureUnit.KilonewtonPerSquareMillimeter, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 кН/мм²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerSquareMillimeter, KilonewtonsPerSquareMillimeterTolerance); - Assert.Equal(PressureUnit.KilonewtonPerSquareMillimeter, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 kPa", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilopascals, KilopascalsTolerance); - Assert.Equal(PressureUnit.Kilopascal, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 кПа", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilopascals, KilopascalsTolerance); - Assert.Equal(PressureUnit.Kilopascal, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 kipf/ft²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareFoot, KilopoundsForcePerSquareFootTolerance); - Assert.Equal(PressureUnit.KilopoundForcePerSquareFoot, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 ksi", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareInch, KilopoundsForcePerSquareInchTolerance); - Assert.Equal(PressureUnit.KilopoundForcePerSquareInch, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 kipf/in²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareInch, KilopoundsForcePerSquareInchTolerance); - Assert.Equal(PressureUnit.KilopoundForcePerSquareInch, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 ksi", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareInch, KilopoundsForcePerSquareInchTolerance); - Assert.Equal(PressureUnit.KilopoundForcePerSquareInch, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 kipf/in²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareInch, KilopoundsForcePerSquareInchTolerance); - Assert.Equal(PressureUnit.KilopoundForcePerSquareInch, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 kipf/mil²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerSquareMil, KilopoundsForcePerSquareMilTolerance); - Assert.Equal(PressureUnit.KilopoundForcePerSquareMil, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 MN/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MeganewtonsPerSquareMeter, MeganewtonsPerSquareMeterTolerance); - Assert.Equal(PressureUnit.MeganewtonPerSquareMeter, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 МН/м²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MeganewtonsPerSquareMeter, MeganewtonsPerSquareMeterTolerance); - Assert.Equal(PressureUnit.MeganewtonPerSquareMeter, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 m of head", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetersOfHead, MetersOfHeadTolerance); - Assert.Equal(PressureUnit.MeterOfHead, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 mH₂O", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetersOfWaterColumn, MetersOfWaterColumnTolerance); - Assert.Equal(PressureUnit.MeterOfWaterColumn, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 mH2O", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetersOfWaterColumn, MetersOfWaterColumnTolerance); - Assert.Equal(PressureUnit.MeterOfWaterColumn, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 m wc", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetersOfWaterColumn, MetersOfWaterColumnTolerance); - Assert.Equal(PressureUnit.MeterOfWaterColumn, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 m wg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetersOfWaterColumn, MetersOfWaterColumnTolerance); - Assert.Equal(PressureUnit.MeterOfWaterColumn, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 µbar", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microbars, MicrobarsTolerance); - Assert.Equal(PressureUnit.Microbar, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 мкбар", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microbars, MicrobarsTolerance); - Assert.Equal(PressureUnit.Microbar, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 µPa", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Micropascals, MicropascalsTolerance); - Assert.Equal(PressureUnit.Micropascal, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 мкПа", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Micropascals, MicropascalsTolerance); - Assert.Equal(PressureUnit.Micropascal, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 mmHg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimetersOfMercury, MillimetersOfMercuryTolerance); - Assert.Equal(PressureUnit.MillimeterOfMercury, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 мм рт.ст.", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimetersOfMercury, MillimetersOfMercuryTolerance); - Assert.Equal(PressureUnit.MillimeterOfMercury, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 mmH₂O", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimetersOfWaterColumn, MillimetersOfWaterColumnTolerance); - Assert.Equal(PressureUnit.MillimeterOfWaterColumn, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 mmH2O", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimetersOfWaterColumn, MillimetersOfWaterColumnTolerance); - Assert.Equal(PressureUnit.MillimeterOfWaterColumn, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 mm wc", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimetersOfWaterColumn, MillimetersOfWaterColumnTolerance); - Assert.Equal(PressureUnit.MillimeterOfWaterColumn, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 mm wg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimetersOfWaterColumn, MillimetersOfWaterColumnTolerance); - Assert.Equal(PressureUnit.MillimeterOfWaterColumn, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 N/cm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonsPerSquareCentimeter, NewtonsPerSquareCentimeterTolerance); - Assert.Equal(PressureUnit.NewtonPerSquareCentimeter, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 Н/см²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonsPerSquareCentimeter, NewtonsPerSquareCentimeterTolerance); - Assert.Equal(PressureUnit.NewtonPerSquareCentimeter, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 N/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonsPerSquareMeter, NewtonsPerSquareMeterTolerance); - Assert.Equal(PressureUnit.NewtonPerSquareMeter, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 Н/м²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonsPerSquareMeter, NewtonsPerSquareMeterTolerance); - Assert.Equal(PressureUnit.NewtonPerSquareMeter, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 N/mm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonsPerSquareMillimeter, NewtonsPerSquareMillimeterTolerance); - Assert.Equal(PressureUnit.NewtonPerSquareMillimeter, parsed.Unit); - } - - { - Assert.True(Pressure.TryParse("1 Н/мм²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonsPerSquareMillimeter, NewtonsPerSquareMillimeterTolerance); - Assert.Equal(PressureUnit.NewtonPerSquareMillimeter, parsed.Unit); - } + [Fact] + public virtual void As_UnitSystem_SI_ReturnsQuantityInSIUnits() + { + var quantity = new Pressure(value: 1, unit: Pressure.BaseUnit); + var expectedValue = quantity.As(Pressure.Info.GetDefaultUnit(UnitSystem.SI)); - { - Assert.True(Pressure.TryParse("1 Pa", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Pascals, PascalsTolerance); - Assert.Equal(PressureUnit.Pascal, parsed.Unit); - } + var convertedValue = quantity.As(UnitSystem.SI); - { - Assert.True(Pressure.TryParse("1 Па", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Pascals, PascalsTolerance); - Assert.Equal(PressureUnit.Pascal, parsed.Unit); - } + Assert.Equal(expectedValue, convertedValue); + } - { - Assert.True(Pressure.TryParse("1 lb/ft²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareFoot, PoundsForcePerSquareFootTolerance); - Assert.Equal(PressureUnit.PoundForcePerSquareFoot, parsed.Unit); - } + [Fact] + public void As_UnitSystem_ThrowsArgumentNullExceptionIfNull() + { + var quantity = new Pressure(value: 1, unit: Pressure.BaseUnit); + UnitSystem nullUnitSystem = null!; + Assert.Throws(() => quantity.As(nullUnitSystem)); + } - { - Assert.True(Pressure.TryParse("1 psi", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareInch, PoundsForcePerSquareInchTolerance); - Assert.Equal(PressureUnit.PoundForcePerSquareInch, parsed.Unit); - } + [Fact] + public void As_UnitSystem_ThrowsArgumentExceptionIfNotSupported() + { + var quantity = new Pressure(value: 1, unit: Pressure.BaseUnit); + var unsupportedUnitSystem = new UnitSystem(UnsupportedBaseUnits); + Assert.Throws(() => quantity.As(unsupportedUnitSystem)); + } - { - Assert.True(Pressure.TryParse("1 lb/in²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareInch, PoundsForcePerSquareInchTolerance); - Assert.Equal(PressureUnit.PoundForcePerSquareInch, parsed.Unit); - } + [Fact] + public virtual void ToUnit_UnitSystem_SI_ReturnsQuantityInSIUnits() + { + var quantity = new Pressure(value: 1, unit: Pressure.BaseUnit); + var expectedUnit = Pressure.Info.GetDefaultUnit(UnitSystem.SI); + var expectedValue = quantity.As(expectedUnit); + Assert.Multiple(() => { - Assert.True(Pressure.TryParse("1 psi", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareInch, PoundsForcePerSquareInchTolerance); - Assert.Equal(PressureUnit.PoundForcePerSquareInch, parsed.Unit); - } + Pressure quantityToConvert = quantity; - { - Assert.True(Pressure.TryParse("1 lb/in²", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareInch, PoundsForcePerSquareInchTolerance); - Assert.Equal(PressureUnit.PoundForcePerSquareInch, parsed.Unit); - } + Pressure convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); + Assert.Equal(expectedUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }, () => { - Assert.True(Pressure.TryParse("1 lb/mil²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareMil, PoundsForcePerSquareMilTolerance); - Assert.Equal(PressureUnit.PoundForcePerSquareMil, parsed.Unit); - } + IQuantity quantityToConvert = quantity; - { - Assert.True(Pressure.TryParse("1 lbs/mil²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerSquareMil, PoundsForcePerSquareMilTolerance); - Assert.Equal(PressureUnit.PoundForcePerSquareMil, parsed.Unit); - } + IQuantity convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); + Assert.Equal(expectedUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }, () => { - Assert.True(Pressure.TryParse("1 lbm/(in·s²)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerInchSecondSquared, PoundsPerInchSecondSquaredTolerance); - Assert.Equal(PressureUnit.PoundPerInchSecondSquared, parsed.Unit); - } + IQuantity quantityToConvert = quantity; - { - Assert.True(Pressure.TryParse("1 lb/(in·s²)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsPerInchSecondSquared, PoundsPerInchSecondSquaredTolerance); - Assert.Equal(PressureUnit.PoundPerInchSecondSquared, parsed.Unit); - } + IQuantity convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); - { - Assert.True(Pressure.TryParse("1 at", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TechnicalAtmospheres, TechnicalAtmospheresTolerance); - Assert.Equal(PressureUnit.TechnicalAtmosphere, parsed.Unit); - } + Assert.Equal(expectedUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }); + } + [Fact] + public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() + { + UnitSystem nullUnitSystem = null!; + Assert.Multiple(() => { - Assert.True(Pressure.TryParse("1 ат", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TechnicalAtmospheres, TechnicalAtmospheresTolerance); - Assert.Equal(PressureUnit.TechnicalAtmosphere, parsed.Unit); - } - + var quantity = new Pressure(value: 1, unit: Pressure.BaseUnit); + Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); + }, () => { - Assert.True(Pressure.TryParse("1 tf/cm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonnesForcePerSquareCentimeter, TonnesForcePerSquareCentimeterTolerance); - Assert.Equal(PressureUnit.TonneForcePerSquareCentimeter, parsed.Unit); - } - + IQuantity quantity = new Pressure(value: 1, unit: Pressure.BaseUnit); + Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); + }, () => { - Assert.True(Pressure.TryParse("1 tf/m²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonnesForcePerSquareMeter, TonnesForcePerSquareMeterTolerance); - Assert.Equal(PressureUnit.TonneForcePerSquareMeter, parsed.Unit); - } + IQuantity quantity = new Pressure(value: 1, unit: Pressure.BaseUnit); + Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); + }); + } + [Fact] + public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() + { + var unsupportedUnitSystem = new UnitSystem(UnsupportedBaseUnits); + Assert.Multiple(() => { - Assert.True(Pressure.TryParse("1 tf/mm²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonnesForcePerSquareMillimeter, TonnesForcePerSquareMillimeterTolerance); - Assert.Equal(PressureUnit.TonneForcePerSquareMillimeter, parsed.Unit); - } - + var quantity = new Pressure(value: 1, unit: Pressure.BaseUnit); + Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); + }, () => { - Assert.True(Pressure.TryParse("1 torr", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Torrs, TorrsTolerance); - Assert.Equal(PressureUnit.Torr, parsed.Unit); - } - + IQuantity quantity = new Pressure(value: 1, unit: Pressure.BaseUnit); + Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); + }, () => { - Assert.True(Pressure.TryParse("1 торр", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Torrs, TorrsTolerance); - Assert.Equal(PressureUnit.Torr, parsed.Unit); - } + IQuantity quantity = new Pressure(value: 1, unit: Pressure.BaseUnit); + Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); + }); + } + + [Theory] + [InlineData("en-US", "4.2 atm", PressureUnit.Atmosphere, 4.2)] + [InlineData("en-US", "4.2 bar", PressureUnit.Bar, 4.2)] + [InlineData("en-US", "4.2 cbar", PressureUnit.Centibar, 4.2)] + [InlineData("en-US", "4.2 cmH₂O", PressureUnit.CentimeterOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 cmH2O", PressureUnit.CentimeterOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 cm wc", PressureUnit.CentimeterOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 cm wg", PressureUnit.CentimeterOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 daPa", PressureUnit.Decapascal, 4.2)] + [InlineData("en-US", "4.2 dbar", PressureUnit.Decibar, 4.2)] + [InlineData("en-US", "4.2 dyn/cm²", PressureUnit.DynePerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 ft of head", PressureUnit.FootOfHead, 4.2)] + [InlineData("en-US", "4.2 GPa", PressureUnit.Gigapascal, 4.2)] + [InlineData("en-US", "4.2 hPa", PressureUnit.Hectopascal, 4.2)] + [InlineData("en-US", "4.2 inHg", PressureUnit.InchOfMercury, 4.2)] + [InlineData("en-US", "4.2 inH2O", PressureUnit.InchOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 inch wc", PressureUnit.InchOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 wc", PressureUnit.InchOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 kbar", PressureUnit.Kilobar, 4.2)] + [InlineData("en-US", "4.2 kgf/cm²", PressureUnit.KilogramForcePerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 kgf/m²", PressureUnit.KilogramForcePerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 kgf/mm²", PressureUnit.KilogramForcePerSquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 kN/cm²", PressureUnit.KilonewtonPerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 kN/m²", PressureUnit.KilonewtonPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 kN/mm²", PressureUnit.KilonewtonPerSquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 kPa", PressureUnit.Kilopascal, 4.2)] + [InlineData("en-US", "4.2 kipf/ft²", PressureUnit.KilopoundForcePerSquareFoot, 4.2)] + [InlineData("en-US", "4.2 ksi", PressureUnit.KilopoundForcePerSquareInch, 4.2)] + [InlineData("en-US", "4.2 kipf/in²", PressureUnit.KilopoundForcePerSquareInch, 4.2)] + [InlineData("en-US", "4.2 kipf/mil²", PressureUnit.KilopoundForcePerSquareMil, 4.2)] + [InlineData("en-US", "4.2 Mbar", PressureUnit.Megabar, 4.2)] + [InlineData("en-US", "4.2 MN/m²", PressureUnit.MeganewtonPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 MPa", PressureUnit.Megapascal, 4.2)] + [InlineData("en-US", "4.2 m of head", PressureUnit.MeterOfHead, 4.2)] + [InlineData("en-US", "4.2 mH₂O", PressureUnit.MeterOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 mH2O", PressureUnit.MeterOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 m wc", PressureUnit.MeterOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 m wg", PressureUnit.MeterOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 µbar", PressureUnit.Microbar, 4.2)] + [InlineData("en-US", "4.2 µPa", PressureUnit.Micropascal, 4.2)] + [InlineData("en-US", "4.2 mbar", PressureUnit.Millibar, 4.2)] + [InlineData("en-US", "4.2 mmHg", PressureUnit.MillimeterOfMercury, 4.2)] + [InlineData("en-US", "4.2 mmH₂O", PressureUnit.MillimeterOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 mmH2O", PressureUnit.MillimeterOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 mm wc", PressureUnit.MillimeterOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 mm wg", PressureUnit.MillimeterOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 mPa", PressureUnit.Millipascal, 4.2)] + [InlineData("en-US", "4.2 N/cm²", PressureUnit.NewtonPerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 N/m²", PressureUnit.NewtonPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 N/mm²", PressureUnit.NewtonPerSquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 Pa", PressureUnit.Pascal, 4.2)] + [InlineData("en-US", "4.2 lb/ft²", PressureUnit.PoundForcePerSquareFoot, 4.2)] + [InlineData("en-US", "4.2 psi", PressureUnit.PoundForcePerSquareInch, 4.2)] + [InlineData("en-US", "4.2 lb/in²", PressureUnit.PoundForcePerSquareInch, 4.2)] + [InlineData("en-US", "4.2 lb/mil²", PressureUnit.PoundForcePerSquareMil, 4.2)] + [InlineData("en-US", "4.2 lbs/mil²", PressureUnit.PoundForcePerSquareMil, 4.2)] + [InlineData("en-US", "4.2 lbm/(in·s²)", PressureUnit.PoundPerInchSecondSquared, 4.2)] + [InlineData("en-US", "4.2 lb/(in·s²)", PressureUnit.PoundPerInchSecondSquared, 4.2)] + [InlineData("en-US", "4.2 at", PressureUnit.TechnicalAtmosphere, 4.2)] + [InlineData("en-US", "4.2 tf/cm²", PressureUnit.TonneForcePerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 tf/m²", PressureUnit.TonneForcePerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 tf/mm²", PressureUnit.TonneForcePerSquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 torr", PressureUnit.Torr, 4.2)] + [InlineData("ru-RU", "4,2 атм", PressureUnit.Atmosphere, 4.2)] + [InlineData("ru-RU", "4,2 бар", PressureUnit.Bar, 4.2)] + [InlineData("ru-RU", "4,2 сбар", PressureUnit.Centibar, 4.2)] + [InlineData("ru-RU", "4,2 даПа", PressureUnit.Decapascal, 4.2)] + [InlineData("ru-RU", "4,2 дбар", PressureUnit.Decibar, 4.2)] + [InlineData("ru-RU", "4,2 ГПа", PressureUnit.Gigapascal, 4.2)] + [InlineData("ru-RU", "4,2 гПа", PressureUnit.Hectopascal, 4.2)] + [InlineData("ru-RU", "4,2 кбар", PressureUnit.Kilobar, 4.2)] + [InlineData("ru-RU", "4,2 кгс/см²", PressureUnit.KilogramForcePerSquareCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 кгс/м²", PressureUnit.KilogramForcePerSquareMeter, 4.2)] + [InlineData("ru-RU", "4,2 кгс/мм²", PressureUnit.KilogramForcePerSquareMillimeter, 4.2)] + [InlineData("ru-RU", "4,2 кН/см²", PressureUnit.KilonewtonPerSquareCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 кН/м²", PressureUnit.KilonewtonPerSquareMeter, 4.2)] + [InlineData("ru-RU", "4,2 кН/мм²", PressureUnit.KilonewtonPerSquareMillimeter, 4.2)] + [InlineData("ru-RU", "4,2 кПа", PressureUnit.Kilopascal, 4.2)] + [InlineData("ru-RU", "4,2 ksi", PressureUnit.KilopoundForcePerSquareInch, 4.2)] + [InlineData("ru-RU", "4,2 kipf/in²", PressureUnit.KilopoundForcePerSquareInch, 4.2)] + [InlineData("ru-RU", "4,2 Мбар", PressureUnit.Megabar, 4.2)] + [InlineData("ru-RU", "4,2 МН/м²", PressureUnit.MeganewtonPerSquareMeter, 4.2)] + [InlineData("ru-RU", "4,2 МПа", PressureUnit.Megapascal, 4.2)] + [InlineData("ru-RU", "4,2 мкбар", PressureUnit.Microbar, 4.2)] + [InlineData("ru-RU", "4,2 мкПа", PressureUnit.Micropascal, 4.2)] + [InlineData("ru-RU", "4,2 мбар", PressureUnit.Millibar, 4.2)] + [InlineData("ru-RU", "4,2 мм рт.ст.", PressureUnit.MillimeterOfMercury, 4.2)] + [InlineData("ru-RU", "4,2 мПа", PressureUnit.Millipascal, 4.2)] + [InlineData("ru-RU", "4,2 Н/см²", PressureUnit.NewtonPerSquareCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 Н/м²", PressureUnit.NewtonPerSquareMeter, 4.2)] + [InlineData("ru-RU", "4,2 Н/мм²", PressureUnit.NewtonPerSquareMillimeter, 4.2)] + [InlineData("ru-RU", "4,2 Па", PressureUnit.Pascal, 4.2)] + [InlineData("ru-RU", "4,2 psi", PressureUnit.PoundForcePerSquareInch, 4.2)] + [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, decimal expectedValue) + { + using var _ = new CultureScope(culture); + var parsed = Pressure.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); + } + [Theory] + [InlineData("en-US", "4.2 atm", PressureUnit.Atmosphere, 4.2)] + [InlineData("en-US", "4.2 bar", PressureUnit.Bar, 4.2)] + [InlineData("en-US", "4.2 cbar", PressureUnit.Centibar, 4.2)] + [InlineData("en-US", "4.2 cmH₂O", PressureUnit.CentimeterOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 cmH2O", PressureUnit.CentimeterOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 cm wc", PressureUnit.CentimeterOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 cm wg", PressureUnit.CentimeterOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 daPa", PressureUnit.Decapascal, 4.2)] + [InlineData("en-US", "4.2 dbar", PressureUnit.Decibar, 4.2)] + [InlineData("en-US", "4.2 dyn/cm²", PressureUnit.DynePerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 ft of head", PressureUnit.FootOfHead, 4.2)] + [InlineData("en-US", "4.2 GPa", PressureUnit.Gigapascal, 4.2)] + [InlineData("en-US", "4.2 hPa", PressureUnit.Hectopascal, 4.2)] + [InlineData("en-US", "4.2 inHg", PressureUnit.InchOfMercury, 4.2)] + [InlineData("en-US", "4.2 inH2O", PressureUnit.InchOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 inch wc", PressureUnit.InchOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 wc", PressureUnit.InchOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 kbar", PressureUnit.Kilobar, 4.2)] + [InlineData("en-US", "4.2 kgf/cm²", PressureUnit.KilogramForcePerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 kgf/m²", PressureUnit.KilogramForcePerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 kgf/mm²", PressureUnit.KilogramForcePerSquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 kN/cm²", PressureUnit.KilonewtonPerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 kN/m²", PressureUnit.KilonewtonPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 kN/mm²", PressureUnit.KilonewtonPerSquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 kPa", PressureUnit.Kilopascal, 4.2)] + [InlineData("en-US", "4.2 kipf/ft²", PressureUnit.KilopoundForcePerSquareFoot, 4.2)] + [InlineData("en-US", "4.2 ksi", PressureUnit.KilopoundForcePerSquareInch, 4.2)] + [InlineData("en-US", "4.2 kipf/in²", PressureUnit.KilopoundForcePerSquareInch, 4.2)] + [InlineData("en-US", "4.2 kipf/mil²", PressureUnit.KilopoundForcePerSquareMil, 4.2)] + [InlineData("en-US", "4.2 Mbar", PressureUnit.Megabar, 4.2)] + [InlineData("en-US", "4.2 MN/m²", PressureUnit.MeganewtonPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 MPa", PressureUnit.Megapascal, 4.2)] + [InlineData("en-US", "4.2 m of head", PressureUnit.MeterOfHead, 4.2)] + [InlineData("en-US", "4.2 mH₂O", PressureUnit.MeterOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 mH2O", PressureUnit.MeterOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 m wc", PressureUnit.MeterOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 m wg", PressureUnit.MeterOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 µbar", PressureUnit.Microbar, 4.2)] + [InlineData("en-US", "4.2 µPa", PressureUnit.Micropascal, 4.2)] + [InlineData("en-US", "4.2 mbar", PressureUnit.Millibar, 4.2)] + [InlineData("en-US", "4.2 mmHg", PressureUnit.MillimeterOfMercury, 4.2)] + [InlineData("en-US", "4.2 mmH₂O", PressureUnit.MillimeterOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 mmH2O", PressureUnit.MillimeterOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 mm wc", PressureUnit.MillimeterOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 mm wg", PressureUnit.MillimeterOfWaterColumn, 4.2)] + [InlineData("en-US", "4.2 mPa", PressureUnit.Millipascal, 4.2)] + [InlineData("en-US", "4.2 N/cm²", PressureUnit.NewtonPerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 N/m²", PressureUnit.NewtonPerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 N/mm²", PressureUnit.NewtonPerSquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 Pa", PressureUnit.Pascal, 4.2)] + [InlineData("en-US", "4.2 lb/ft²", PressureUnit.PoundForcePerSquareFoot, 4.2)] + [InlineData("en-US", "4.2 psi", PressureUnit.PoundForcePerSquareInch, 4.2)] + [InlineData("en-US", "4.2 lb/in²", PressureUnit.PoundForcePerSquareInch, 4.2)] + [InlineData("en-US", "4.2 lb/mil²", PressureUnit.PoundForcePerSquareMil, 4.2)] + [InlineData("en-US", "4.2 lbs/mil²", PressureUnit.PoundForcePerSquareMil, 4.2)] + [InlineData("en-US", "4.2 lbm/(in·s²)", PressureUnit.PoundPerInchSecondSquared, 4.2)] + [InlineData("en-US", "4.2 lb/(in·s²)", PressureUnit.PoundPerInchSecondSquared, 4.2)] + [InlineData("en-US", "4.2 at", PressureUnit.TechnicalAtmosphere, 4.2)] + [InlineData("en-US", "4.2 tf/cm²", PressureUnit.TonneForcePerSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 tf/m²", PressureUnit.TonneForcePerSquareMeter, 4.2)] + [InlineData("en-US", "4.2 tf/mm²", PressureUnit.TonneForcePerSquareMillimeter, 4.2)] + [InlineData("en-US", "4.2 torr", PressureUnit.Torr, 4.2)] + [InlineData("ru-RU", "4,2 атм", PressureUnit.Atmosphere, 4.2)] + [InlineData("ru-RU", "4,2 бар", PressureUnit.Bar, 4.2)] + [InlineData("ru-RU", "4,2 сбар", PressureUnit.Centibar, 4.2)] + [InlineData("ru-RU", "4,2 даПа", PressureUnit.Decapascal, 4.2)] + [InlineData("ru-RU", "4,2 дбар", PressureUnit.Decibar, 4.2)] + [InlineData("ru-RU", "4,2 ГПа", PressureUnit.Gigapascal, 4.2)] + [InlineData("ru-RU", "4,2 гПа", PressureUnit.Hectopascal, 4.2)] + [InlineData("ru-RU", "4,2 кбар", PressureUnit.Kilobar, 4.2)] + [InlineData("ru-RU", "4,2 кгс/см²", PressureUnit.KilogramForcePerSquareCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 кгс/м²", PressureUnit.KilogramForcePerSquareMeter, 4.2)] + [InlineData("ru-RU", "4,2 кгс/мм²", PressureUnit.KilogramForcePerSquareMillimeter, 4.2)] + [InlineData("ru-RU", "4,2 кН/см²", PressureUnit.KilonewtonPerSquareCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 кН/м²", PressureUnit.KilonewtonPerSquareMeter, 4.2)] + [InlineData("ru-RU", "4,2 кН/мм²", PressureUnit.KilonewtonPerSquareMillimeter, 4.2)] + [InlineData("ru-RU", "4,2 кПа", PressureUnit.Kilopascal, 4.2)] + [InlineData("ru-RU", "4,2 ksi", PressureUnit.KilopoundForcePerSquareInch, 4.2)] + [InlineData("ru-RU", "4,2 kipf/in²", PressureUnit.KilopoundForcePerSquareInch, 4.2)] + [InlineData("ru-RU", "4,2 Мбар", PressureUnit.Megabar, 4.2)] + [InlineData("ru-RU", "4,2 МН/м²", PressureUnit.MeganewtonPerSquareMeter, 4.2)] + [InlineData("ru-RU", "4,2 МПа", PressureUnit.Megapascal, 4.2)] + [InlineData("ru-RU", "4,2 мкбар", PressureUnit.Microbar, 4.2)] + [InlineData("ru-RU", "4,2 мкПа", PressureUnit.Micropascal, 4.2)] + [InlineData("ru-RU", "4,2 мбар", PressureUnit.Millibar, 4.2)] + [InlineData("ru-RU", "4,2 мм рт.ст.", PressureUnit.MillimeterOfMercury, 4.2)] + [InlineData("ru-RU", "4,2 мПа", PressureUnit.Millipascal, 4.2)] + [InlineData("ru-RU", "4,2 Н/см²", PressureUnit.NewtonPerSquareCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 Н/м²", PressureUnit.NewtonPerSquareMeter, 4.2)] + [InlineData("ru-RU", "4,2 Н/мм²", PressureUnit.NewtonPerSquareMillimeter, 4.2)] + [InlineData("ru-RU", "4,2 Па", PressureUnit.Pascal, 4.2)] + [InlineData("ru-RU", "4,2 psi", PressureUnit.PoundForcePerSquareInch, 4.2)] + [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, decimal expectedValue) + { + using var _ = new CultureScope(culture); + Assert.True(Pressure.TryParse(quantityString, out Pressure parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -2606,6 +1647,104 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Pressu Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", PressureUnit.Atmosphere, "atm")] + [InlineData("en-US", PressureUnit.Bar, "bar")] + [InlineData("en-US", PressureUnit.Centibar, "cbar")] + [InlineData("en-US", PressureUnit.CentimeterOfWaterColumn, "cmH₂O")] + [InlineData("en-US", PressureUnit.Decapascal, "daPa")] + [InlineData("en-US", PressureUnit.Decibar, "dbar")] + [InlineData("en-US", PressureUnit.DynePerSquareCentimeter, "dyn/cm²")] + [InlineData("en-US", PressureUnit.FootOfHead, "ft of head")] + [InlineData("en-US", PressureUnit.Gigapascal, "GPa")] + [InlineData("en-US", PressureUnit.Hectopascal, "hPa")] + [InlineData("en-US", PressureUnit.InchOfMercury, "inHg")] + [InlineData("en-US", PressureUnit.InchOfWaterColumn, "inH2O")] + [InlineData("en-US", PressureUnit.Kilobar, "kbar")] + [InlineData("en-US", PressureUnit.KilogramForcePerSquareCentimeter, "kgf/cm²")] + [InlineData("en-US", PressureUnit.KilogramForcePerSquareMeter, "kgf/m²")] + [InlineData("en-US", PressureUnit.KilogramForcePerSquareMillimeter, "kgf/mm²")] + [InlineData("en-US", PressureUnit.KilonewtonPerSquareCentimeter, "kN/cm²")] + [InlineData("en-US", PressureUnit.KilonewtonPerSquareMeter, "kN/m²")] + [InlineData("en-US", PressureUnit.KilonewtonPerSquareMillimeter, "kN/mm²")] + [InlineData("en-US", PressureUnit.Kilopascal, "kPa")] + [InlineData("en-US", PressureUnit.KilopoundForcePerSquareFoot, "kipf/ft²")] + [InlineData("en-US", PressureUnit.KilopoundForcePerSquareInch, "ksi")] + [InlineData("en-US", PressureUnit.KilopoundForcePerSquareMil, "kipf/mil²")] + [InlineData("en-US", PressureUnit.Megabar, "Mbar")] + [InlineData("en-US", PressureUnit.MeganewtonPerSquareMeter, "MN/m²")] + [InlineData("en-US", PressureUnit.Megapascal, "MPa")] + [InlineData("en-US", PressureUnit.MeterOfHead, "m of head")] + [InlineData("en-US", PressureUnit.MeterOfWaterColumn, "mH₂O")] + [InlineData("en-US", PressureUnit.Microbar, "µbar")] + [InlineData("en-US", PressureUnit.Micropascal, "µPa")] + [InlineData("en-US", PressureUnit.Millibar, "mbar")] + [InlineData("en-US", PressureUnit.MillimeterOfMercury, "mmHg")] + [InlineData("en-US", PressureUnit.MillimeterOfWaterColumn, "mmH₂O")] + [InlineData("en-US", PressureUnit.Millipascal, "mPa")] + [InlineData("en-US", PressureUnit.NewtonPerSquareCentimeter, "N/cm²")] + [InlineData("en-US", PressureUnit.NewtonPerSquareMeter, "N/m²")] + [InlineData("en-US", PressureUnit.NewtonPerSquareMillimeter, "N/mm²")] + [InlineData("en-US", PressureUnit.Pascal, "Pa")] + [InlineData("en-US", PressureUnit.PoundForcePerSquareFoot, "lb/ft²")] + [InlineData("en-US", PressureUnit.PoundForcePerSquareInch, "psi")] + [InlineData("en-US", PressureUnit.PoundForcePerSquareMil, "lb/mil²")] + [InlineData("en-US", PressureUnit.PoundPerInchSecondSquared, "lbm/(in·s²)")] + [InlineData("en-US", PressureUnit.TechnicalAtmosphere, "at")] + [InlineData("en-US", PressureUnit.TonneForcePerSquareCentimeter, "tf/cm²")] + [InlineData("en-US", PressureUnit.TonneForcePerSquareMeter, "tf/m²")] + [InlineData("en-US", PressureUnit.TonneForcePerSquareMillimeter, "tf/mm²")] + [InlineData("en-US", PressureUnit.Torr, "torr")] + [InlineData("ru-RU", PressureUnit.Atmosphere, "атм")] + [InlineData("ru-RU", PressureUnit.Bar, "бар")] + [InlineData("ru-RU", PressureUnit.Centibar, "сбар")] + [InlineData("ru-RU", PressureUnit.Decapascal, "даПа")] + [InlineData("ru-RU", PressureUnit.Decibar, "дбар")] + [InlineData("ru-RU", PressureUnit.Gigapascal, "ГПа")] + [InlineData("ru-RU", PressureUnit.Hectopascal, "гПа")] + [InlineData("ru-RU", PressureUnit.Kilobar, "кбар")] + [InlineData("ru-RU", PressureUnit.KilogramForcePerSquareCentimeter, "кгс/см²")] + [InlineData("ru-RU", PressureUnit.KilogramForcePerSquareMeter, "кгс/м²")] + [InlineData("ru-RU", PressureUnit.KilogramForcePerSquareMillimeter, "кгс/мм²")] + [InlineData("ru-RU", PressureUnit.KilonewtonPerSquareCentimeter, "кН/см²")] + [InlineData("ru-RU", PressureUnit.KilonewtonPerSquareMeter, "кН/м²")] + [InlineData("ru-RU", PressureUnit.KilonewtonPerSquareMillimeter, "кН/мм²")] + [InlineData("ru-RU", PressureUnit.Kilopascal, "кПа")] + [InlineData("ru-RU", PressureUnit.KilopoundForcePerSquareInch, "ksi")] + [InlineData("ru-RU", PressureUnit.Megabar, "Мбар")] + [InlineData("ru-RU", PressureUnit.MeganewtonPerSquareMeter, "МН/м²")] + [InlineData("ru-RU", PressureUnit.Megapascal, "МПа")] + [InlineData("ru-RU", PressureUnit.Microbar, "мкбар")] + [InlineData("ru-RU", PressureUnit.Micropascal, "мкПа")] + [InlineData("ru-RU", PressureUnit.Millibar, "мбар")] + [InlineData("ru-RU", PressureUnit.MillimeterOfMercury, "мм рт.ст.")] + [InlineData("ru-RU", PressureUnit.Millipascal, "мПа")] + [InlineData("ru-RU", PressureUnit.NewtonPerSquareCentimeter, "Н/см²")] + [InlineData("ru-RU", PressureUnit.NewtonPerSquareMeter, "Н/м²")] + [InlineData("ru-RU", PressureUnit.NewtonPerSquareMillimeter, "Н/мм²")] + [InlineData("ru-RU", PressureUnit.Pascal, "Па")] + [InlineData("ru-RU", PressureUnit.PoundForcePerSquareInch, "psi")] + [InlineData("ru-RU", PressureUnit.TechnicalAtmosphere, "ат")] + [InlineData("ru-RU", PressureUnit.Torr, "торр")] + public void GetAbbreviationForCulture(string culture, PressureUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Pressure.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Pressure.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Pressure.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(PressureUnit unit) @@ -2636,6 +1775,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); }); } @@ -2659,78 +1799,80 @@ 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.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.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] @@ -2776,8 +1918,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); @@ -2814,23 +1954,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = Pressure.FromPascals(1); - Assert.True(v.Equals(Pressure.FromPascals(1), PascalsTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Pressure.Zero, PascalsTolerance, ComparisonType.Relative)); - Assert.True(Pressure.FromPascals(100).Equals(Pressure.FromPascals(120), 0.3, ComparisonType.Relative)); - Assert.False(Pressure.FromPascals(100).Equals(Pressure.FromPascals(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = Pressure.FromPascals(1); - Assert.Throws(() => v.Equals(Pressure.FromPascals(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -2845,6 +1968,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(pascal.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = Pressure.FromPascals(1); + var negativeTolerance = Pressure.FromPascals(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -2861,6 +2010,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() { @@ -3011,158 +2172,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Pressure.FromPascals(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Pressure.FromPascals(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Pressure.FromPascals(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Pressure.FromPascals(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Pressure.FromPascals(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Pressure.FromPascals(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Pressure.FromPascals(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Pressure.FromPascals(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Pressure.FromPascals(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Pressure.FromPascals(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Pressure.FromPascals(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Pressure.FromPascals(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Pressure.FromPascals(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Pressure.FromPascals(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Pressure.FromPascals(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Pressure.FromPascals(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Pressure))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Pressure.FromPascals(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(PressureUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Pressure.FromPascals(1.0); - Assert.Equal(Pressure.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Pressure.FromPascals(1.0); - Assert.Equal(Pressure.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Pressure.FromPascals(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Pressure.FromPascals(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Pressure.FromPascals(1.0); - Assert.Equal(new {Pressure.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 076c08aa38..5b81d01045 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RadiationEquivalentDoseRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RadiationEquivalentDoseRateTestsBase.g.cs @@ -132,7 +132,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new RadiationEquivalentDoseRate(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -145,15 +145,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void RadiationEquivalentDoseRate_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + RadiationEquivalentDoseRateUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new RadiationEquivalentDoseRate(1, RadiationEquivalentDoseRateUnit.SievertPerSecond); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(RadiationEquivalentDoseRate.Zero, quantityInfo.Zero); Assert.Equal("RadiationEquivalentDoseRate", quantityInfo.Name); + Assert.Equal(RadiationEquivalentDoseRate.Zero, quantityInfo.Zero); + Assert.Equal(RadiationEquivalentDoseRate.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(RadiationEquivalentDoseRate.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void RadiationEquivalentDoseRateInfo_CreateWithCustomUnitInfos() + { + RadiationEquivalentDoseRateUnit[] expectedUnits = [RadiationEquivalentDoseRateUnit.SievertPerSecond]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -176,43 +194,43 @@ public void SievertPerSecondToRadiationEquivalentDoseRateUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = RadiationEquivalentDoseRate.From(1, RadiationEquivalentDoseRateUnit.MicrosievertPerHour); - AssertEx.EqualTolerance(1, quantity00.MicrosievertsPerHour, MicrosievertsPerHourTolerance); + Assert.Equal(1, quantity00.MicrosievertsPerHour); Assert.Equal(RadiationEquivalentDoseRateUnit.MicrosievertPerHour, quantity00.Unit); var quantity01 = RadiationEquivalentDoseRate.From(1, RadiationEquivalentDoseRateUnit.MicrosievertPerSecond); - AssertEx.EqualTolerance(1, quantity01.MicrosievertsPerSecond, MicrosievertsPerSecondTolerance); + Assert.Equal(1, quantity01.MicrosievertsPerSecond); Assert.Equal(RadiationEquivalentDoseRateUnit.MicrosievertPerSecond, quantity01.Unit); var quantity02 = RadiationEquivalentDoseRate.From(1, RadiationEquivalentDoseRateUnit.MilliroentgenEquivalentManPerHour); - AssertEx.EqualTolerance(1, quantity02.MilliroentgensEquivalentManPerHour, MilliroentgensEquivalentManPerHourTolerance); + Assert.Equal(1, quantity02.MilliroentgensEquivalentManPerHour); Assert.Equal(RadiationEquivalentDoseRateUnit.MilliroentgenEquivalentManPerHour, quantity02.Unit); var quantity03 = RadiationEquivalentDoseRate.From(1, RadiationEquivalentDoseRateUnit.MillisievertPerHour); - AssertEx.EqualTolerance(1, quantity03.MillisievertsPerHour, MillisievertsPerHourTolerance); + Assert.Equal(1, quantity03.MillisievertsPerHour); Assert.Equal(RadiationEquivalentDoseRateUnit.MillisievertPerHour, quantity03.Unit); var quantity04 = RadiationEquivalentDoseRate.From(1, RadiationEquivalentDoseRateUnit.MillisievertPerSecond); - AssertEx.EqualTolerance(1, quantity04.MillisievertsPerSecond, MillisievertsPerSecondTolerance); + Assert.Equal(1, quantity04.MillisievertsPerSecond); Assert.Equal(RadiationEquivalentDoseRateUnit.MillisievertPerSecond, quantity04.Unit); var quantity05 = RadiationEquivalentDoseRate.From(1, RadiationEquivalentDoseRateUnit.NanosievertPerHour); - AssertEx.EqualTolerance(1, quantity05.NanosievertsPerHour, NanosievertsPerHourTolerance); + Assert.Equal(1, quantity05.NanosievertsPerHour); Assert.Equal(RadiationEquivalentDoseRateUnit.NanosievertPerHour, quantity05.Unit); var quantity06 = RadiationEquivalentDoseRate.From(1, RadiationEquivalentDoseRateUnit.NanosievertPerSecond); - AssertEx.EqualTolerance(1, quantity06.NanosievertsPerSecond, NanosievertsPerSecondTolerance); + Assert.Equal(1, quantity06.NanosievertsPerSecond); Assert.Equal(RadiationEquivalentDoseRateUnit.NanosievertPerSecond, quantity06.Unit); var quantity07 = RadiationEquivalentDoseRate.From(1, RadiationEquivalentDoseRateUnit.RoentgenEquivalentManPerHour); - AssertEx.EqualTolerance(1, quantity07.RoentgensEquivalentManPerHour, RoentgensEquivalentManPerHourTolerance); + Assert.Equal(1, quantity07.RoentgensEquivalentManPerHour); Assert.Equal(RadiationEquivalentDoseRateUnit.RoentgenEquivalentManPerHour, quantity07.Unit); var quantity08 = RadiationEquivalentDoseRate.From(1, RadiationEquivalentDoseRateUnit.SievertPerHour); - AssertEx.EqualTolerance(1, quantity08.SievertsPerHour, SievertsPerHourTolerance); + Assert.Equal(1, quantity08.SievertsPerHour); Assert.Equal(RadiationEquivalentDoseRateUnit.SievertPerHour, quantity08.Unit); var quantity09 = RadiationEquivalentDoseRate.From(1, RadiationEquivalentDoseRateUnit.SievertPerSecond); - AssertEx.EqualTolerance(1, quantity09.SievertsPerSecond, SievertsPerSecondTolerance); + Assert.Equal(1, quantity09.SievertsPerSecond); Assert.Equal(RadiationEquivalentDoseRateUnit.SievertPerSecond, quantity09.Unit); } @@ -357,248 +375,58 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 µSv/h", RadiationEquivalentDoseRateUnit.MicrosievertPerHour, 4.2)] + [InlineData("en-US", "4.2 µSv/s", RadiationEquivalentDoseRateUnit.MicrosievertPerSecond, 4.2)] + [InlineData("en-US", "4.2 mrem/h", RadiationEquivalentDoseRateUnit.MilliroentgenEquivalentManPerHour, 4.2)] + [InlineData("en-US", "4.2 mSv/h", RadiationEquivalentDoseRateUnit.MillisievertPerHour, 4.2)] + [InlineData("en-US", "4.2 mSv/s", RadiationEquivalentDoseRateUnit.MillisievertPerSecond, 4.2)] + [InlineData("en-US", "4.2 nSv/h", RadiationEquivalentDoseRateUnit.NanosievertPerHour, 4.2)] + [InlineData("en-US", "4.2 nSv/s", RadiationEquivalentDoseRateUnit.NanosievertPerSecond, 4.2)] + [InlineData("en-US", "4.2 rem/h", RadiationEquivalentDoseRateUnit.RoentgenEquivalentManPerHour, 4.2)] + [InlineData("en-US", "4.2 Sv/h", RadiationEquivalentDoseRateUnit.SievertPerHour, 4.2)] + [InlineData("en-US", "4.2 Sv/s", RadiationEquivalentDoseRateUnit.SievertPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 мкЗв/ч", RadiationEquivalentDoseRateUnit.MicrosievertPerHour, 4.2)] + [InlineData("ru-RU", "4,2 мкЗв/с", RadiationEquivalentDoseRateUnit.MicrosievertPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 мЗв/ч", RadiationEquivalentDoseRateUnit.MillisievertPerHour, 4.2)] + [InlineData("ru-RU", "4,2 мЗв/с", RadiationEquivalentDoseRateUnit.MillisievertPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 нЗв/ч", RadiationEquivalentDoseRateUnit.NanosievertPerHour, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = RadiationEquivalentDoseRate.Parse("1 µSv/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrosievertsPerHour, MicrosievertsPerHourTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.MicrosievertPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationEquivalentDoseRate.Parse("1 мкЗв/ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MicrosievertsPerHour, MicrosievertsPerHourTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.MicrosievertPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationEquivalentDoseRate.Parse("1 µSv/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrosievertsPerSecond, MicrosievertsPerSecondTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.MicrosievertPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationEquivalentDoseRate.Parse("1 мкЗв/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MicrosievertsPerSecond, MicrosievertsPerSecondTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.MicrosievertPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationEquivalentDoseRate.Parse("1 mrem/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilliroentgensEquivalentManPerHour, MilliroentgensEquivalentManPerHourTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.MilliroentgenEquivalentManPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationEquivalentDoseRate.Parse("1 mSv/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillisievertsPerHour, MillisievertsPerHourTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.MillisievertPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationEquivalentDoseRate.Parse("1 мЗв/ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MillisievertsPerHour, MillisievertsPerHourTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.MillisievertPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationEquivalentDoseRate.Parse("1 mSv/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillisievertsPerSecond, MillisievertsPerSecondTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.MillisievertPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationEquivalentDoseRate.Parse("1 мЗв/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MillisievertsPerSecond, MillisievertsPerSecondTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.MillisievertPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationEquivalentDoseRate.Parse("1 nSv/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanosievertsPerHour, NanosievertsPerHourTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.NanosievertPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationEquivalentDoseRate.Parse("1 нЗв/ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.NanosievertsPerHour, NanosievertsPerHourTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.NanosievertPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationEquivalentDoseRate.Parse("1 nSv/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanosievertsPerSecond, NanosievertsPerSecondTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.NanosievertPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationEquivalentDoseRate.Parse("1 нЗв/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.NanosievertsPerSecond, NanosievertsPerSecondTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.NanosievertPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationEquivalentDoseRate.Parse("1 rem/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.RoentgensEquivalentManPerHour, RoentgensEquivalentManPerHourTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.RoentgenEquivalentManPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationEquivalentDoseRate.Parse("1 Sv/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SievertsPerHour, SievertsPerHourTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.SievertPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationEquivalentDoseRate.Parse("1 Зв/ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.SievertsPerHour, SievertsPerHourTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.SievertPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationEquivalentDoseRate.Parse("1 Sv/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SievertsPerSecond, SievertsPerSecondTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.SievertPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationEquivalentDoseRate.Parse("1 Зв/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.SievertsPerSecond, SievertsPerSecondTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.SievertPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = RadiationEquivalentDoseRate.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 µSv/h", RadiationEquivalentDoseRateUnit.MicrosievertPerHour, 4.2)] + [InlineData("en-US", "4.2 µSv/s", RadiationEquivalentDoseRateUnit.MicrosievertPerSecond, 4.2)] + [InlineData("en-US", "4.2 mrem/h", RadiationEquivalentDoseRateUnit.MilliroentgenEquivalentManPerHour, 4.2)] + [InlineData("en-US", "4.2 mSv/h", RadiationEquivalentDoseRateUnit.MillisievertPerHour, 4.2)] + [InlineData("en-US", "4.2 mSv/s", RadiationEquivalentDoseRateUnit.MillisievertPerSecond, 4.2)] + [InlineData("en-US", "4.2 nSv/h", RadiationEquivalentDoseRateUnit.NanosievertPerHour, 4.2)] + [InlineData("en-US", "4.2 nSv/s", RadiationEquivalentDoseRateUnit.NanosievertPerSecond, 4.2)] + [InlineData("en-US", "4.2 rem/h", RadiationEquivalentDoseRateUnit.RoentgenEquivalentManPerHour, 4.2)] + [InlineData("en-US", "4.2 Sv/h", RadiationEquivalentDoseRateUnit.SievertPerHour, 4.2)] + [InlineData("en-US", "4.2 Sv/s", RadiationEquivalentDoseRateUnit.SievertPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 мкЗв/ч", RadiationEquivalentDoseRateUnit.MicrosievertPerHour, 4.2)] + [InlineData("ru-RU", "4,2 мкЗв/с", RadiationEquivalentDoseRateUnit.MicrosievertPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 мЗв/ч", RadiationEquivalentDoseRateUnit.MillisievertPerHour, 4.2)] + [InlineData("ru-RU", "4,2 мЗв/с", RadiationEquivalentDoseRateUnit.MillisievertPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 нЗв/ч", RadiationEquivalentDoseRateUnit.NanosievertPerHour, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(RadiationEquivalentDoseRate.TryParse("1 µSv/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrosievertsPerHour, MicrosievertsPerHourTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.MicrosievertPerHour, parsed.Unit); - } - - { - Assert.True(RadiationEquivalentDoseRate.TryParse("1 мкЗв/ч", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrosievertsPerHour, MicrosievertsPerHourTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.MicrosievertPerHour, parsed.Unit); - } - - { - Assert.True(RadiationEquivalentDoseRate.TryParse("1 µSv/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrosievertsPerSecond, MicrosievertsPerSecondTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.MicrosievertPerSecond, parsed.Unit); - } - - { - Assert.True(RadiationEquivalentDoseRate.TryParse("1 мкЗв/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrosievertsPerSecond, MicrosievertsPerSecondTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.MicrosievertPerSecond, parsed.Unit); - } - - { - Assert.True(RadiationEquivalentDoseRate.TryParse("1 mrem/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilliroentgensEquivalentManPerHour, MilliroentgensEquivalentManPerHourTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.MilliroentgenEquivalentManPerHour, parsed.Unit); - } - - { - Assert.True(RadiationEquivalentDoseRate.TryParse("1 mSv/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillisievertsPerHour, MillisievertsPerHourTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.MillisievertPerHour, parsed.Unit); - } - - { - Assert.True(RadiationEquivalentDoseRate.TryParse("1 мЗв/ч", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillisievertsPerHour, MillisievertsPerHourTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.MillisievertPerHour, parsed.Unit); - } - - { - Assert.True(RadiationEquivalentDoseRate.TryParse("1 mSv/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillisievertsPerSecond, MillisievertsPerSecondTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.MillisievertPerSecond, parsed.Unit); - } - - { - Assert.True(RadiationEquivalentDoseRate.TryParse("1 мЗв/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillisievertsPerSecond, MillisievertsPerSecondTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.MillisievertPerSecond, parsed.Unit); - } - - { - Assert.True(RadiationEquivalentDoseRate.TryParse("1 nSv/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanosievertsPerHour, NanosievertsPerHourTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.NanosievertPerHour, parsed.Unit); - } - - { - Assert.True(RadiationEquivalentDoseRate.TryParse("1 нЗв/ч", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanosievertsPerHour, NanosievertsPerHourTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.NanosievertPerHour, parsed.Unit); - } - - { - Assert.True(RadiationEquivalentDoseRate.TryParse("1 nSv/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanosievertsPerSecond, NanosievertsPerSecondTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.NanosievertPerSecond, parsed.Unit); - } - - { - Assert.True(RadiationEquivalentDoseRate.TryParse("1 нЗв/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanosievertsPerSecond, NanosievertsPerSecondTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.NanosievertPerSecond, parsed.Unit); - } - - { - Assert.True(RadiationEquivalentDoseRate.TryParse("1 rem/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.RoentgensEquivalentManPerHour, RoentgensEquivalentManPerHourTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.RoentgenEquivalentManPerHour, parsed.Unit); - } - - { - Assert.True(RadiationEquivalentDoseRate.TryParse("1 Sv/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SievertsPerHour, SievertsPerHourTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.SievertPerHour, parsed.Unit); - } - - { - Assert.True(RadiationEquivalentDoseRate.TryParse("1 Зв/ч", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SievertsPerHour, SievertsPerHourTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.SievertPerHour, parsed.Unit); - } - - { - Assert.True(RadiationEquivalentDoseRate.TryParse("1 Sv/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SievertsPerSecond, SievertsPerSecondTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.SievertPerSecond, parsed.Unit); - } - - { - Assert.True(RadiationEquivalentDoseRate.TryParse("1 Зв/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SievertsPerSecond, SievertsPerSecondTolerance); - Assert.Equal(RadiationEquivalentDoseRateUnit.SievertPerSecond, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(RadiationEquivalentDoseRate.TryParse(quantityString, out RadiationEquivalentDoseRate parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -779,6 +607,44 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Radiat Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", RadiationEquivalentDoseRateUnit.MicrosievertPerHour, "µSv/h")] + [InlineData("en-US", RadiationEquivalentDoseRateUnit.MicrosievertPerSecond, "µSv/s")] + [InlineData("en-US", RadiationEquivalentDoseRateUnit.MilliroentgenEquivalentManPerHour, "mrem/h")] + [InlineData("en-US", RadiationEquivalentDoseRateUnit.MillisievertPerHour, "mSv/h")] + [InlineData("en-US", RadiationEquivalentDoseRateUnit.MillisievertPerSecond, "mSv/s")] + [InlineData("en-US", RadiationEquivalentDoseRateUnit.NanosievertPerHour, "nSv/h")] + [InlineData("en-US", RadiationEquivalentDoseRateUnit.NanosievertPerSecond, "nSv/s")] + [InlineData("en-US", RadiationEquivalentDoseRateUnit.RoentgenEquivalentManPerHour, "rem/h")] + [InlineData("en-US", RadiationEquivalentDoseRateUnit.SievertPerHour, "Sv/h")] + [InlineData("en-US", RadiationEquivalentDoseRateUnit.SievertPerSecond, "Sv/s")] + [InlineData("ru-RU", RadiationEquivalentDoseRateUnit.MicrosievertPerHour, "мкЗв/ч")] + [InlineData("ru-RU", RadiationEquivalentDoseRateUnit.MicrosievertPerSecond, "мкЗв/с")] + [InlineData("ru-RU", RadiationEquivalentDoseRateUnit.MillisievertPerHour, "мЗв/ч")] + [InlineData("ru-RU", RadiationEquivalentDoseRateUnit.MillisievertPerSecond, "мЗв/с")] + [InlineData("ru-RU", RadiationEquivalentDoseRateUnit.NanosievertPerHour, "нЗв/ч")] + [InlineData("ru-RU", RadiationEquivalentDoseRateUnit.NanosievertPerSecond, "нЗв/с")] + [InlineData("ru-RU", RadiationEquivalentDoseRateUnit.SievertPerHour, "Зв/ч")] + [InlineData("ru-RU", RadiationEquivalentDoseRateUnit.SievertPerSecond, "Зв/с")] + public void GetAbbreviationForCulture(string culture, RadiationEquivalentDoseRateUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = RadiationEquivalentDoseRate.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(RadiationEquivalentDoseRate.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = RadiationEquivalentDoseRate.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(RadiationEquivalentDoseRateUnit unit) @@ -809,6 +675,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); }); } @@ -832,41 +699,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] @@ -912,8 +781,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); @@ -951,34 +818,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = RadiationEquivalentDoseRate.FromSievertsPerSecond(1); - Assert.True(v.Equals(RadiationEquivalentDoseRate.FromSievertsPerSecond(1), SievertsPerSecondTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(RadiationEquivalentDoseRate.Zero, SievertsPerSecondTolerance, ComparisonType.Relative)); - Assert.True(RadiationEquivalentDoseRate.FromSievertsPerSecond(100).Equals(RadiationEquivalentDoseRate.FromSievertsPerSecond(120), 0.3, ComparisonType.Relative)); - Assert.False(RadiationEquivalentDoseRate.FromSievertsPerSecond(100).Equals(RadiationEquivalentDoseRate.FromSievertsPerSecond(120), 0.1, ComparisonType.Relative)); + RadiationEquivalentDoseRate sievertpersecond = RadiationEquivalentDoseRate.FromSievertsPerSecond(1); + Assert.False(sievertpersecond.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = RadiationEquivalentDoseRate.FromSievertsPerSecond(1); - Assert.Throws(() => v.Equals(RadiationEquivalentDoseRate.FromSievertsPerSecond(1), -1, ComparisonType.Relative)); + RadiationEquivalentDoseRate sievertpersecond = RadiationEquivalentDoseRate.FromSievertsPerSecond(1); + Assert.False(sievertpersecond.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - RadiationEquivalentDoseRate sievertpersecond = RadiationEquivalentDoseRate.FromSievertsPerSecond(1); - Assert.False(sievertpersecond.Equals(new object())); + var quantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(firstValue); + var otherQuantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(secondValue); + RadiationEquivalentDoseRate maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - RadiationEquivalentDoseRate sievertpersecond = RadiationEquivalentDoseRate.FromSievertsPerSecond(1); - Assert.False(sievertpersecond.Equals(null)); + var quantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(1); + var negativeTolerance = RadiationEquivalentDoseRate.FromSievertsPerSecond(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -997,6 +873,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() { @@ -1073,158 +961,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(RadiationEquivalentDoseRate))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(RadiationEquivalentDoseRateUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(1.0); - Assert.Equal(RadiationEquivalentDoseRate.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(1.0); - Assert.Equal(RadiationEquivalentDoseRate.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(1.0); - Assert.Equal(new {RadiationEquivalentDoseRate.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 0d59a27966..02b698dc78 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RadiationEquivalentDoseTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RadiationEquivalentDoseTestsBase.g.cs @@ -116,7 +116,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new RadiationEquivalentDose(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -129,15 +129,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void RadiationEquivalentDose_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + RadiationEquivalentDoseUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new RadiationEquivalentDose(1, RadiationEquivalentDoseUnit.Sievert); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(RadiationEquivalentDose.Zero, quantityInfo.Zero); Assert.Equal("RadiationEquivalentDose", quantityInfo.Name); + Assert.Equal(RadiationEquivalentDose.Zero, quantityInfo.Zero); + Assert.Equal(RadiationEquivalentDose.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(RadiationEquivalentDose.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -156,27 +174,27 @@ public void SievertToRadiationEquivalentDoseUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = RadiationEquivalentDose.From(1, RadiationEquivalentDoseUnit.Microsievert); - AssertEx.EqualTolerance(1, quantity00.Microsieverts, MicrosievertsTolerance); + Assert.Equal(1, quantity00.Microsieverts); Assert.Equal(RadiationEquivalentDoseUnit.Microsievert, quantity00.Unit); var quantity01 = RadiationEquivalentDose.From(1, RadiationEquivalentDoseUnit.MilliroentgenEquivalentMan); - AssertEx.EqualTolerance(1, quantity01.MilliroentgensEquivalentMan, MilliroentgensEquivalentManTolerance); + Assert.Equal(1, quantity01.MilliroentgensEquivalentMan); Assert.Equal(RadiationEquivalentDoseUnit.MilliroentgenEquivalentMan, quantity01.Unit); var quantity02 = RadiationEquivalentDose.From(1, RadiationEquivalentDoseUnit.Millisievert); - AssertEx.EqualTolerance(1, quantity02.Millisieverts, MillisievertsTolerance); + Assert.Equal(1, quantity02.Millisieverts); Assert.Equal(RadiationEquivalentDoseUnit.Millisievert, quantity02.Unit); var quantity03 = RadiationEquivalentDose.From(1, RadiationEquivalentDoseUnit.Nanosievert); - AssertEx.EqualTolerance(1, quantity03.Nanosieverts, NanosievertsTolerance); + Assert.Equal(1, quantity03.Nanosieverts); Assert.Equal(RadiationEquivalentDoseUnit.Nanosievert, quantity03.Unit); var quantity04 = RadiationEquivalentDose.From(1, RadiationEquivalentDoseUnit.RoentgenEquivalentMan); - AssertEx.EqualTolerance(1, quantity04.RoentgensEquivalentMan, RoentgensEquivalentManTolerance); + Assert.Equal(1, quantity04.RoentgensEquivalentMan); Assert.Equal(RadiationEquivalentDoseUnit.RoentgenEquivalentMan, quantity04.Unit); var quantity05 = RadiationEquivalentDose.From(1, RadiationEquivalentDoseUnit.Sievert); - AssertEx.EqualTolerance(1, quantity05.Sieverts, SievertsTolerance); + Assert.Equal(1, quantity05.Sieverts); Assert.Equal(RadiationEquivalentDoseUnit.Sievert, quantity05.Unit); } @@ -317,144 +335,42 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 µSv", RadiationEquivalentDoseUnit.Microsievert, 4.2)] + [InlineData("en-US", "4.2 mrem", RadiationEquivalentDoseUnit.MilliroentgenEquivalentMan, 4.2)] + [InlineData("en-US", "4.2 mSv", RadiationEquivalentDoseUnit.Millisievert, 4.2)] + [InlineData("en-US", "4.2 nSv", RadiationEquivalentDoseUnit.Nanosievert, 4.2)] + [InlineData("en-US", "4.2 rem", RadiationEquivalentDoseUnit.RoentgenEquivalentMan, 4.2)] + [InlineData("en-US", "4.2 Sv", RadiationEquivalentDoseUnit.Sievert, 4.2)] + [InlineData("ru-RU", "4,2 мкЗв", RadiationEquivalentDoseUnit.Microsievert, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = RadiationEquivalentDose.Parse("1 µSv", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microsieverts, MicrosievertsTolerance); - Assert.Equal(RadiationEquivalentDoseUnit.Microsievert, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationEquivalentDose.Parse("1 мкЗв", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Microsieverts, MicrosievertsTolerance); - Assert.Equal(RadiationEquivalentDoseUnit.Microsievert, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationEquivalentDose.Parse("1 mrem", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilliroentgensEquivalentMan, MilliroentgensEquivalentManTolerance); - Assert.Equal(RadiationEquivalentDoseUnit.MilliroentgenEquivalentMan, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationEquivalentDose.Parse("1 mSv", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millisieverts, MillisievertsTolerance); - Assert.Equal(RadiationEquivalentDoseUnit.Millisievert, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationEquivalentDose.Parse("1 мЗв", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Millisieverts, MillisievertsTolerance); - Assert.Equal(RadiationEquivalentDoseUnit.Millisievert, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationEquivalentDose.Parse("1 nSv", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanosieverts, NanosievertsTolerance); - Assert.Equal(RadiationEquivalentDoseUnit.Nanosievert, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationEquivalentDose.Parse("1 нЗв", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Nanosieverts, NanosievertsTolerance); - Assert.Equal(RadiationEquivalentDoseUnit.Nanosievert, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationEquivalentDose.Parse("1 rem", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.RoentgensEquivalentMan, RoentgensEquivalentManTolerance); - Assert.Equal(RadiationEquivalentDoseUnit.RoentgenEquivalentMan, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationEquivalentDose.Parse("1 Sv", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Sieverts, SievertsTolerance); - Assert.Equal(RadiationEquivalentDoseUnit.Sievert, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationEquivalentDose.Parse("1 Зв", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Sieverts, SievertsTolerance); - Assert.Equal(RadiationEquivalentDoseUnit.Sievert, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = RadiationEquivalentDose.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 µSv", RadiationEquivalentDoseUnit.Microsievert, 4.2)] + [InlineData("en-US", "4.2 mrem", RadiationEquivalentDoseUnit.MilliroentgenEquivalentMan, 4.2)] + [InlineData("en-US", "4.2 mSv", RadiationEquivalentDoseUnit.Millisievert, 4.2)] + [InlineData("en-US", "4.2 nSv", RadiationEquivalentDoseUnit.Nanosievert, 4.2)] + [InlineData("en-US", "4.2 rem", RadiationEquivalentDoseUnit.RoentgenEquivalentMan, 4.2)] + [InlineData("en-US", "4.2 Sv", RadiationEquivalentDoseUnit.Sievert, 4.2)] + [InlineData("ru-RU", "4,2 мкЗв", RadiationEquivalentDoseUnit.Microsievert, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(RadiationEquivalentDose.TryParse("1 µSv", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microsieverts, MicrosievertsTolerance); - Assert.Equal(RadiationEquivalentDoseUnit.Microsievert, parsed.Unit); - } - - { - Assert.True(RadiationEquivalentDose.TryParse("1 мкЗв", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microsieverts, MicrosievertsTolerance); - Assert.Equal(RadiationEquivalentDoseUnit.Microsievert, parsed.Unit); - } - - { - Assert.True(RadiationEquivalentDose.TryParse("1 mrem", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilliroentgensEquivalentMan, MilliroentgensEquivalentManTolerance); - Assert.Equal(RadiationEquivalentDoseUnit.MilliroentgenEquivalentMan, parsed.Unit); - } - - { - Assert.True(RadiationEquivalentDose.TryParse("1 mSv", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Millisieverts, MillisievertsTolerance); - Assert.Equal(RadiationEquivalentDoseUnit.Millisievert, parsed.Unit); - } - - { - Assert.True(RadiationEquivalentDose.TryParse("1 мЗв", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Millisieverts, MillisievertsTolerance); - Assert.Equal(RadiationEquivalentDoseUnit.Millisievert, parsed.Unit); - } - - { - Assert.True(RadiationEquivalentDose.TryParse("1 nSv", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanosieverts, NanosievertsTolerance); - Assert.Equal(RadiationEquivalentDoseUnit.Nanosievert, parsed.Unit); - } - - { - Assert.True(RadiationEquivalentDose.TryParse("1 нЗв", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanosieverts, NanosievertsTolerance); - Assert.Equal(RadiationEquivalentDoseUnit.Nanosievert, parsed.Unit); - } - - { - Assert.True(RadiationEquivalentDose.TryParse("1 rem", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.RoentgensEquivalentMan, RoentgensEquivalentManTolerance); - Assert.Equal(RadiationEquivalentDoseUnit.RoentgenEquivalentMan, parsed.Unit); - } - - { - Assert.True(RadiationEquivalentDose.TryParse("1 Sv", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Sieverts, SievertsTolerance); - Assert.Equal(RadiationEquivalentDoseUnit.Sievert, parsed.Unit); - } - - { - Assert.True(RadiationEquivalentDose.TryParse("1 Зв", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Sieverts, SievertsTolerance); - Assert.Equal(RadiationEquivalentDoseUnit.Sievert, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(RadiationEquivalentDose.TryParse(quantityString, out RadiationEquivalentDose parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -587,6 +503,36 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Radiat Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", RadiationEquivalentDoseUnit.Microsievert, "µSv")] + [InlineData("en-US", RadiationEquivalentDoseUnit.MilliroentgenEquivalentMan, "mrem")] + [InlineData("en-US", RadiationEquivalentDoseUnit.Millisievert, "mSv")] + [InlineData("en-US", RadiationEquivalentDoseUnit.Nanosievert, "nSv")] + [InlineData("en-US", RadiationEquivalentDoseUnit.RoentgenEquivalentMan, "rem")] + [InlineData("en-US", RadiationEquivalentDoseUnit.Sievert, "Sv")] + [InlineData("ru-RU", RadiationEquivalentDoseUnit.Microsievert, "мкЗв")] + [InlineData("ru-RU", RadiationEquivalentDoseUnit.Millisievert, "мЗв")] + [InlineData("ru-RU", RadiationEquivalentDoseUnit.Nanosievert, "нЗв")] + [InlineData("ru-RU", RadiationEquivalentDoseUnit.Sievert, "Зв")] + public void GetAbbreviationForCulture(string culture, RadiationEquivalentDoseUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = RadiationEquivalentDose.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(RadiationEquivalentDose.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = RadiationEquivalentDose.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(RadiationEquivalentDoseUnit unit) @@ -617,6 +563,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); }); } @@ -640,37 +587,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] @@ -716,8 +665,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); @@ -755,34 +702,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = RadiationEquivalentDose.FromSieverts(1); - Assert.True(v.Equals(RadiationEquivalentDose.FromSieverts(1), SievertsTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(RadiationEquivalentDose.Zero, SievertsTolerance, ComparisonType.Relative)); - Assert.True(RadiationEquivalentDose.FromSieverts(100).Equals(RadiationEquivalentDose.FromSieverts(120), 0.3, ComparisonType.Relative)); - Assert.False(RadiationEquivalentDose.FromSieverts(100).Equals(RadiationEquivalentDose.FromSieverts(120), 0.1, ComparisonType.Relative)); + RadiationEquivalentDose sievert = RadiationEquivalentDose.FromSieverts(1); + Assert.False(sievert.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = RadiationEquivalentDose.FromSieverts(1); - Assert.Throws(() => v.Equals(RadiationEquivalentDose.FromSieverts(1), -1, ComparisonType.Relative)); + RadiationEquivalentDose sievert = RadiationEquivalentDose.FromSieverts(1); + Assert.False(sievert.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - RadiationEquivalentDose sievert = RadiationEquivalentDose.FromSieverts(1); - Assert.False(sievert.Equals(new object())); + var quantity = RadiationEquivalentDose.FromSieverts(firstValue); + var otherQuantity = RadiationEquivalentDose.FromSieverts(secondValue); + RadiationEquivalentDose maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - RadiationEquivalentDose sievert = RadiationEquivalentDose.FromSieverts(1); - Assert.False(sievert.Equals(null)); + var quantity = RadiationEquivalentDose.FromSieverts(1); + var negativeTolerance = RadiationEquivalentDose.FromSieverts(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -801,6 +757,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() { @@ -869,158 +837,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = RadiationEquivalentDose.FromSieverts(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = RadiationEquivalentDose.FromSieverts(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = RadiationEquivalentDose.FromSieverts(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = RadiationEquivalentDose.FromSieverts(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = RadiationEquivalentDose.FromSieverts(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = RadiationEquivalentDose.FromSieverts(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = RadiationEquivalentDose.FromSieverts(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = RadiationEquivalentDose.FromSieverts(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = RadiationEquivalentDose.FromSieverts(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = RadiationEquivalentDose.FromSieverts(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = RadiationEquivalentDose.FromSieverts(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = RadiationEquivalentDose.FromSieverts(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = RadiationEquivalentDose.FromSieverts(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = RadiationEquivalentDose.FromSieverts(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = RadiationEquivalentDose.FromSieverts(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = RadiationEquivalentDose.FromSieverts(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(RadiationEquivalentDose))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = RadiationEquivalentDose.FromSieverts(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(RadiationEquivalentDoseUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = RadiationEquivalentDose.FromSieverts(1.0); - Assert.Equal(RadiationEquivalentDose.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = RadiationEquivalentDose.FromSieverts(1.0); - Assert.Equal(RadiationEquivalentDose.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = RadiationEquivalentDose.FromSieverts(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = RadiationEquivalentDose.FromSieverts(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = RadiationEquivalentDose.FromSieverts(1.0); - Assert.Equal(new {RadiationEquivalentDose.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 0ef0e16bc9..ba23e5b515 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RadiationExposureTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RadiationExposureTestsBase.g.cs @@ -124,7 +124,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new RadiationExposure(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -137,15 +137,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void RadiationExposure_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + RadiationExposureUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new RadiationExposure(1, RadiationExposureUnit.CoulombPerKilogram); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(RadiationExposure.Zero, quantityInfo.Zero); Assert.Equal("RadiationExposure", quantityInfo.Name); + Assert.Equal(RadiationExposure.Zero, quantityInfo.Zero); + Assert.Equal(RadiationExposure.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(RadiationExposure.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -166,35 +184,35 @@ public void CoulombPerKilogramToRadiationExposureUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = RadiationExposure.From(1, RadiationExposureUnit.CoulombPerKilogram); - AssertEx.EqualTolerance(1, quantity00.CoulombsPerKilogram, CoulombsPerKilogramTolerance); + Assert.Equal(1, quantity00.CoulombsPerKilogram); Assert.Equal(RadiationExposureUnit.CoulombPerKilogram, quantity00.Unit); var quantity01 = RadiationExposure.From(1, RadiationExposureUnit.MicrocoulombPerKilogram); - AssertEx.EqualTolerance(1, quantity01.MicrocoulombsPerKilogram, MicrocoulombsPerKilogramTolerance); + Assert.Equal(1, quantity01.MicrocoulombsPerKilogram); Assert.Equal(RadiationExposureUnit.MicrocoulombPerKilogram, quantity01.Unit); var quantity02 = RadiationExposure.From(1, RadiationExposureUnit.Microroentgen); - AssertEx.EqualTolerance(1, quantity02.Microroentgens, MicroroentgensTolerance); + Assert.Equal(1, quantity02.Microroentgens); Assert.Equal(RadiationExposureUnit.Microroentgen, quantity02.Unit); var quantity03 = RadiationExposure.From(1, RadiationExposureUnit.MillicoulombPerKilogram); - AssertEx.EqualTolerance(1, quantity03.MillicoulombsPerKilogram, MillicoulombsPerKilogramTolerance); + Assert.Equal(1, quantity03.MillicoulombsPerKilogram); Assert.Equal(RadiationExposureUnit.MillicoulombPerKilogram, quantity03.Unit); var quantity04 = RadiationExposure.From(1, RadiationExposureUnit.Milliroentgen); - AssertEx.EqualTolerance(1, quantity04.Milliroentgens, MilliroentgensTolerance); + Assert.Equal(1, quantity04.Milliroentgens); Assert.Equal(RadiationExposureUnit.Milliroentgen, quantity04.Unit); var quantity05 = RadiationExposure.From(1, RadiationExposureUnit.NanocoulombPerKilogram); - AssertEx.EqualTolerance(1, quantity05.NanocoulombsPerKilogram, NanocoulombsPerKilogramTolerance); + Assert.Equal(1, quantity05.NanocoulombsPerKilogram); Assert.Equal(RadiationExposureUnit.NanocoulombPerKilogram, quantity05.Unit); var quantity06 = RadiationExposure.From(1, RadiationExposureUnit.PicocoulombPerKilogram); - AssertEx.EqualTolerance(1, quantity06.PicocoulombsPerKilogram, PicocoulombsPerKilogramTolerance); + Assert.Equal(1, quantity06.PicocoulombsPerKilogram); Assert.Equal(RadiationExposureUnit.PicocoulombPerKilogram, quantity06.Unit); var quantity07 = RadiationExposure.From(1, RadiationExposureUnit.Roentgen); - AssertEx.EqualTolerance(1, quantity07.Roentgens, RoentgensTolerance); + Assert.Equal(1, quantity07.Roentgens); Assert.Equal(RadiationExposureUnit.Roentgen, quantity07.Unit); } @@ -337,118 +355,38 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 C/kg", RadiationExposureUnit.CoulombPerKilogram, 4.2)] + [InlineData("en-US", "4.2 µC/kg", RadiationExposureUnit.MicrocoulombPerKilogram, 4.2)] + [InlineData("en-US", "4.2 µR", RadiationExposureUnit.Microroentgen, 4.2)] + [InlineData("en-US", "4.2 mC/kg", RadiationExposureUnit.MillicoulombPerKilogram, 4.2)] + [InlineData("en-US", "4.2 mR", RadiationExposureUnit.Milliroentgen, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = RadiationExposure.Parse("1 C/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CoulombsPerKilogram, CoulombsPerKilogramTolerance); - Assert.Equal(RadiationExposureUnit.CoulombPerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationExposure.Parse("1 µC/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrocoulombsPerKilogram, MicrocoulombsPerKilogramTolerance); - Assert.Equal(RadiationExposureUnit.MicrocoulombPerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationExposure.Parse("1 µR", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microroentgens, MicroroentgensTolerance); - Assert.Equal(RadiationExposureUnit.Microroentgen, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationExposure.Parse("1 mC/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillicoulombsPerKilogram, MillicoulombsPerKilogramTolerance); - Assert.Equal(RadiationExposureUnit.MillicoulombPerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationExposure.Parse("1 mR", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Milliroentgens, MilliroentgensTolerance); - Assert.Equal(RadiationExposureUnit.Milliroentgen, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationExposure.Parse("1 nC/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanocoulombsPerKilogram, NanocoulombsPerKilogramTolerance); - Assert.Equal(RadiationExposureUnit.NanocoulombPerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationExposure.Parse("1 pC/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PicocoulombsPerKilogram, PicocoulombsPerKilogramTolerance); - Assert.Equal(RadiationExposureUnit.PicocoulombPerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RadiationExposure.Parse("1 R", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Roentgens, RoentgensTolerance); - Assert.Equal(RadiationExposureUnit.Roentgen, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = RadiationExposure.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 C/kg", RadiationExposureUnit.CoulombPerKilogram, 4.2)] + [InlineData("en-US", "4.2 µC/kg", RadiationExposureUnit.MicrocoulombPerKilogram, 4.2)] + [InlineData("en-US", "4.2 µR", RadiationExposureUnit.Microroentgen, 4.2)] + [InlineData("en-US", "4.2 mC/kg", RadiationExposureUnit.MillicoulombPerKilogram, 4.2)] + [InlineData("en-US", "4.2 mR", RadiationExposureUnit.Milliroentgen, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(RadiationExposure.TryParse("1 C/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CoulombsPerKilogram, CoulombsPerKilogramTolerance); - Assert.Equal(RadiationExposureUnit.CoulombPerKilogram, parsed.Unit); - } - - { - Assert.True(RadiationExposure.TryParse("1 µC/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrocoulombsPerKilogram, MicrocoulombsPerKilogramTolerance); - Assert.Equal(RadiationExposureUnit.MicrocoulombPerKilogram, parsed.Unit); - } - - { - Assert.True(RadiationExposure.TryParse("1 µR", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microroentgens, MicroroentgensTolerance); - Assert.Equal(RadiationExposureUnit.Microroentgen, parsed.Unit); - } - - { - Assert.True(RadiationExposure.TryParse("1 mC/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillicoulombsPerKilogram, MillicoulombsPerKilogramTolerance); - Assert.Equal(RadiationExposureUnit.MillicoulombPerKilogram, parsed.Unit); - } - - { - Assert.True(RadiationExposure.TryParse("1 mR", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Milliroentgens, MilliroentgensTolerance); - Assert.Equal(RadiationExposureUnit.Milliroentgen, parsed.Unit); - } - - { - Assert.True(RadiationExposure.TryParse("1 nC/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanocoulombsPerKilogram, NanocoulombsPerKilogramTolerance); - Assert.Equal(RadiationExposureUnit.NanocoulombPerKilogram, parsed.Unit); - } - - { - Assert.True(RadiationExposure.TryParse("1 pC/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PicocoulombsPerKilogram, PicocoulombsPerKilogramTolerance); - Assert.Equal(RadiationExposureUnit.PicocoulombPerKilogram, parsed.Unit); - } - - { - Assert.True(RadiationExposure.TryParse("1 R", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Roentgens, RoentgensTolerance); - Assert.Equal(RadiationExposureUnit.Roentgen, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(RadiationExposure.TryParse(quantityString, out RadiationExposure parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -581,6 +519,34 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Radiat Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", RadiationExposureUnit.CoulombPerKilogram, "C/kg")] + [InlineData("en-US", RadiationExposureUnit.MicrocoulombPerKilogram, "µC/kg")] + [InlineData("en-US", RadiationExposureUnit.Microroentgen, "µR")] + [InlineData("en-US", RadiationExposureUnit.MillicoulombPerKilogram, "mC/kg")] + [InlineData("en-US", RadiationExposureUnit.Milliroentgen, "mR")] + [InlineData("en-US", RadiationExposureUnit.NanocoulombPerKilogram, "nC/kg")] + [InlineData("en-US", RadiationExposureUnit.PicocoulombPerKilogram, "pC/kg")] + [InlineData("en-US", RadiationExposureUnit.Roentgen, "R")] + public void GetAbbreviationForCulture(string culture, RadiationExposureUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = RadiationExposure.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(RadiationExposure.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = RadiationExposure.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(RadiationExposureUnit unit) @@ -611,6 +577,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); }); } @@ -634,39 +601,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] @@ -712,8 +681,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); @@ -751,34 +718,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = RadiationExposure.FromCoulombsPerKilogram(1); - Assert.True(v.Equals(RadiationExposure.FromCoulombsPerKilogram(1), CoulombsPerKilogramTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(RadiationExposure.Zero, CoulombsPerKilogramTolerance, ComparisonType.Relative)); - Assert.True(RadiationExposure.FromCoulombsPerKilogram(100).Equals(RadiationExposure.FromCoulombsPerKilogram(120), 0.3, ComparisonType.Relative)); - Assert.False(RadiationExposure.FromCoulombsPerKilogram(100).Equals(RadiationExposure.FromCoulombsPerKilogram(120), 0.1, ComparisonType.Relative)); + RadiationExposure coulombperkilogram = RadiationExposure.FromCoulombsPerKilogram(1); + Assert.False(coulombperkilogram.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = RadiationExposure.FromCoulombsPerKilogram(1); - Assert.Throws(() => v.Equals(RadiationExposure.FromCoulombsPerKilogram(1), -1, ComparisonType.Relative)); + RadiationExposure coulombperkilogram = RadiationExposure.FromCoulombsPerKilogram(1); + Assert.False(coulombperkilogram.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - RadiationExposure coulombperkilogram = RadiationExposure.FromCoulombsPerKilogram(1); - Assert.False(coulombperkilogram.Equals(new object())); + var quantity = RadiationExposure.FromCoulombsPerKilogram(firstValue); + var otherQuantity = RadiationExposure.FromCoulombsPerKilogram(secondValue); + RadiationExposure maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - RadiationExposure coulombperkilogram = RadiationExposure.FromCoulombsPerKilogram(1); - Assert.False(coulombperkilogram.Equals(null)); + var quantity = RadiationExposure.FromCoulombsPerKilogram(1); + var negativeTolerance = RadiationExposure.FromCoulombsPerKilogram(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -797,6 +773,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() { @@ -869,158 +857,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = RadiationExposure.FromCoulombsPerKilogram(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = RadiationExposure.FromCoulombsPerKilogram(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = RadiationExposure.FromCoulombsPerKilogram(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = RadiationExposure.FromCoulombsPerKilogram(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = RadiationExposure.FromCoulombsPerKilogram(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = RadiationExposure.FromCoulombsPerKilogram(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = RadiationExposure.FromCoulombsPerKilogram(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = RadiationExposure.FromCoulombsPerKilogram(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = RadiationExposure.FromCoulombsPerKilogram(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = RadiationExposure.FromCoulombsPerKilogram(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = RadiationExposure.FromCoulombsPerKilogram(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = RadiationExposure.FromCoulombsPerKilogram(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = RadiationExposure.FromCoulombsPerKilogram(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = RadiationExposure.FromCoulombsPerKilogram(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = RadiationExposure.FromCoulombsPerKilogram(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = RadiationExposure.FromCoulombsPerKilogram(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(RadiationExposure))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = RadiationExposure.FromCoulombsPerKilogram(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(RadiationExposureUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = RadiationExposure.FromCoulombsPerKilogram(1.0); - Assert.Equal(RadiationExposure.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = RadiationExposure.FromCoulombsPerKilogram(1.0); - Assert.Equal(RadiationExposure.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = RadiationExposure.FromCoulombsPerKilogram(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = RadiationExposure.FromCoulombsPerKilogram(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = RadiationExposure.FromCoulombsPerKilogram(1.0); - Assert.Equal(new {RadiationExposure.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 7503c02822..06f8b48b7a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RadioactivityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RadioactivityTestsBase.g.cs @@ -208,7 +208,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Radioactivity(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -221,15 +221,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Radioactivity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + RadioactivityUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Radioactivity(1, RadioactivityUnit.Becquerel); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Radioactivity.Zero, quantityInfo.Zero); Assert.Equal("Radioactivity", quantityInfo.Name); + Assert.Equal(Radioactivity.Zero, quantityInfo.Zero); + Assert.Equal(Radioactivity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Radioactivity.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -271,119 +289,119 @@ public void BecquerelToRadioactivityUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Radioactivity.From(1, RadioactivityUnit.Becquerel); - AssertEx.EqualTolerance(1, quantity00.Becquerels, BecquerelsTolerance); + Assert.Equal(1, quantity00.Becquerels); Assert.Equal(RadioactivityUnit.Becquerel, quantity00.Unit); var quantity01 = Radioactivity.From(1, RadioactivityUnit.Curie); - AssertEx.EqualTolerance(1, quantity01.Curies, CuriesTolerance); + Assert.Equal(1, quantity01.Curies); Assert.Equal(RadioactivityUnit.Curie, quantity01.Unit); var quantity02 = Radioactivity.From(1, RadioactivityUnit.Exabecquerel); - AssertEx.EqualTolerance(1, quantity02.Exabecquerels, ExabecquerelsTolerance); + Assert.Equal(1, quantity02.Exabecquerels); Assert.Equal(RadioactivityUnit.Exabecquerel, quantity02.Unit); var quantity03 = Radioactivity.From(1, RadioactivityUnit.Gigabecquerel); - AssertEx.EqualTolerance(1, quantity03.Gigabecquerels, GigabecquerelsTolerance); + Assert.Equal(1, quantity03.Gigabecquerels); Assert.Equal(RadioactivityUnit.Gigabecquerel, quantity03.Unit); var quantity04 = Radioactivity.From(1, RadioactivityUnit.Gigacurie); - AssertEx.EqualTolerance(1, quantity04.Gigacuries, GigacuriesTolerance); + Assert.Equal(1, quantity04.Gigacuries); Assert.Equal(RadioactivityUnit.Gigacurie, quantity04.Unit); var quantity05 = Radioactivity.From(1, RadioactivityUnit.Gigarutherford); - AssertEx.EqualTolerance(1, quantity05.Gigarutherfords, GigarutherfordsTolerance); + Assert.Equal(1, quantity05.Gigarutherfords); Assert.Equal(RadioactivityUnit.Gigarutherford, quantity05.Unit); var quantity06 = Radioactivity.From(1, RadioactivityUnit.Kilobecquerel); - AssertEx.EqualTolerance(1, quantity06.Kilobecquerels, KilobecquerelsTolerance); + Assert.Equal(1, quantity06.Kilobecquerels); Assert.Equal(RadioactivityUnit.Kilobecquerel, quantity06.Unit); var quantity07 = Radioactivity.From(1, RadioactivityUnit.Kilocurie); - AssertEx.EqualTolerance(1, quantity07.Kilocuries, KilocuriesTolerance); + Assert.Equal(1, quantity07.Kilocuries); Assert.Equal(RadioactivityUnit.Kilocurie, quantity07.Unit); var quantity08 = Radioactivity.From(1, RadioactivityUnit.Kilorutherford); - AssertEx.EqualTolerance(1, quantity08.Kilorutherfords, KilorutherfordsTolerance); + Assert.Equal(1, quantity08.Kilorutherfords); Assert.Equal(RadioactivityUnit.Kilorutherford, quantity08.Unit); var quantity09 = Radioactivity.From(1, RadioactivityUnit.Megabecquerel); - AssertEx.EqualTolerance(1, quantity09.Megabecquerels, MegabecquerelsTolerance); + Assert.Equal(1, quantity09.Megabecquerels); Assert.Equal(RadioactivityUnit.Megabecquerel, quantity09.Unit); var quantity10 = Radioactivity.From(1, RadioactivityUnit.Megacurie); - AssertEx.EqualTolerance(1, quantity10.Megacuries, MegacuriesTolerance); + Assert.Equal(1, quantity10.Megacuries); Assert.Equal(RadioactivityUnit.Megacurie, quantity10.Unit); var quantity11 = Radioactivity.From(1, RadioactivityUnit.Megarutherford); - AssertEx.EqualTolerance(1, quantity11.Megarutherfords, MegarutherfordsTolerance); + Assert.Equal(1, quantity11.Megarutherfords); Assert.Equal(RadioactivityUnit.Megarutherford, quantity11.Unit); var quantity12 = Radioactivity.From(1, RadioactivityUnit.Microbecquerel); - AssertEx.EqualTolerance(1, quantity12.Microbecquerels, MicrobecquerelsTolerance); + Assert.Equal(1, quantity12.Microbecquerels); Assert.Equal(RadioactivityUnit.Microbecquerel, quantity12.Unit); var quantity13 = Radioactivity.From(1, RadioactivityUnit.Microcurie); - AssertEx.EqualTolerance(1, quantity13.Microcuries, MicrocuriesTolerance); + Assert.Equal(1, quantity13.Microcuries); Assert.Equal(RadioactivityUnit.Microcurie, quantity13.Unit); var quantity14 = Radioactivity.From(1, RadioactivityUnit.Microrutherford); - AssertEx.EqualTolerance(1, quantity14.Microrutherfords, MicrorutherfordsTolerance); + Assert.Equal(1, quantity14.Microrutherfords); Assert.Equal(RadioactivityUnit.Microrutherford, quantity14.Unit); var quantity15 = Radioactivity.From(1, RadioactivityUnit.Millibecquerel); - AssertEx.EqualTolerance(1, quantity15.Millibecquerels, MillibecquerelsTolerance); + Assert.Equal(1, quantity15.Millibecquerels); Assert.Equal(RadioactivityUnit.Millibecquerel, quantity15.Unit); var quantity16 = Radioactivity.From(1, RadioactivityUnit.Millicurie); - AssertEx.EqualTolerance(1, quantity16.Millicuries, MillicuriesTolerance); + Assert.Equal(1, quantity16.Millicuries); Assert.Equal(RadioactivityUnit.Millicurie, quantity16.Unit); var quantity17 = Radioactivity.From(1, RadioactivityUnit.Millirutherford); - AssertEx.EqualTolerance(1, quantity17.Millirutherfords, MillirutherfordsTolerance); + Assert.Equal(1, quantity17.Millirutherfords); Assert.Equal(RadioactivityUnit.Millirutherford, quantity17.Unit); var quantity18 = Radioactivity.From(1, RadioactivityUnit.Nanobecquerel); - AssertEx.EqualTolerance(1, quantity18.Nanobecquerels, NanobecquerelsTolerance); + Assert.Equal(1, quantity18.Nanobecquerels); Assert.Equal(RadioactivityUnit.Nanobecquerel, quantity18.Unit); var quantity19 = Radioactivity.From(1, RadioactivityUnit.Nanocurie); - AssertEx.EqualTolerance(1, quantity19.Nanocuries, NanocuriesTolerance); + Assert.Equal(1, quantity19.Nanocuries); Assert.Equal(RadioactivityUnit.Nanocurie, quantity19.Unit); var quantity20 = Radioactivity.From(1, RadioactivityUnit.Nanorutherford); - AssertEx.EqualTolerance(1, quantity20.Nanorutherfords, NanorutherfordsTolerance); + Assert.Equal(1, quantity20.Nanorutherfords); Assert.Equal(RadioactivityUnit.Nanorutherford, quantity20.Unit); var quantity21 = Radioactivity.From(1, RadioactivityUnit.Petabecquerel); - AssertEx.EqualTolerance(1, quantity21.Petabecquerels, PetabecquerelsTolerance); + Assert.Equal(1, quantity21.Petabecquerels); Assert.Equal(RadioactivityUnit.Petabecquerel, quantity21.Unit); var quantity22 = Radioactivity.From(1, RadioactivityUnit.Picobecquerel); - AssertEx.EqualTolerance(1, quantity22.Picobecquerels, PicobecquerelsTolerance); + Assert.Equal(1, quantity22.Picobecquerels); Assert.Equal(RadioactivityUnit.Picobecquerel, quantity22.Unit); var quantity23 = Radioactivity.From(1, RadioactivityUnit.Picocurie); - AssertEx.EqualTolerance(1, quantity23.Picocuries, PicocuriesTolerance); + Assert.Equal(1, quantity23.Picocuries); Assert.Equal(RadioactivityUnit.Picocurie, quantity23.Unit); var quantity24 = Radioactivity.From(1, RadioactivityUnit.Picorutherford); - AssertEx.EqualTolerance(1, quantity24.Picorutherfords, PicorutherfordsTolerance); + Assert.Equal(1, quantity24.Picorutherfords); Assert.Equal(RadioactivityUnit.Picorutherford, quantity24.Unit); var quantity25 = Radioactivity.From(1, RadioactivityUnit.Rutherford); - AssertEx.EqualTolerance(1, quantity25.Rutherfords, RutherfordsTolerance); + Assert.Equal(1, quantity25.Rutherfords); Assert.Equal(RadioactivityUnit.Rutherford, quantity25.Unit); var quantity26 = Radioactivity.From(1, RadioactivityUnit.Terabecquerel); - AssertEx.EqualTolerance(1, quantity26.Terabecquerels, TerabecquerelsTolerance); + Assert.Equal(1, quantity26.Terabecquerels); Assert.Equal(RadioactivityUnit.Terabecquerel, quantity26.Unit); var quantity27 = Radioactivity.From(1, RadioactivityUnit.Teracurie); - AssertEx.EqualTolerance(1, quantity27.Teracuries, TeracuriesTolerance); + Assert.Equal(1, quantity27.Teracuries); Assert.Equal(RadioactivityUnit.Teracurie, quantity27.Unit); var quantity28 = Radioactivity.From(1, RadioactivityUnit.Terarutherford); - AssertEx.EqualTolerance(1, quantity28.Terarutherfords, TerarutherfordsTolerance); + Assert.Equal(1, quantity28.Terarutherfords); Assert.Equal(RadioactivityUnit.Terarutherford, quantity28.Unit); } @@ -547,672 +565,138 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 Bq", RadioactivityUnit.Becquerel, 4.2)] + [InlineData("en-US", "4.2 Ci", RadioactivityUnit.Curie, 4.2)] + [InlineData("en-US", "4.2 EBq", RadioactivityUnit.Exabecquerel, 4.2)] + [InlineData("en-US", "4.2 GBq", RadioactivityUnit.Gigabecquerel, 4.2)] + [InlineData("en-US", "4.2 GCi", RadioactivityUnit.Gigacurie, 4.2)] + [InlineData("en-US", "4.2 GRd", RadioactivityUnit.Gigarutherford, 4.2)] + [InlineData("en-US", "4.2 kBq", RadioactivityUnit.Kilobecquerel, 4.2)] + [InlineData("en-US", "4.2 kCi", RadioactivityUnit.Kilocurie, 4.2)] + [InlineData("en-US", "4.2 kRd", RadioactivityUnit.Kilorutherford, 4.2)] + [InlineData("en-US", "4.2 MBq", RadioactivityUnit.Megabecquerel, 4.2)] + [InlineData("en-US", "4.2 MCi", RadioactivityUnit.Megacurie, 4.2)] + [InlineData("en-US", "4.2 MRd", RadioactivityUnit.Megarutherford, 4.2)] + [InlineData("en-US", "4.2 µBq", RadioactivityUnit.Microbecquerel, 4.2)] + [InlineData("en-US", "4.2 µCi", RadioactivityUnit.Microcurie, 4.2)] + [InlineData("en-US", "4.2 µRd", RadioactivityUnit.Microrutherford, 4.2)] + [InlineData("en-US", "4.2 mBq", RadioactivityUnit.Millibecquerel, 4.2)] + [InlineData("en-US", "4.2 mCi", RadioactivityUnit.Millicurie, 4.2)] + [InlineData("en-US", "4.2 mRd", RadioactivityUnit.Millirutherford, 4.2)] + [InlineData("en-US", "4.2 nBq", RadioactivityUnit.Nanobecquerel, 4.2)] + [InlineData("en-US", "4.2 nCi", RadioactivityUnit.Nanocurie, 4.2)] + [InlineData("en-US", "4.2 nRd", RadioactivityUnit.Nanorutherford, 4.2)] + [InlineData("en-US", "4.2 PBq", RadioactivityUnit.Petabecquerel, 4.2)] + [InlineData("en-US", "4.2 pBq", RadioactivityUnit.Picobecquerel, 4.2)] + [InlineData("en-US", "4.2 pCi", RadioactivityUnit.Picocurie, 4.2)] + [InlineData("en-US", "4.2 pRd", RadioactivityUnit.Picorutherford, 4.2)] + [InlineData("en-US", "4.2 Rd", RadioactivityUnit.Rutherford, 4.2)] + [InlineData("en-US", "4.2 TBq", RadioactivityUnit.Terabecquerel, 4.2)] + [InlineData("en-US", "4.2 TCi", RadioactivityUnit.Teracurie, 4.2)] + [InlineData("en-US", "4.2 TRd", RadioactivityUnit.Terarutherford, 4.2)] + [InlineData("ru-RU", "4,2 Бк", RadioactivityUnit.Becquerel, 4.2)] + [InlineData("ru-RU", "4,2 Ки", RadioactivityUnit.Curie, 4.2)] + [InlineData("ru-RU", "4,2 ЭБк", RadioactivityUnit.Exabecquerel, 4.2)] + [InlineData("ru-RU", "4,2 ГБк", RadioactivityUnit.Gigabecquerel, 4.2)] + [InlineData("ru-RU", "4,2 ГКи", RadioactivityUnit.Gigacurie, 4.2)] + [InlineData("ru-RU", "4,2 ГРд", RadioactivityUnit.Gigarutherford, 4.2)] + [InlineData("ru-RU", "4,2 кБк", RadioactivityUnit.Kilobecquerel, 4.2)] + [InlineData("ru-RU", "4,2 кКи", RadioactivityUnit.Kilocurie, 4.2)] + [InlineData("ru-RU", "4,2 кРд", RadioactivityUnit.Kilorutherford, 4.2)] + [InlineData("ru-RU", "4,2 МБк", RadioactivityUnit.Megabecquerel, 4.2)] + [InlineData("ru-RU", "4,2 МКи", RadioactivityUnit.Megacurie, 4.2)] + [InlineData("ru-RU", "4,2 МРд", RadioactivityUnit.Megarutherford, 4.2)] + [InlineData("ru-RU", "4,2 мкБк", RadioactivityUnit.Microbecquerel, 4.2)] + [InlineData("ru-RU", "4,2 мкКи", RadioactivityUnit.Microcurie, 4.2)] + [InlineData("ru-RU", "4,2 мкРд", RadioactivityUnit.Microrutherford, 4.2)] + [InlineData("ru-RU", "4,2 мБк", RadioactivityUnit.Millibecquerel, 4.2)] + [InlineData("ru-RU", "4,2 мКи", RadioactivityUnit.Millicurie, 4.2)] + [InlineData("ru-RU", "4,2 мРд", RadioactivityUnit.Millirutherford, 4.2)] + [InlineData("ru-RU", "4,2 нБк", RadioactivityUnit.Nanobecquerel, 4.2)] + [InlineData("ru-RU", "4,2 нКи", RadioactivityUnit.Nanocurie, 4.2)] + [InlineData("ru-RU", "4,2 нРд", RadioactivityUnit.Nanorutherford, 4.2)] + [InlineData("ru-RU", "4,2 ПБк", RadioactivityUnit.Petabecquerel, 4.2)] + [InlineData("ru-RU", "4,2 пБк", RadioactivityUnit.Picobecquerel, 4.2)] + [InlineData("ru-RU", "4,2 пКи", RadioactivityUnit.Picocurie, 4.2)] + [InlineData("ru-RU", "4,2 пРд", RadioactivityUnit.Picorutherford, 4.2)] + [InlineData("ru-RU", "4,2 Рд", RadioactivityUnit.Rutherford, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = Radioactivity.Parse("1 Bq", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Becquerels, BecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Becquerel, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 Бк", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Becquerels, BecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Becquerel, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 Ci", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Curies, CuriesTolerance); - Assert.Equal(RadioactivityUnit.Curie, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 Ки", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Curies, CuriesTolerance); - Assert.Equal(RadioactivityUnit.Curie, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 EBq", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Exabecquerels, ExabecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Exabecquerel, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 ЭБк", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Exabecquerels, ExabecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Exabecquerel, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 GBq", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Gigabecquerels, GigabecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Gigabecquerel, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 ГБк", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Gigabecquerels, GigabecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Gigabecquerel, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 GCi", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Gigacuries, GigacuriesTolerance); - Assert.Equal(RadioactivityUnit.Gigacurie, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 ГКи", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Gigacuries, GigacuriesTolerance); - Assert.Equal(RadioactivityUnit.Gigacurie, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 GRd", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Gigarutherfords, GigarutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Gigarutherford, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 ГРд", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Gigarutherfords, GigarutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Gigarutherford, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 kBq", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilobecquerels, KilobecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Kilobecquerel, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 кБк", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Kilobecquerels, KilobecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Kilobecquerel, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 kCi", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilocuries, KilocuriesTolerance); - Assert.Equal(RadioactivityUnit.Kilocurie, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 кКи", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Kilocuries, KilocuriesTolerance); - Assert.Equal(RadioactivityUnit.Kilocurie, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 kRd", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kilorutherfords, KilorutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Kilorutherford, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 кРд", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Kilorutherfords, KilorutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Kilorutherford, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 MBq", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megabecquerels, MegabecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Megabecquerel, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 МБк", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Megabecquerels, MegabecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Megabecquerel, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 MCi", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megacuries, MegacuriesTolerance); - Assert.Equal(RadioactivityUnit.Megacurie, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 МКи", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Megacuries, MegacuriesTolerance); - Assert.Equal(RadioactivityUnit.Megacurie, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 MRd", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megarutherfords, MegarutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Megarutherford, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 МРд", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Megarutherfords, MegarutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Megarutherford, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 µBq", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microbecquerels, MicrobecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Microbecquerel, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 мкБк", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Microbecquerels, MicrobecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Microbecquerel, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 µCi", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microcuries, MicrocuriesTolerance); - Assert.Equal(RadioactivityUnit.Microcurie, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 мкКи", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Microcuries, MicrocuriesTolerance); - Assert.Equal(RadioactivityUnit.Microcurie, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 µRd", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microrutherfords, MicrorutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Microrutherford, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 мкРд", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Microrutherfords, MicrorutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Microrutherford, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 mBq", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millibecquerels, MillibecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Millibecquerel, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 мБк", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Millibecquerels, MillibecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Millibecquerel, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 mCi", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millicuries, MillicuriesTolerance); - Assert.Equal(RadioactivityUnit.Millicurie, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 мКи", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Millicuries, MillicuriesTolerance); - Assert.Equal(RadioactivityUnit.Millicurie, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 mRd", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Millirutherfords, MillirutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Millirutherford, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 мРд", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Millirutherfords, MillirutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Millirutherford, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 nBq", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanobecquerels, NanobecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Nanobecquerel, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 нБк", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Nanobecquerels, NanobecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Nanobecquerel, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 nCi", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanocuries, NanocuriesTolerance); - Assert.Equal(RadioactivityUnit.Nanocurie, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 нКи", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Nanocuries, NanocuriesTolerance); - Assert.Equal(RadioactivityUnit.Nanocurie, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 nRd", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanorutherfords, NanorutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Nanorutherford, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 нРд", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Nanorutherfords, NanorutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Nanorutherford, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 PBq", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Petabecquerels, PetabecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Petabecquerel, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 ПБк", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Petabecquerels, PetabecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Petabecquerel, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 pBq", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Picobecquerels, PicobecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Picobecquerel, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 пБк", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Picobecquerels, PicobecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Picobecquerel, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 pCi", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Picocuries, PicocuriesTolerance); - Assert.Equal(RadioactivityUnit.Picocurie, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 пКи", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Picocuries, PicocuriesTolerance); - Assert.Equal(RadioactivityUnit.Picocurie, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 pRd", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Picorutherfords, PicorutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Picorutherford, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 пРд", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Picorutherfords, PicorutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Picorutherford, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 Rd", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Rutherfords, RutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Rutherford, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 Рд", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Rutherfords, RutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Rutherford, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 TBq", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Terabecquerels, TerabecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Terabecquerel, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 ТБк", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Terabecquerels, TerabecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Terabecquerel, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 TCi", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Teracuries, TeracuriesTolerance); - Assert.Equal(RadioactivityUnit.Teracurie, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 ТКи", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Teracuries, TeracuriesTolerance); - Assert.Equal(RadioactivityUnit.Teracurie, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 TRd", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Terarutherfords, TerarutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Terarutherford, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Radioactivity.Parse("1 ТРд", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Terarutherfords, TerarutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Terarutherford, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Radioactivity.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 Bq", RadioactivityUnit.Becquerel, 4.2)] + [InlineData("en-US", "4.2 Ci", RadioactivityUnit.Curie, 4.2)] + [InlineData("en-US", "4.2 EBq", RadioactivityUnit.Exabecquerel, 4.2)] + [InlineData("en-US", "4.2 GBq", RadioactivityUnit.Gigabecquerel, 4.2)] + [InlineData("en-US", "4.2 GCi", RadioactivityUnit.Gigacurie, 4.2)] + [InlineData("en-US", "4.2 GRd", RadioactivityUnit.Gigarutherford, 4.2)] + [InlineData("en-US", "4.2 kBq", RadioactivityUnit.Kilobecquerel, 4.2)] + [InlineData("en-US", "4.2 kCi", RadioactivityUnit.Kilocurie, 4.2)] + [InlineData("en-US", "4.2 kRd", RadioactivityUnit.Kilorutherford, 4.2)] + [InlineData("en-US", "4.2 MBq", RadioactivityUnit.Megabecquerel, 4.2)] + [InlineData("en-US", "4.2 MCi", RadioactivityUnit.Megacurie, 4.2)] + [InlineData("en-US", "4.2 MRd", RadioactivityUnit.Megarutherford, 4.2)] + [InlineData("en-US", "4.2 µBq", RadioactivityUnit.Microbecquerel, 4.2)] + [InlineData("en-US", "4.2 µCi", RadioactivityUnit.Microcurie, 4.2)] + [InlineData("en-US", "4.2 µRd", RadioactivityUnit.Microrutherford, 4.2)] + [InlineData("en-US", "4.2 mBq", RadioactivityUnit.Millibecquerel, 4.2)] + [InlineData("en-US", "4.2 mCi", RadioactivityUnit.Millicurie, 4.2)] + [InlineData("en-US", "4.2 mRd", RadioactivityUnit.Millirutherford, 4.2)] + [InlineData("en-US", "4.2 nBq", RadioactivityUnit.Nanobecquerel, 4.2)] + [InlineData("en-US", "4.2 nCi", RadioactivityUnit.Nanocurie, 4.2)] + [InlineData("en-US", "4.2 nRd", RadioactivityUnit.Nanorutherford, 4.2)] + [InlineData("en-US", "4.2 PBq", RadioactivityUnit.Petabecquerel, 4.2)] + [InlineData("en-US", "4.2 pBq", RadioactivityUnit.Picobecquerel, 4.2)] + [InlineData("en-US", "4.2 pCi", RadioactivityUnit.Picocurie, 4.2)] + [InlineData("en-US", "4.2 pRd", RadioactivityUnit.Picorutherford, 4.2)] + [InlineData("en-US", "4.2 Rd", RadioactivityUnit.Rutherford, 4.2)] + [InlineData("en-US", "4.2 TBq", RadioactivityUnit.Terabecquerel, 4.2)] + [InlineData("en-US", "4.2 TCi", RadioactivityUnit.Teracurie, 4.2)] + [InlineData("en-US", "4.2 TRd", RadioactivityUnit.Terarutherford, 4.2)] + [InlineData("ru-RU", "4,2 Бк", RadioactivityUnit.Becquerel, 4.2)] + [InlineData("ru-RU", "4,2 Ки", RadioactivityUnit.Curie, 4.2)] + [InlineData("ru-RU", "4,2 ЭБк", RadioactivityUnit.Exabecquerel, 4.2)] + [InlineData("ru-RU", "4,2 ГБк", RadioactivityUnit.Gigabecquerel, 4.2)] + [InlineData("ru-RU", "4,2 ГКи", RadioactivityUnit.Gigacurie, 4.2)] + [InlineData("ru-RU", "4,2 ГРд", RadioactivityUnit.Gigarutherford, 4.2)] + [InlineData("ru-RU", "4,2 кБк", RadioactivityUnit.Kilobecquerel, 4.2)] + [InlineData("ru-RU", "4,2 кКи", RadioactivityUnit.Kilocurie, 4.2)] + [InlineData("ru-RU", "4,2 кРд", RadioactivityUnit.Kilorutherford, 4.2)] + [InlineData("ru-RU", "4,2 МБк", RadioactivityUnit.Megabecquerel, 4.2)] + [InlineData("ru-RU", "4,2 МКи", RadioactivityUnit.Megacurie, 4.2)] + [InlineData("ru-RU", "4,2 МРд", RadioactivityUnit.Megarutherford, 4.2)] + [InlineData("ru-RU", "4,2 мкБк", RadioactivityUnit.Microbecquerel, 4.2)] + [InlineData("ru-RU", "4,2 мкКи", RadioactivityUnit.Microcurie, 4.2)] + [InlineData("ru-RU", "4,2 мкРд", RadioactivityUnit.Microrutherford, 4.2)] + [InlineData("ru-RU", "4,2 мБк", RadioactivityUnit.Millibecquerel, 4.2)] + [InlineData("ru-RU", "4,2 мКи", RadioactivityUnit.Millicurie, 4.2)] + [InlineData("ru-RU", "4,2 мРд", RadioactivityUnit.Millirutherford, 4.2)] + [InlineData("ru-RU", "4,2 нБк", RadioactivityUnit.Nanobecquerel, 4.2)] + [InlineData("ru-RU", "4,2 нКи", RadioactivityUnit.Nanocurie, 4.2)] + [InlineData("ru-RU", "4,2 нРд", RadioactivityUnit.Nanorutherford, 4.2)] + [InlineData("ru-RU", "4,2 ПБк", RadioactivityUnit.Petabecquerel, 4.2)] + [InlineData("ru-RU", "4,2 пБк", RadioactivityUnit.Picobecquerel, 4.2)] + [InlineData("ru-RU", "4,2 пКи", RadioactivityUnit.Picocurie, 4.2)] + [InlineData("ru-RU", "4,2 пРд", RadioactivityUnit.Picorutherford, 4.2)] + [InlineData("ru-RU", "4,2 Рд", RadioactivityUnit.Rutherford, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(Radioactivity.TryParse("1 Bq", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Becquerels, BecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Becquerel, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 Бк", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Becquerels, BecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Becquerel, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 Ci", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Curies, CuriesTolerance); - Assert.Equal(RadioactivityUnit.Curie, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 Ки", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Curies, CuriesTolerance); - Assert.Equal(RadioactivityUnit.Curie, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 EBq", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Exabecquerels, ExabecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Exabecquerel, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 ЭБк", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Exabecquerels, ExabecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Exabecquerel, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 GBq", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gigabecquerels, GigabecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Gigabecquerel, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 ГБк", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gigabecquerels, GigabecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Gigabecquerel, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 GCi", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gigacuries, GigacuriesTolerance); - Assert.Equal(RadioactivityUnit.Gigacurie, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 ГКи", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gigacuries, GigacuriesTolerance); - Assert.Equal(RadioactivityUnit.Gigacurie, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 GRd", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gigarutherfords, GigarutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Gigarutherford, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 ГРд", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Gigarutherfords, GigarutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Gigarutherford, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 kBq", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilobecquerels, KilobecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Kilobecquerel, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 кБк", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilobecquerels, KilobecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Kilobecquerel, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 kCi", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilocuries, KilocuriesTolerance); - Assert.Equal(RadioactivityUnit.Kilocurie, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 кКи", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilocuries, KilocuriesTolerance); - Assert.Equal(RadioactivityUnit.Kilocurie, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 kRd", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilorutherfords, KilorutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Kilorutherford, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 кРд", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kilorutherfords, KilorutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Kilorutherford, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 µBq", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microbecquerels, MicrobecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Microbecquerel, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 мкБк", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microbecquerels, MicrobecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Microbecquerel, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 µCi", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microcuries, MicrocuriesTolerance); - Assert.Equal(RadioactivityUnit.Microcurie, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 мкКи", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microcuries, MicrocuriesTolerance); - Assert.Equal(RadioactivityUnit.Microcurie, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 µRd", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microrutherfords, MicrorutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Microrutherford, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 мкРд", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microrutherfords, MicrorutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Microrutherford, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 nBq", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanobecquerels, NanobecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Nanobecquerel, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 нБк", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanobecquerels, NanobecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Nanobecquerel, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 nCi", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanocuries, NanocuriesTolerance); - Assert.Equal(RadioactivityUnit.Nanocurie, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 нКи", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanocuries, NanocuriesTolerance); - Assert.Equal(RadioactivityUnit.Nanocurie, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 nRd", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanorutherfords, NanorutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Nanorutherford, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 нРд", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanorutherfords, NanorutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Nanorutherford, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 pCi", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Picocuries, PicocuriesTolerance); - Assert.Equal(RadioactivityUnit.Picocurie, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 пКи", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Picocuries, PicocuriesTolerance); - Assert.Equal(RadioactivityUnit.Picocurie, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 pRd", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Picorutherfords, PicorutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Picorutherford, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 пРд", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Picorutherfords, PicorutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Picorutherford, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 Rd", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Rutherfords, RutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Rutherford, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 Рд", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Rutherfords, RutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Rutherford, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 TBq", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Terabecquerels, TerabecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Terabecquerel, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 ТБк", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Terabecquerels, TerabecquerelsTolerance); - Assert.Equal(RadioactivityUnit.Terabecquerel, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 TCi", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Teracuries, TeracuriesTolerance); - Assert.Equal(RadioactivityUnit.Teracurie, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 ТКи", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Teracuries, TeracuriesTolerance); - Assert.Equal(RadioactivityUnit.Teracurie, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 TRd", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Terarutherfords, TerarutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Terarutherford, parsed.Unit); - } - - { - Assert.True(Radioactivity.TryParse("1 ТРд", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Terarutherfords, TerarutherfordsTolerance); - Assert.Equal(RadioactivityUnit.Terarutherford, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Radioactivity.TryParse(quantityString, out Radioactivity parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -1629,6 +1113,84 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Radioa Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", RadioactivityUnit.Becquerel, "Bq")] + [InlineData("en-US", RadioactivityUnit.Curie, "Ci")] + [InlineData("en-US", RadioactivityUnit.Exabecquerel, "EBq")] + [InlineData("en-US", RadioactivityUnit.Gigabecquerel, "GBq")] + [InlineData("en-US", RadioactivityUnit.Gigacurie, "GCi")] + [InlineData("en-US", RadioactivityUnit.Gigarutherford, "GRd")] + [InlineData("en-US", RadioactivityUnit.Kilobecquerel, "kBq")] + [InlineData("en-US", RadioactivityUnit.Kilocurie, "kCi")] + [InlineData("en-US", RadioactivityUnit.Kilorutherford, "kRd")] + [InlineData("en-US", RadioactivityUnit.Megabecquerel, "MBq")] + [InlineData("en-US", RadioactivityUnit.Megacurie, "MCi")] + [InlineData("en-US", RadioactivityUnit.Megarutherford, "MRd")] + [InlineData("en-US", RadioactivityUnit.Microbecquerel, "µBq")] + [InlineData("en-US", RadioactivityUnit.Microcurie, "µCi")] + [InlineData("en-US", RadioactivityUnit.Microrutherford, "µRd")] + [InlineData("en-US", RadioactivityUnit.Millibecquerel, "mBq")] + [InlineData("en-US", RadioactivityUnit.Millicurie, "mCi")] + [InlineData("en-US", RadioactivityUnit.Millirutherford, "mRd")] + [InlineData("en-US", RadioactivityUnit.Nanobecquerel, "nBq")] + [InlineData("en-US", RadioactivityUnit.Nanocurie, "nCi")] + [InlineData("en-US", RadioactivityUnit.Nanorutherford, "nRd")] + [InlineData("en-US", RadioactivityUnit.Petabecquerel, "PBq")] + [InlineData("en-US", RadioactivityUnit.Picobecquerel, "pBq")] + [InlineData("en-US", RadioactivityUnit.Picocurie, "pCi")] + [InlineData("en-US", RadioactivityUnit.Picorutherford, "pRd")] + [InlineData("en-US", RadioactivityUnit.Rutherford, "Rd")] + [InlineData("en-US", RadioactivityUnit.Terabecquerel, "TBq")] + [InlineData("en-US", RadioactivityUnit.Teracurie, "TCi")] + [InlineData("en-US", RadioactivityUnit.Terarutherford, "TRd")] + [InlineData("ru-RU", RadioactivityUnit.Becquerel, "Бк")] + [InlineData("ru-RU", RadioactivityUnit.Curie, "Ки")] + [InlineData("ru-RU", RadioactivityUnit.Exabecquerel, "ЭБк")] + [InlineData("ru-RU", RadioactivityUnit.Gigabecquerel, "ГБк")] + [InlineData("ru-RU", RadioactivityUnit.Gigacurie, "ГКи")] + [InlineData("ru-RU", RadioactivityUnit.Gigarutherford, "ГРд")] + [InlineData("ru-RU", RadioactivityUnit.Kilobecquerel, "кБк")] + [InlineData("ru-RU", RadioactivityUnit.Kilocurie, "кКи")] + [InlineData("ru-RU", RadioactivityUnit.Kilorutherford, "кРд")] + [InlineData("ru-RU", RadioactivityUnit.Megabecquerel, "МБк")] + [InlineData("ru-RU", RadioactivityUnit.Megacurie, "МКи")] + [InlineData("ru-RU", RadioactivityUnit.Megarutherford, "МРд")] + [InlineData("ru-RU", RadioactivityUnit.Microbecquerel, "мкБк")] + [InlineData("ru-RU", RadioactivityUnit.Microcurie, "мкКи")] + [InlineData("ru-RU", RadioactivityUnit.Microrutherford, "мкРд")] + [InlineData("ru-RU", RadioactivityUnit.Millibecquerel, "мБк")] + [InlineData("ru-RU", RadioactivityUnit.Millicurie, "мКи")] + [InlineData("ru-RU", RadioactivityUnit.Millirutherford, "мРд")] + [InlineData("ru-RU", RadioactivityUnit.Nanobecquerel, "нБк")] + [InlineData("ru-RU", RadioactivityUnit.Nanocurie, "нКи")] + [InlineData("ru-RU", RadioactivityUnit.Nanorutherford, "нРд")] + [InlineData("ru-RU", RadioactivityUnit.Petabecquerel, "ПБк")] + [InlineData("ru-RU", RadioactivityUnit.Picobecquerel, "пБк")] + [InlineData("ru-RU", RadioactivityUnit.Picocurie, "пКи")] + [InlineData("ru-RU", RadioactivityUnit.Picorutherford, "пРд")] + [InlineData("ru-RU", RadioactivityUnit.Rutherford, "Рд")] + [InlineData("ru-RU", RadioactivityUnit.Terabecquerel, "ТБк")] + [InlineData("ru-RU", RadioactivityUnit.Teracurie, "ТКи")] + [InlineData("ru-RU", RadioactivityUnit.Terarutherford, "ТРд")] + public void GetAbbreviationForCulture(string culture, RadioactivityUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Radioactivity.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Radioactivity.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Radioactivity.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(RadioactivityUnit unit) @@ -1659,6 +1221,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); }); } @@ -1682,60 +1245,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] @@ -1781,8 +1346,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); @@ -1819,23 +1382,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = Radioactivity.FromBecquerels(1); - Assert.True(v.Equals(Radioactivity.FromBecquerels(1), BecquerelsTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Radioactivity.Zero, BecquerelsTolerance, ComparisonType.Relative)); - Assert.True(Radioactivity.FromBecquerels(100).Equals(Radioactivity.FromBecquerels(120), 0.3, ComparisonType.Relative)); - Assert.False(Radioactivity.FromBecquerels(100).Equals(Radioactivity.FromBecquerels(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = Radioactivity.FromBecquerels(1); - Assert.Throws(() => v.Equals(Radioactivity.FromBecquerels(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1850,6 +1396,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(becquerel.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = Radioactivity.FromBecquerels(1); + var negativeTolerance = Radioactivity.FromBecquerels(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1866,6 +1438,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() { @@ -1980,158 +1564,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Radioactivity.FromBecquerels(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Radioactivity.FromBecquerels(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Radioactivity.FromBecquerels(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Radioactivity.FromBecquerels(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Radioactivity.FromBecquerels(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Radioactivity.FromBecquerels(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Radioactivity.FromBecquerels(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Radioactivity.FromBecquerels(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Radioactivity.FromBecquerels(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Radioactivity.FromBecquerels(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Radioactivity.FromBecquerels(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Radioactivity.FromBecquerels(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Radioactivity.FromBecquerels(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Radioactivity.FromBecquerels(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Radioactivity.FromBecquerels(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Radioactivity.FromBecquerels(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Radioactivity))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Radioactivity.FromBecquerels(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(RadioactivityUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Radioactivity.FromBecquerels(1.0); - Assert.Equal(Radioactivity.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Radioactivity.FromBecquerels(1.0); - Assert.Equal(Radioactivity.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Radioactivity.FromBecquerels(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Radioactivity.FromBecquerels(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Radioactivity.FromBecquerels(1.0); - Assert.Equal(new {Radioactivity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 860d2f97be..1dcc343cbd 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RatioChangeRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RatioChangeRateTestsBase.g.cs @@ -100,7 +100,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new RatioChangeRate(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -113,15 +113,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void RatioChangeRate_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + RatioChangeRateUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new RatioChangeRate(1, RatioChangeRateUnit.DecimalFractionPerSecond); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(RatioChangeRate.Zero, quantityInfo.Zero); Assert.Equal("RatioChangeRate", quantityInfo.Name); + Assert.Equal(RatioChangeRate.Zero, quantityInfo.Zero); + Assert.Equal(RatioChangeRate.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(RatioChangeRate.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void RatioChangeRateInfo_CreateWithCustomUnitInfos() + { + RatioChangeRateUnit[] expectedUnits = [RatioChangeRateUnit.DecimalFractionPerSecond]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -136,11 +154,11 @@ public void DecimalFractionPerSecondToRatioChangeRateUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = RatioChangeRate.From(1, RatioChangeRateUnit.DecimalFractionPerSecond); - AssertEx.EqualTolerance(1, quantity00.DecimalFractionsPerSecond, DecimalFractionsPerSecondTolerance); + Assert.Equal(1, quantity00.DecimalFractionsPerSecond); Assert.Equal(RatioChangeRateUnit.DecimalFractionPerSecond, quantity00.Unit); var quantity01 = RatioChangeRate.From(1, RatioChangeRateUnit.PercentPerSecond); - AssertEx.EqualTolerance(1, quantity01.PercentsPerSecond, PercentsPerSecondTolerance); + Assert.Equal(1, quantity01.PercentsPerSecond); Assert.Equal(RatioChangeRateUnit.PercentPerSecond, quantity01.Unit); } @@ -277,40 +295,26 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [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, decimal expectedValue) { - try - { - var parsed = RatioChangeRate.Parse("1 /s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecimalFractionsPerSecond, DecimalFractionsPerSecondTolerance); - Assert.Equal(RatioChangeRateUnit.DecimalFractionPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RatioChangeRate.Parse("1 %/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PercentsPerSecond, PercentsPerSecondTolerance); - Assert.Equal(RatioChangeRateUnit.PercentPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = RatioChangeRate.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [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, decimal expectedValue) { - { - Assert.True(RatioChangeRate.TryParse("1 /s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecimalFractionsPerSecond, DecimalFractionsPerSecondTolerance); - Assert.Equal(RatioChangeRateUnit.DecimalFractionPerSecond, parsed.Unit); - } - - { - Assert.True(RatioChangeRate.TryParse("1 %/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PercentsPerSecond, PercentsPerSecondTolerance); - Assert.Equal(RatioChangeRateUnit.PercentPerSecond, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(RatioChangeRate.TryParse(quantityString, out RatioChangeRate parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -395,6 +399,28 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, RatioC Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", RatioChangeRateUnit.DecimalFractionPerSecond, "/s")] + [InlineData("en-US", RatioChangeRateUnit.PercentPerSecond, "%/s")] + public void GetAbbreviationForCulture(string culture, RatioChangeRateUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = RatioChangeRate.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(RatioChangeRate.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = RatioChangeRate.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(RatioChangeRateUnit unit) @@ -425,6 +451,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); }); } @@ -448,33 +475,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] @@ -520,8 +549,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); @@ -559,34 +586,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = RatioChangeRate.FromDecimalFractionsPerSecond(1); - Assert.True(v.Equals(RatioChangeRate.FromDecimalFractionsPerSecond(1), DecimalFractionsPerSecondTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(RatioChangeRate.Zero, DecimalFractionsPerSecondTolerance, ComparisonType.Relative)); - Assert.True(RatioChangeRate.FromDecimalFractionsPerSecond(100).Equals(RatioChangeRate.FromDecimalFractionsPerSecond(120), 0.3, ComparisonType.Relative)); - Assert.False(RatioChangeRate.FromDecimalFractionsPerSecond(100).Equals(RatioChangeRate.FromDecimalFractionsPerSecond(120), 0.1, ComparisonType.Relative)); + RatioChangeRate decimalfractionpersecond = RatioChangeRate.FromDecimalFractionsPerSecond(1); + Assert.False(decimalfractionpersecond.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = RatioChangeRate.FromDecimalFractionsPerSecond(1); - Assert.Throws(() => v.Equals(RatioChangeRate.FromDecimalFractionsPerSecond(1), -1, ComparisonType.Relative)); + RatioChangeRate decimalfractionpersecond = RatioChangeRate.FromDecimalFractionsPerSecond(1); + Assert.False(decimalfractionpersecond.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - RatioChangeRate decimalfractionpersecond = RatioChangeRate.FromDecimalFractionsPerSecond(1); - Assert.False(decimalfractionpersecond.Equals(new object())); + var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(firstValue); + var otherQuantity = RatioChangeRate.FromDecimalFractionsPerSecond(secondValue); + RatioChangeRate maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - RatioChangeRate decimalfractionpersecond = RatioChangeRate.FromDecimalFractionsPerSecond(1); - Assert.False(decimalfractionpersecond.Equals(null)); + var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1); + var negativeTolerance = RatioChangeRate.FromDecimalFractionsPerSecond(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -605,6 +641,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() { @@ -665,158 +713,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(RatioChangeRate))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(RatioChangeRateUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal(RatioChangeRate.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal(RatioChangeRate.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal(new {RatioChangeRate.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 34c296eced..2fcb9bf172 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RatioTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RatioTestsBase.g.cs @@ -108,15 +108,33 @@ public void Ctor_WithNaNValue_DoNotThrowsArgumentException() [Fact] public void Ratio_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + RatioUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Ratio(1, RatioUnit.DecimalFraction); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Ratio.Zero, quantityInfo.Zero); Assert.Equal("Ratio", quantityInfo.Name); + Assert.Equal(Ratio.Zero, quantityInfo.Zero); + Assert.Equal(Ratio.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Ratio.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void RatioInfo_CreateWithCustomUnitInfos() + { + RatioUnit[] expectedUnits = [RatioUnit.DecimalFraction]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -135,27 +153,27 @@ public void DecimalFractionToRatioUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Ratio.From(1, RatioUnit.DecimalFraction); - AssertEx.EqualTolerance(1, quantity00.DecimalFractions, DecimalFractionsTolerance); + Assert.Equal(1, quantity00.DecimalFractions); Assert.Equal(RatioUnit.DecimalFraction, quantity00.Unit); var quantity01 = Ratio.From(1, RatioUnit.PartPerBillion); - AssertEx.EqualTolerance(1, quantity01.PartsPerBillion, PartsPerBillionTolerance); + Assert.Equal(1, quantity01.PartsPerBillion); Assert.Equal(RatioUnit.PartPerBillion, quantity01.Unit); var quantity02 = Ratio.From(1, RatioUnit.PartPerMillion); - AssertEx.EqualTolerance(1, quantity02.PartsPerMillion, PartsPerMillionTolerance); + Assert.Equal(1, quantity02.PartsPerMillion); Assert.Equal(RatioUnit.PartPerMillion, quantity02.Unit); var quantity03 = Ratio.From(1, RatioUnit.PartPerThousand); - AssertEx.EqualTolerance(1, quantity03.PartsPerThousand, PartsPerThousandTolerance); + Assert.Equal(1, quantity03.PartsPerThousand); Assert.Equal(RatioUnit.PartPerThousand, quantity03.Unit); var quantity04 = Ratio.From(1, RatioUnit.PartPerTrillion); - AssertEx.EqualTolerance(1, quantity04.PartsPerTrillion, PartsPerTrillionTolerance); + Assert.Equal(1, quantity04.PartsPerTrillion); Assert.Equal(RatioUnit.PartPerTrillion, quantity04.Unit); var quantity05 = Ratio.From(1, RatioUnit.Percent); - AssertEx.EqualTolerance(1, quantity05.Percent, PercentTolerance); + Assert.Equal(1, quantity05.Percent); Assert.Equal(RatioUnit.Percent, quantity05.Unit); } @@ -257,92 +275,34 @@ public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 ", RatioUnit.DecimalFraction, 4.2)] + [InlineData("en-US", "4.2 ppb", RatioUnit.PartPerBillion, 4.2)] + [InlineData("en-US", "4.2 ppm", RatioUnit.PartPerMillion, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = Ratio.Parse("1 ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecimalFractions, DecimalFractionsTolerance); - Assert.Equal(RatioUnit.DecimalFraction, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Ratio.Parse("1 ppb", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PartsPerBillion, PartsPerBillionTolerance); - Assert.Equal(RatioUnit.PartPerBillion, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Ratio.Parse("1 ppm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PartsPerMillion, PartsPerMillionTolerance); - Assert.Equal(RatioUnit.PartPerMillion, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Ratio.Parse("1 ‰", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PartsPerThousand, PartsPerThousandTolerance); - Assert.Equal(RatioUnit.PartPerThousand, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Ratio.Parse("1 ppt", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PartsPerTrillion, PartsPerTrillionTolerance); - Assert.Equal(RatioUnit.PartPerTrillion, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Ratio.Parse("1 %", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Percent, PercentTolerance); - Assert.Equal(RatioUnit.Percent, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Ratio.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 ", RatioUnit.DecimalFraction, 4.2)] + [InlineData("en-US", "4.2 ppb", RatioUnit.PartPerBillion, 4.2)] + [InlineData("en-US", "4.2 ppm", RatioUnit.PartPerMillion, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(Ratio.TryParse("1 ", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecimalFractions, DecimalFractionsTolerance); - Assert.Equal(RatioUnit.DecimalFraction, parsed.Unit); - } - - { - Assert.True(Ratio.TryParse("1 ppb", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PartsPerBillion, PartsPerBillionTolerance); - Assert.Equal(RatioUnit.PartPerBillion, parsed.Unit); - } - - { - Assert.True(Ratio.TryParse("1 ppm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PartsPerMillion, PartsPerMillionTolerance); - Assert.Equal(RatioUnit.PartPerMillion, parsed.Unit); - } - - { - Assert.True(Ratio.TryParse("1 ‰", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PartsPerThousand, PartsPerThousandTolerance); - Assert.Equal(RatioUnit.PartPerThousand, parsed.Unit); - } - - { - Assert.True(Ratio.TryParse("1 ppt", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PartsPerTrillion, PartsPerTrillionTolerance); - Assert.Equal(RatioUnit.PartPerTrillion, parsed.Unit); - } - - { - Assert.True(Ratio.TryParse("1 %", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Percent, PercentTolerance); - Assert.Equal(RatioUnit.Percent, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Ratio.TryParse(quantityString, out Ratio parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -459,6 +419,32 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, RatioU Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", RatioUnit.DecimalFraction, "")] + [InlineData("en-US", RatioUnit.PartPerBillion, "ppb")] + [InlineData("en-US", RatioUnit.PartPerMillion, "ppm")] + [InlineData("en-US", RatioUnit.PartPerThousand, "‰")] + [InlineData("en-US", RatioUnit.PartPerTrillion, "ppt")] + [InlineData("en-US", RatioUnit.Percent, "%")] + public void GetAbbreviationForCulture(string culture, RatioUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Ratio.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Ratio.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Ratio.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(RatioUnit unit) @@ -489,6 +475,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); }); } @@ -512,37 +499,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] @@ -588,8 +577,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); @@ -627,34 +614,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = Ratio.FromDecimalFractions(1); - Assert.True(v.Equals(Ratio.FromDecimalFractions(1), DecimalFractionsTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Ratio.Zero, DecimalFractionsTolerance, ComparisonType.Relative)); - Assert.True(Ratio.FromDecimalFractions(100).Equals(Ratio.FromDecimalFractions(120), 0.3, ComparisonType.Relative)); - Assert.False(Ratio.FromDecimalFractions(100).Equals(Ratio.FromDecimalFractions(120), 0.1, ComparisonType.Relative)); + Ratio decimalfraction = Ratio.FromDecimalFractions(1); + Assert.False(decimalfraction.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = Ratio.FromDecimalFractions(1); - Assert.Throws(() => v.Equals(Ratio.FromDecimalFractions(1), -1, ComparisonType.Relative)); + Ratio decimalfraction = Ratio.FromDecimalFractions(1); + Assert.False(decimalfraction.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - Ratio decimalfraction = Ratio.FromDecimalFractions(1); - Assert.False(decimalfraction.Equals(new object())); + var quantity = Ratio.FromDecimalFractions(firstValue); + var otherQuantity = Ratio.FromDecimalFractions(secondValue); + Ratio maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - Ratio decimalfraction = Ratio.FromDecimalFractions(1); - Assert.False(decimalfraction.Equals(null)); + var quantity = Ratio.FromDecimalFractions(1); + var negativeTolerance = Ratio.FromDecimalFractions(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -673,6 +669,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() { @@ -741,158 +749,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Ratio))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(RatioUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal(Ratio.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal(Ratio.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal(new {Ratio.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 90a67526a3..72f6c0610c 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalAreaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalAreaTestsBase.g.cs @@ -136,7 +136,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ReciprocalArea(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -149,15 +149,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ReciprocalArea_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ReciprocalAreaUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ReciprocalArea(1, ReciprocalAreaUnit.InverseSquareMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ReciprocalArea.Zero, quantityInfo.Zero); Assert.Equal("ReciprocalArea", quantityInfo.Name); + Assert.Equal(ReciprocalArea.Zero, quantityInfo.Zero); + Assert.Equal(ReciprocalArea.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ReciprocalArea.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -181,47 +199,47 @@ public void InverseSquareMeterToReciprocalAreaUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ReciprocalArea.From(1, ReciprocalAreaUnit.InverseSquareCentimeter); - AssertEx.EqualTolerance(1, quantity00.InverseSquareCentimeters, InverseSquareCentimetersTolerance); + Assert.Equal(1, quantity00.InverseSquareCentimeters); Assert.Equal(ReciprocalAreaUnit.InverseSquareCentimeter, quantity00.Unit); var quantity01 = ReciprocalArea.From(1, ReciprocalAreaUnit.InverseSquareDecimeter); - AssertEx.EqualTolerance(1, quantity01.InverseSquareDecimeters, InverseSquareDecimetersTolerance); + Assert.Equal(1, quantity01.InverseSquareDecimeters); Assert.Equal(ReciprocalAreaUnit.InverseSquareDecimeter, quantity01.Unit); var quantity02 = ReciprocalArea.From(1, ReciprocalAreaUnit.InverseSquareFoot); - AssertEx.EqualTolerance(1, quantity02.InverseSquareFeet, InverseSquareFeetTolerance); + Assert.Equal(1, quantity02.InverseSquareFeet); Assert.Equal(ReciprocalAreaUnit.InverseSquareFoot, quantity02.Unit); var quantity03 = ReciprocalArea.From(1, ReciprocalAreaUnit.InverseSquareInch); - AssertEx.EqualTolerance(1, quantity03.InverseSquareInches, InverseSquareInchesTolerance); + Assert.Equal(1, quantity03.InverseSquareInches); Assert.Equal(ReciprocalAreaUnit.InverseSquareInch, quantity03.Unit); var quantity04 = ReciprocalArea.From(1, ReciprocalAreaUnit.InverseSquareKilometer); - AssertEx.EqualTolerance(1, quantity04.InverseSquareKilometers, InverseSquareKilometersTolerance); + Assert.Equal(1, quantity04.InverseSquareKilometers); Assert.Equal(ReciprocalAreaUnit.InverseSquareKilometer, quantity04.Unit); var quantity05 = ReciprocalArea.From(1, ReciprocalAreaUnit.InverseSquareMeter); - AssertEx.EqualTolerance(1, quantity05.InverseSquareMeters, InverseSquareMetersTolerance); + Assert.Equal(1, quantity05.InverseSquareMeters); Assert.Equal(ReciprocalAreaUnit.InverseSquareMeter, quantity05.Unit); var quantity06 = ReciprocalArea.From(1, ReciprocalAreaUnit.InverseSquareMicrometer); - AssertEx.EqualTolerance(1, quantity06.InverseSquareMicrometers, InverseSquareMicrometersTolerance); + Assert.Equal(1, quantity06.InverseSquareMicrometers); Assert.Equal(ReciprocalAreaUnit.InverseSquareMicrometer, quantity06.Unit); var quantity07 = ReciprocalArea.From(1, ReciprocalAreaUnit.InverseSquareMile); - AssertEx.EqualTolerance(1, quantity07.InverseSquareMiles, InverseSquareMilesTolerance); + Assert.Equal(1, quantity07.InverseSquareMiles); Assert.Equal(ReciprocalAreaUnit.InverseSquareMile, quantity07.Unit); var quantity08 = ReciprocalArea.From(1, ReciprocalAreaUnit.InverseSquareMillimeter); - AssertEx.EqualTolerance(1, quantity08.InverseSquareMillimeters, InverseSquareMillimetersTolerance); + Assert.Equal(1, quantity08.InverseSquareMillimeters); Assert.Equal(ReciprocalAreaUnit.InverseSquareMillimeter, quantity08.Unit); var quantity09 = ReciprocalArea.From(1, ReciprocalAreaUnit.InverseSquareYard); - AssertEx.EqualTolerance(1, quantity09.InverseSquareYards, InverseSquareYardsTolerance); + Assert.Equal(1, quantity09.InverseSquareYards); Assert.Equal(ReciprocalAreaUnit.InverseSquareYard, quantity09.Unit); var quantity10 = ReciprocalArea.From(1, ReciprocalAreaUnit.InverseUsSurveySquareFoot); - AssertEx.EqualTolerance(1, quantity10.InverseUsSurveySquareFeet, InverseUsSurveySquareFeetTolerance); + Assert.Equal(1, quantity10.InverseUsSurveySquareFeet); Assert.Equal(ReciprocalAreaUnit.InverseUsSurveySquareFoot, quantity10.Unit); } @@ -367,157 +385,44 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 cm⁻²", ReciprocalAreaUnit.InverseSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 dm⁻²", ReciprocalAreaUnit.InverseSquareDecimeter, 4.2)] + [InlineData("en-US", "4.2 ft⁻²", ReciprocalAreaUnit.InverseSquareFoot, 4.2)] + [InlineData("en-US", "4.2 in⁻²", ReciprocalAreaUnit.InverseSquareInch, 4.2)] + [InlineData("en-US", "4.2 km⁻²", ReciprocalAreaUnit.InverseSquareKilometer, 4.2)] + [InlineData("en-US", "4.2 m⁻²", ReciprocalAreaUnit.InverseSquareMeter, 4.2)] + [InlineData("en-US", "4.2 µm⁻²", ReciprocalAreaUnit.InverseSquareMicrometer, 4.2)] + [InlineData("en-US", "4.2 mi⁻²", ReciprocalAreaUnit.InverseSquareMile, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = ReciprocalArea.Parse("1 cm⁻²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseSquareCentimeters, InverseSquareCentimetersTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalArea.Parse("1 dm⁻²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseSquareDecimeters, InverseSquareDecimetersTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareDecimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalArea.Parse("1 ft⁻²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseSquareFeet, InverseSquareFeetTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalArea.Parse("1 in⁻²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseSquareInches, InverseSquareInchesTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalArea.Parse("1 km⁻²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseSquareKilometers, InverseSquareKilometersTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareKilometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalArea.Parse("1 m⁻²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseSquareMeters, InverseSquareMetersTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalArea.Parse("1 µm⁻²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseSquareMicrometers, InverseSquareMicrometersTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareMicrometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalArea.Parse("1 mi⁻²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseSquareMiles, InverseSquareMilesTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareMile, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalArea.Parse("1 mm⁻²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseSquareMillimeters, InverseSquareMillimetersTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalArea.Parse("1 yd⁻²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseSquareYards, InverseSquareYardsTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareYard, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalArea.Parse("1 ft⁻² (US)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseUsSurveySquareFeet, InverseUsSurveySquareFeetTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseUsSurveySquareFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ReciprocalArea.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 cm⁻²", ReciprocalAreaUnit.InverseSquareCentimeter, 4.2)] + [InlineData("en-US", "4.2 dm⁻²", ReciprocalAreaUnit.InverseSquareDecimeter, 4.2)] + [InlineData("en-US", "4.2 ft⁻²", ReciprocalAreaUnit.InverseSquareFoot, 4.2)] + [InlineData("en-US", "4.2 in⁻²", ReciprocalAreaUnit.InverseSquareInch, 4.2)] + [InlineData("en-US", "4.2 km⁻²", ReciprocalAreaUnit.InverseSquareKilometer, 4.2)] + [InlineData("en-US", "4.2 m⁻²", ReciprocalAreaUnit.InverseSquareMeter, 4.2)] + [InlineData("en-US", "4.2 µm⁻²", ReciprocalAreaUnit.InverseSquareMicrometer, 4.2)] + [InlineData("en-US", "4.2 mi⁻²", ReciprocalAreaUnit.InverseSquareMile, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(ReciprocalArea.TryParse("1 cm⁻²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseSquareCentimeters, InverseSquareCentimetersTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareCentimeter, parsed.Unit); - } - - { - Assert.True(ReciprocalArea.TryParse("1 dm⁻²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseSquareDecimeters, InverseSquareDecimetersTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareDecimeter, parsed.Unit); - } - - { - Assert.True(ReciprocalArea.TryParse("1 ft⁻²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseSquareFeet, InverseSquareFeetTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareFoot, parsed.Unit); - } - - { - Assert.True(ReciprocalArea.TryParse("1 in⁻²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseSquareInches, InverseSquareInchesTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareInch, parsed.Unit); - } - - { - Assert.True(ReciprocalArea.TryParse("1 km⁻²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseSquareKilometers, InverseSquareKilometersTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareKilometer, parsed.Unit); - } - - { - Assert.True(ReciprocalArea.TryParse("1 m⁻²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseSquareMeters, InverseSquareMetersTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareMeter, parsed.Unit); - } - - { - Assert.True(ReciprocalArea.TryParse("1 µm⁻²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseSquareMicrometers, InverseSquareMicrometersTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareMicrometer, parsed.Unit); - } - - { - Assert.True(ReciprocalArea.TryParse("1 mi⁻²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseSquareMiles, InverseSquareMilesTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareMile, parsed.Unit); - } - - { - Assert.True(ReciprocalArea.TryParse("1 mm⁻²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseSquareMillimeters, InverseSquareMillimetersTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareMillimeter, parsed.Unit); - } - - { - Assert.True(ReciprocalArea.TryParse("1 yd⁻²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseSquareYards, InverseSquareYardsTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseSquareYard, parsed.Unit); - } - - { - Assert.True(ReciprocalArea.TryParse("1 ft⁻² (US)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseUsSurveySquareFeet, InverseUsSurveySquareFeetTolerance); - Assert.Equal(ReciprocalAreaUnit.InverseUsSurveySquareFoot, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ReciprocalArea.TryParse(quantityString, out ReciprocalArea parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -674,6 +579,37 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Recipr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ReciprocalAreaUnit.InverseSquareCentimeter, "cm⁻²")] + [InlineData("en-US", ReciprocalAreaUnit.InverseSquareDecimeter, "dm⁻²")] + [InlineData("en-US", ReciprocalAreaUnit.InverseSquareFoot, "ft⁻²")] + [InlineData("en-US", ReciprocalAreaUnit.InverseSquareInch, "in⁻²")] + [InlineData("en-US", ReciprocalAreaUnit.InverseSquareKilometer, "km⁻²")] + [InlineData("en-US", ReciprocalAreaUnit.InverseSquareMeter, "m⁻²")] + [InlineData("en-US", ReciprocalAreaUnit.InverseSquareMicrometer, "µm⁻²")] + [InlineData("en-US", ReciprocalAreaUnit.InverseSquareMile, "mi⁻²")] + [InlineData("en-US", ReciprocalAreaUnit.InverseSquareMillimeter, "mm⁻²")] + [InlineData("en-US", ReciprocalAreaUnit.InverseSquareYard, "yd⁻²")] + [InlineData("en-US", ReciprocalAreaUnit.InverseUsSurveySquareFoot, "ft⁻² (US)")] + public void GetAbbreviationForCulture(string culture, ReciprocalAreaUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ReciprocalArea.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ReciprocalArea.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ReciprocalArea.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ReciprocalAreaUnit unit) @@ -704,6 +640,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); }); } @@ -727,42 +664,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] @@ -808,8 +747,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); @@ -847,34 +784,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = ReciprocalArea.FromInverseSquareMeters(1); - Assert.True(v.Equals(ReciprocalArea.FromInverseSquareMeters(1), InverseSquareMetersTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ReciprocalArea.Zero, InverseSquareMetersTolerance, ComparisonType.Relative)); - Assert.True(ReciprocalArea.FromInverseSquareMeters(100).Equals(ReciprocalArea.FromInverseSquareMeters(120), 0.3, ComparisonType.Relative)); - Assert.False(ReciprocalArea.FromInverseSquareMeters(100).Equals(ReciprocalArea.FromInverseSquareMeters(120), 0.1, ComparisonType.Relative)); + ReciprocalArea inversesquaremeter = ReciprocalArea.FromInverseSquareMeters(1); + Assert.False(inversesquaremeter.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = ReciprocalArea.FromInverseSquareMeters(1); - Assert.Throws(() => v.Equals(ReciprocalArea.FromInverseSquareMeters(1), -1, ComparisonType.Relative)); + ReciprocalArea inversesquaremeter = ReciprocalArea.FromInverseSquareMeters(1); + Assert.False(inversesquaremeter.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - ReciprocalArea inversesquaremeter = ReciprocalArea.FromInverseSquareMeters(1); - Assert.False(inversesquaremeter.Equals(new object())); + var quantity = ReciprocalArea.FromInverseSquareMeters(firstValue); + var otherQuantity = ReciprocalArea.FromInverseSquareMeters(secondValue); + ReciprocalArea maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - ReciprocalArea inversesquaremeter = ReciprocalArea.FromInverseSquareMeters(1); - Assert.False(inversesquaremeter.Equals(null)); + var quantity = ReciprocalArea.FromInverseSquareMeters(1); + var negativeTolerance = ReciprocalArea.FromInverseSquareMeters(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -893,6 +839,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() { @@ -971,158 +929,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ReciprocalArea))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ReciprocalAreaUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal(ReciprocalArea.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal(ReciprocalArea.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal(new {ReciprocalArea.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 011a7a5381..8a9cfff97f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalLengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalLengthTestsBase.g.cs @@ -132,7 +132,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ReciprocalLength(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -145,15 +145,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ReciprocalLength_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ReciprocalLengthUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ReciprocalLength(1, ReciprocalLengthUnit.InverseMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ReciprocalLength.Zero, quantityInfo.Zero); Assert.Equal("ReciprocalLength", quantityInfo.Name); + Assert.Equal(ReciprocalLength.Zero, quantityInfo.Zero); + Assert.Equal(ReciprocalLength.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ReciprocalLength.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void ReciprocalLengthInfo_CreateWithCustomUnitInfos() + { + ReciprocalLengthUnit[] expectedUnits = [ReciprocalLengthUnit.InverseMeter]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -176,43 +194,43 @@ public void InverseMeterToReciprocalLengthUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ReciprocalLength.From(1, ReciprocalLengthUnit.InverseCentimeter); - AssertEx.EqualTolerance(1, quantity00.InverseCentimeters, InverseCentimetersTolerance); + Assert.Equal(1, quantity00.InverseCentimeters); Assert.Equal(ReciprocalLengthUnit.InverseCentimeter, quantity00.Unit); var quantity01 = ReciprocalLength.From(1, ReciprocalLengthUnit.InverseFoot); - AssertEx.EqualTolerance(1, quantity01.InverseFeet, InverseFeetTolerance); + Assert.Equal(1, quantity01.InverseFeet); Assert.Equal(ReciprocalLengthUnit.InverseFoot, quantity01.Unit); var quantity02 = ReciprocalLength.From(1, ReciprocalLengthUnit.InverseInch); - AssertEx.EqualTolerance(1, quantity02.InverseInches, InverseInchesTolerance); + Assert.Equal(1, quantity02.InverseInches); Assert.Equal(ReciprocalLengthUnit.InverseInch, quantity02.Unit); var quantity03 = ReciprocalLength.From(1, ReciprocalLengthUnit.InverseMeter); - AssertEx.EqualTolerance(1, quantity03.InverseMeters, InverseMetersTolerance); + Assert.Equal(1, quantity03.InverseMeters); Assert.Equal(ReciprocalLengthUnit.InverseMeter, quantity03.Unit); var quantity04 = ReciprocalLength.From(1, ReciprocalLengthUnit.InverseMicroinch); - AssertEx.EqualTolerance(1, quantity04.InverseMicroinches, InverseMicroinchesTolerance); + Assert.Equal(1, quantity04.InverseMicroinches); Assert.Equal(ReciprocalLengthUnit.InverseMicroinch, quantity04.Unit); var quantity05 = ReciprocalLength.From(1, ReciprocalLengthUnit.InverseMil); - AssertEx.EqualTolerance(1, quantity05.InverseMils, InverseMilsTolerance); + Assert.Equal(1, quantity05.InverseMils); Assert.Equal(ReciprocalLengthUnit.InverseMil, quantity05.Unit); var quantity06 = ReciprocalLength.From(1, ReciprocalLengthUnit.InverseMile); - AssertEx.EqualTolerance(1, quantity06.InverseMiles, InverseMilesTolerance); + Assert.Equal(1, quantity06.InverseMiles); Assert.Equal(ReciprocalLengthUnit.InverseMile, quantity06.Unit); var quantity07 = ReciprocalLength.From(1, ReciprocalLengthUnit.InverseMillimeter); - AssertEx.EqualTolerance(1, quantity07.InverseMillimeters, InverseMillimetersTolerance); + Assert.Equal(1, quantity07.InverseMillimeters); Assert.Equal(ReciprocalLengthUnit.InverseMillimeter, quantity07.Unit); var quantity08 = ReciprocalLength.From(1, ReciprocalLengthUnit.InverseUsSurveyFoot); - AssertEx.EqualTolerance(1, quantity08.InverseUsSurveyFeet, InverseUsSurveyFeetTolerance); + Assert.Equal(1, quantity08.InverseUsSurveyFeet); Assert.Equal(ReciprocalLengthUnit.InverseUsSurveyFoot, quantity08.Unit); var quantity09 = ReciprocalLength.From(1, ReciprocalLengthUnit.InverseYard); - AssertEx.EqualTolerance(1, quantity09.InverseYards, InverseYardsTolerance); + Assert.Equal(1, quantity09.InverseYards); Assert.Equal(ReciprocalLengthUnit.InverseYard, quantity09.Unit); } @@ -357,274 +375,62 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 cm⁻¹", ReciprocalLengthUnit.InverseCentimeter, 4.2)] + [InlineData("en-US", "4.2 1/cm", ReciprocalLengthUnit.InverseCentimeter, 4.2)] + [InlineData("en-US", "4.2 ft⁻¹", ReciprocalLengthUnit.InverseFoot, 4.2)] + [InlineData("en-US", "4.2 1/ft", ReciprocalLengthUnit.InverseFoot, 4.2)] + [InlineData("en-US", "4.2 in⁻¹", ReciprocalLengthUnit.InverseInch, 4.2)] + [InlineData("en-US", "4.2 1/in", ReciprocalLengthUnit.InverseInch, 4.2)] + [InlineData("en-US", "4.2 m⁻¹", ReciprocalLengthUnit.InverseMeter, 4.2)] + [InlineData("en-US", "4.2 1/m", ReciprocalLengthUnit.InverseMeter, 4.2)] + [InlineData("en-US", "4.2 µin⁻¹", ReciprocalLengthUnit.InverseMicroinch, 4.2)] + [InlineData("en-US", "4.2 1/µin", ReciprocalLengthUnit.InverseMicroinch, 4.2)] + [InlineData("en-US", "4.2 mil⁻¹", ReciprocalLengthUnit.InverseMil, 4.2)] + [InlineData("en-US", "4.2 1/mil", ReciprocalLengthUnit.InverseMil, 4.2)] + [InlineData("en-US", "4.2 mi⁻¹", ReciprocalLengthUnit.InverseMile, 4.2)] + [InlineData("en-US", "4.2 1/mi", ReciprocalLengthUnit.InverseMile, 4.2)] + [InlineData("en-US", "4.2 mm⁻¹", ReciprocalLengthUnit.InverseMillimeter, 4.2)] + [InlineData("en-US", "4.2 1/mm", ReciprocalLengthUnit.InverseMillimeter, 4.2)] + [InlineData("en-US", "4.2 ftUS⁻¹", ReciprocalLengthUnit.InverseUsSurveyFoot, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = ReciprocalLength.Parse("1 cm⁻¹", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseCentimeters, InverseCentimetersTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalLength.Parse("1 1/cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseCentimeters, InverseCentimetersTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalLength.Parse("1 ft⁻¹", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseFeet, InverseFeetTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalLength.Parse("1 1/ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseFeet, InverseFeetTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalLength.Parse("1 in⁻¹", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseInches, InverseInchesTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalLength.Parse("1 1/in", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseInches, InverseInchesTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalLength.Parse("1 m⁻¹", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseMeters, InverseMetersTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalLength.Parse("1 1/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseMeters, InverseMetersTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalLength.Parse("1 µin⁻¹", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseMicroinches, InverseMicroinchesTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseMicroinch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalLength.Parse("1 1/µin", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseMicroinches, InverseMicroinchesTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseMicroinch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalLength.Parse("1 mil⁻¹", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseMils, InverseMilsTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseMil, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalLength.Parse("1 1/mil", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseMils, InverseMilsTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseMil, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalLength.Parse("1 mi⁻¹", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseMiles, InverseMilesTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseMile, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalLength.Parse("1 1/mi", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseMiles, InverseMilesTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseMile, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalLength.Parse("1 mm⁻¹", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseMillimeters, InverseMillimetersTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalLength.Parse("1 1/mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseMillimeters, InverseMillimetersTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalLength.Parse("1 ftUS⁻¹", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseUsSurveyFeet, InverseUsSurveyFeetTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseUsSurveyFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalLength.Parse("1 1/ftUS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseUsSurveyFeet, InverseUsSurveyFeetTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseUsSurveyFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalLength.Parse("1 yd⁻¹", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseYards, InverseYardsTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseYard, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ReciprocalLength.Parse("1 1/yd", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InverseYards, InverseYardsTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseYard, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ReciprocalLength.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 cm⁻¹", ReciprocalLengthUnit.InverseCentimeter, 4.2)] + [InlineData("en-US", "4.2 1/cm", ReciprocalLengthUnit.InverseCentimeter, 4.2)] + [InlineData("en-US", "4.2 ft⁻¹", ReciprocalLengthUnit.InverseFoot, 4.2)] + [InlineData("en-US", "4.2 1/ft", ReciprocalLengthUnit.InverseFoot, 4.2)] + [InlineData("en-US", "4.2 in⁻¹", ReciprocalLengthUnit.InverseInch, 4.2)] + [InlineData("en-US", "4.2 1/in", ReciprocalLengthUnit.InverseInch, 4.2)] + [InlineData("en-US", "4.2 m⁻¹", ReciprocalLengthUnit.InverseMeter, 4.2)] + [InlineData("en-US", "4.2 1/m", ReciprocalLengthUnit.InverseMeter, 4.2)] + [InlineData("en-US", "4.2 µin⁻¹", ReciprocalLengthUnit.InverseMicroinch, 4.2)] + [InlineData("en-US", "4.2 1/µin", ReciprocalLengthUnit.InverseMicroinch, 4.2)] + [InlineData("en-US", "4.2 mil⁻¹", ReciprocalLengthUnit.InverseMil, 4.2)] + [InlineData("en-US", "4.2 1/mil", ReciprocalLengthUnit.InverseMil, 4.2)] + [InlineData("en-US", "4.2 mi⁻¹", ReciprocalLengthUnit.InverseMile, 4.2)] + [InlineData("en-US", "4.2 1/mi", ReciprocalLengthUnit.InverseMile, 4.2)] + [InlineData("en-US", "4.2 mm⁻¹", ReciprocalLengthUnit.InverseMillimeter, 4.2)] + [InlineData("en-US", "4.2 1/mm", ReciprocalLengthUnit.InverseMillimeter, 4.2)] + [InlineData("en-US", "4.2 ftUS⁻¹", ReciprocalLengthUnit.InverseUsSurveyFoot, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(ReciprocalLength.TryParse("1 cm⁻¹", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseCentimeters, InverseCentimetersTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseCentimeter, parsed.Unit); - } - - { - Assert.True(ReciprocalLength.TryParse("1 1/cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseCentimeters, InverseCentimetersTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseCentimeter, parsed.Unit); - } - - { - Assert.True(ReciprocalLength.TryParse("1 ft⁻¹", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseFeet, InverseFeetTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseFoot, parsed.Unit); - } - - { - Assert.True(ReciprocalLength.TryParse("1 1/ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseFeet, InverseFeetTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseFoot, parsed.Unit); - } - - { - Assert.True(ReciprocalLength.TryParse("1 in⁻¹", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseInches, InverseInchesTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseInch, parsed.Unit); - } - - { - Assert.True(ReciprocalLength.TryParse("1 1/in", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseInches, InverseInchesTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseInch, parsed.Unit); - } - - { - Assert.True(ReciprocalLength.TryParse("1 m⁻¹", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseMeters, InverseMetersTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseMeter, parsed.Unit); - } - - { - Assert.True(ReciprocalLength.TryParse("1 1/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseMeters, InverseMetersTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseMeter, parsed.Unit); - } - - { - Assert.True(ReciprocalLength.TryParse("1 µin⁻¹", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseMicroinches, InverseMicroinchesTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseMicroinch, parsed.Unit); - } - - { - Assert.True(ReciprocalLength.TryParse("1 1/µin", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseMicroinches, InverseMicroinchesTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseMicroinch, parsed.Unit); - } - - { - Assert.True(ReciprocalLength.TryParse("1 mil⁻¹", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseMils, InverseMilsTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseMil, parsed.Unit); - } - - { - Assert.True(ReciprocalLength.TryParse("1 1/mil", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseMils, InverseMilsTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseMil, parsed.Unit); - } - - { - Assert.True(ReciprocalLength.TryParse("1 mi⁻¹", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseMiles, InverseMilesTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseMile, parsed.Unit); - } - - { - Assert.True(ReciprocalLength.TryParse("1 1/mi", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseMiles, InverseMilesTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseMile, parsed.Unit); - } - - { - Assert.True(ReciprocalLength.TryParse("1 mm⁻¹", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseMillimeters, InverseMillimetersTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseMillimeter, parsed.Unit); - } - - { - Assert.True(ReciprocalLength.TryParse("1 1/mm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseMillimeters, InverseMillimetersTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseMillimeter, parsed.Unit); - } - - { - Assert.True(ReciprocalLength.TryParse("1 ftUS⁻¹", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseUsSurveyFeet, InverseUsSurveyFeetTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseUsSurveyFoot, parsed.Unit); - } - - { - Assert.True(ReciprocalLength.TryParse("1 1/ftUS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseUsSurveyFeet, InverseUsSurveyFeetTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseUsSurveyFoot, parsed.Unit); - } - - { - Assert.True(ReciprocalLength.TryParse("1 yd⁻¹", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseYards, InverseYardsTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseYard, parsed.Unit); - } - - { - Assert.True(ReciprocalLength.TryParse("1 1/yd", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InverseYards, InverseYardsTolerance); - Assert.Equal(ReciprocalLengthUnit.InverseYard, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ReciprocalLength.TryParse(quantityString, out ReciprocalLength parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -853,6 +659,36 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Recipr Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ReciprocalLengthUnit.InverseCentimeter, "cm⁻¹")] + [InlineData("en-US", ReciprocalLengthUnit.InverseFoot, "ft⁻¹")] + [InlineData("en-US", ReciprocalLengthUnit.InverseInch, "in⁻¹")] + [InlineData("en-US", ReciprocalLengthUnit.InverseMeter, "m⁻¹")] + [InlineData("en-US", ReciprocalLengthUnit.InverseMicroinch, "µin⁻¹")] + [InlineData("en-US", ReciprocalLengthUnit.InverseMil, "mil⁻¹")] + [InlineData("en-US", ReciprocalLengthUnit.InverseMile, "mi⁻¹")] + [InlineData("en-US", ReciprocalLengthUnit.InverseMillimeter, "mm⁻¹")] + [InlineData("en-US", ReciprocalLengthUnit.InverseUsSurveyFoot, "ftUS⁻¹")] + [InlineData("en-US", ReciprocalLengthUnit.InverseYard, "yd⁻¹")] + public void GetAbbreviationForCulture(string culture, ReciprocalLengthUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ReciprocalLength.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ReciprocalLength.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ReciprocalLength.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ReciprocalLengthUnit unit) @@ -883,6 +719,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); }); } @@ -906,41 +743,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] @@ -986,8 +825,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); @@ -1024,23 +861,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = ReciprocalLength.FromInverseMeters(1); - Assert.True(v.Equals(ReciprocalLength.FromInverseMeters(1), InverseMetersTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ReciprocalLength.Zero, InverseMetersTolerance, ComparisonType.Relative)); - Assert.True(ReciprocalLength.FromInverseMeters(100).Equals(ReciprocalLength.FromInverseMeters(120), 0.3, ComparisonType.Relative)); - Assert.False(ReciprocalLength.FromInverseMeters(100).Equals(ReciprocalLength.FromInverseMeters(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = ReciprocalLength.FromInverseMeters(1); - Assert.Throws(() => v.Equals(ReciprocalLength.FromInverseMeters(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1055,6 +875,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(inversemeter.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = ReciprocalLength.FromInverseMeters(1); + var negativeTolerance = ReciprocalLength.FromInverseMeters(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1071,6 +917,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() { @@ -1147,158 +1005,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ReciprocalLength))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ReciprocalLengthUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal(ReciprocalLength.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal(ReciprocalLength.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal(new {ReciprocalLength.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 6d27aae36f..3fc5616de5 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RelativeHumidityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RelativeHumidityTestsBase.g.cs @@ -88,15 +88,33 @@ public void Ctor_WithNaNValue_DoNotThrowsArgumentException() [Fact] public void RelativeHumidity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + RelativeHumidityUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new RelativeHumidity(1, RelativeHumidityUnit.Percent); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(RelativeHumidity.Zero, quantityInfo.Zero); Assert.Equal("RelativeHumidity", quantityInfo.Name); + Assert.Equal(RelativeHumidity.Zero, quantityInfo.Zero); + Assert.Equal(RelativeHumidity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(RelativeHumidity.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -110,7 +128,7 @@ public void PercentToRelativeHumidityUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = RelativeHumidity.From(1, RelativeHumidityUnit.Percent); - AssertEx.EqualTolerance(1, quantity00.Percent, PercentTolerance); + Assert.Equal(1, quantity00.Percent); Assert.Equal(RelativeHumidityUnit.Percent, quantity00.Unit); } @@ -207,27 +225,24 @@ public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 %RH", RelativeHumidityUnit.Percent, 4.2)] + public void Parse(string culture, string quantityString, RelativeHumidityUnit expectedUnit, decimal expectedValue) { - try - { - var parsed = RelativeHumidity.Parse("1 %RH", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Percent, PercentTolerance); - Assert.Equal(RelativeHumidityUnit.Percent, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = RelativeHumidity.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 %RH", RelativeHumidityUnit.Percent, 4.2)] + public void TryParse(string culture, string quantityString, RelativeHumidityUnit expectedUnit, decimal expectedValue) { - { - Assert.True(RelativeHumidity.TryParse("1 %RH", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Percent, PercentTolerance); - Assert.Equal(RelativeHumidityUnit.Percent, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(RelativeHumidity.TryParse(quantityString, out RelativeHumidity parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -304,6 +319,27 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Relati Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", RelativeHumidityUnit.Percent, "%RH")] + public void GetAbbreviationForCulture(string culture, RelativeHumidityUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = RelativeHumidity.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(RelativeHumidity.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = RelativeHumidity.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(RelativeHumidityUnit unit) @@ -334,6 +370,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); }); } @@ -357,32 +394,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] @@ -428,7 +467,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); @@ -466,34 +504,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = RelativeHumidity.FromPercent(1); - Assert.True(v.Equals(RelativeHumidity.FromPercent(1), PercentTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(RelativeHumidity.Zero, PercentTolerance, ComparisonType.Relative)); - Assert.True(RelativeHumidity.FromPercent(100).Equals(RelativeHumidity.FromPercent(120), 0.3, ComparisonType.Relative)); - Assert.False(RelativeHumidity.FromPercent(100).Equals(RelativeHumidity.FromPercent(120), 0.1, ComparisonType.Relative)); + RelativeHumidity percent = RelativeHumidity.FromPercent(1); + Assert.False(percent.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = RelativeHumidity.FromPercent(1); - Assert.Throws(() => v.Equals(RelativeHumidity.FromPercent(1), -1, ComparisonType.Relative)); + RelativeHumidity percent = RelativeHumidity.FromPercent(1); + Assert.False(percent.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - RelativeHumidity percent = RelativeHumidity.FromPercent(1); - Assert.False(percent.Equals(new object())); + var quantity = RelativeHumidity.FromPercent(firstValue); + var otherQuantity = RelativeHumidity.FromPercent(secondValue); + RelativeHumidity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - RelativeHumidity percent = RelativeHumidity.FromPercent(1); - Assert.False(percent.Equals(null)); + var quantity = RelativeHumidity.FromPercent(1); + var negativeTolerance = RelativeHumidity.FromPercent(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -512,6 +559,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() { @@ -570,158 +629,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(RelativeHumidity))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(RelativeHumidityUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal(RelativeHumidity.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal(RelativeHumidity.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal(new {RelativeHumidity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 754123dbd1..39724a50c6 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalAccelerationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalAccelerationTestsBase.g.cs @@ -108,7 +108,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new RotationalAcceleration(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -121,15 +121,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void RotationalAcceleration_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + RotationalAccelerationUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new RotationalAcceleration(1, RotationalAccelerationUnit.RadianPerSecondSquared); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(RotationalAcceleration.Zero, quantityInfo.Zero); Assert.Equal("RotationalAcceleration", quantityInfo.Name); + Assert.Equal(RotationalAcceleration.Zero, quantityInfo.Zero); + Assert.Equal(RotationalAcceleration.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(RotationalAcceleration.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void RotationalAccelerationInfo_CreateWithCustomUnitInfos() + { + RotationalAccelerationUnit[] expectedUnits = [RotationalAccelerationUnit.RadianPerSecondSquared]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -146,19 +164,19 @@ public void RadianPerSecondSquaredToRotationalAccelerationUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = RotationalAcceleration.From(1, RotationalAccelerationUnit.DegreePerSecondSquared); - AssertEx.EqualTolerance(1, quantity00.DegreesPerSecondSquared, DegreesPerSecondSquaredTolerance); + Assert.Equal(1, quantity00.DegreesPerSecondSquared); Assert.Equal(RotationalAccelerationUnit.DegreePerSecondSquared, quantity00.Unit); var quantity01 = RotationalAcceleration.From(1, RotationalAccelerationUnit.RadianPerSecondSquared); - AssertEx.EqualTolerance(1, quantity01.RadiansPerSecondSquared, RadiansPerSecondSquaredTolerance); + Assert.Equal(1, quantity01.RadiansPerSecondSquared); Assert.Equal(RotationalAccelerationUnit.RadianPerSecondSquared, quantity01.Unit); var quantity02 = RotationalAcceleration.From(1, RotationalAccelerationUnit.RevolutionPerMinutePerSecond); - AssertEx.EqualTolerance(1, quantity02.RevolutionsPerMinutePerSecond, RevolutionsPerMinutePerSecondTolerance); + Assert.Equal(1, quantity02.RevolutionsPerMinutePerSecond); Assert.Equal(RotationalAccelerationUnit.RevolutionPerMinutePerSecond, quantity02.Unit); var quantity03 = RotationalAcceleration.From(1, RotationalAccelerationUnit.RevolutionPerSecondSquared); - AssertEx.EqualTolerance(1, quantity03.RevolutionsPerSecondSquared, RevolutionsPerSecondSquaredTolerance); + Assert.Equal(1, quantity03.RevolutionsPerSecondSquared); Assert.Equal(RotationalAccelerationUnit.RevolutionPerSecondSquared, quantity03.Unit); } @@ -297,79 +315,32 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 °/s²", RotationalAccelerationUnit.DegreePerSecondSquared, 4.2)] + [InlineData("en-US", "4.2 deg/s²", RotationalAccelerationUnit.DegreePerSecondSquared, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = RotationalAcceleration.Parse("1 °/s²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesPerSecondSquared, DegreesPerSecondSquaredTolerance); - Assert.Equal(RotationalAccelerationUnit.DegreePerSecondSquared, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalAcceleration.Parse("1 deg/s²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesPerSecondSquared, DegreesPerSecondSquaredTolerance); - Assert.Equal(RotationalAccelerationUnit.DegreePerSecondSquared, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalAcceleration.Parse("1 rad/s²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.RadiansPerSecondSquared, RadiansPerSecondSquaredTolerance); - Assert.Equal(RotationalAccelerationUnit.RadianPerSecondSquared, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalAcceleration.Parse("1 rpm/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.RevolutionsPerMinutePerSecond, RevolutionsPerMinutePerSecondTolerance); - Assert.Equal(RotationalAccelerationUnit.RevolutionPerMinutePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalAcceleration.Parse("1 r/s²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.RevolutionsPerSecondSquared, RevolutionsPerSecondSquaredTolerance); - Assert.Equal(RotationalAccelerationUnit.RevolutionPerSecondSquared, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = RotationalAcceleration.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 °/s²", RotationalAccelerationUnit.DegreePerSecondSquared, 4.2)] + [InlineData("en-US", "4.2 deg/s²", RotationalAccelerationUnit.DegreePerSecondSquared, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(RotationalAcceleration.TryParse("1 °/s²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesPerSecondSquared, DegreesPerSecondSquaredTolerance); - Assert.Equal(RotationalAccelerationUnit.DegreePerSecondSquared, parsed.Unit); - } - - { - Assert.True(RotationalAcceleration.TryParse("1 deg/s²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesPerSecondSquared, DegreesPerSecondSquaredTolerance); - Assert.Equal(RotationalAccelerationUnit.DegreePerSecondSquared, parsed.Unit); - } - - { - Assert.True(RotationalAcceleration.TryParse("1 rad/s²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.RadiansPerSecondSquared, RadiansPerSecondSquaredTolerance); - Assert.Equal(RotationalAccelerationUnit.RadianPerSecondSquared, parsed.Unit); - } - - { - Assert.True(RotationalAcceleration.TryParse("1 rpm/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.RevolutionsPerMinutePerSecond, RevolutionsPerMinutePerSecondTolerance); - Assert.Equal(RotationalAccelerationUnit.RevolutionPerMinutePerSecond, parsed.Unit); - } - - { - Assert.True(RotationalAcceleration.TryParse("1 r/s²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.RevolutionsPerSecondSquared, RevolutionsPerSecondSquaredTolerance); - Assert.Equal(RotationalAccelerationUnit.RevolutionPerSecondSquared, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(RotationalAcceleration.TryParse(quantityString, out RotationalAcceleration parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -478,6 +449,30 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Rotati Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", RotationalAccelerationUnit.DegreePerSecondSquared, "°/s²")] + [InlineData("en-US", RotationalAccelerationUnit.RadianPerSecondSquared, "rad/s²")] + [InlineData("en-US", RotationalAccelerationUnit.RevolutionPerMinutePerSecond, "rpm/s")] + [InlineData("en-US", RotationalAccelerationUnit.RevolutionPerSecondSquared, "r/s²")] + public void GetAbbreviationForCulture(string culture, RotationalAccelerationUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = RotationalAcceleration.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(RotationalAcceleration.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = RotationalAcceleration.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(RotationalAccelerationUnit unit) @@ -508,6 +503,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); }); } @@ -531,35 +527,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] @@ -605,8 +603,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); @@ -644,34 +640,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = RotationalAcceleration.FromRadiansPerSecondSquared(1); - Assert.True(v.Equals(RotationalAcceleration.FromRadiansPerSecondSquared(1), RadiansPerSecondSquaredTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(RotationalAcceleration.Zero, RadiansPerSecondSquaredTolerance, ComparisonType.Relative)); - Assert.True(RotationalAcceleration.FromRadiansPerSecondSquared(100).Equals(RotationalAcceleration.FromRadiansPerSecondSquared(120), 0.3, ComparisonType.Relative)); - Assert.False(RotationalAcceleration.FromRadiansPerSecondSquared(100).Equals(RotationalAcceleration.FromRadiansPerSecondSquared(120), 0.1, ComparisonType.Relative)); + RotationalAcceleration radianpersecondsquared = RotationalAcceleration.FromRadiansPerSecondSquared(1); + Assert.False(radianpersecondsquared.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = RotationalAcceleration.FromRadiansPerSecondSquared(1); - Assert.Throws(() => v.Equals(RotationalAcceleration.FromRadiansPerSecondSquared(1), -1, ComparisonType.Relative)); + RotationalAcceleration radianpersecondsquared = RotationalAcceleration.FromRadiansPerSecondSquared(1); + Assert.False(radianpersecondsquared.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - RotationalAcceleration radianpersecondsquared = RotationalAcceleration.FromRadiansPerSecondSquared(1); - Assert.False(radianpersecondsquared.Equals(new object())); + var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(firstValue); + var otherQuantity = RotationalAcceleration.FromRadiansPerSecondSquared(secondValue); + RotationalAcceleration maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - RotationalAcceleration radianpersecondsquared = RotationalAcceleration.FromRadiansPerSecondSquared(1); - Assert.False(radianpersecondsquared.Equals(null)); + var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1); + var negativeTolerance = RotationalAcceleration.FromRadiansPerSecondSquared(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -690,6 +695,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() { @@ -754,158 +771,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(RotationalAcceleration))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(RotationalAccelerationUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal(RotationalAcceleration.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal(RotationalAcceleration.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal(new {RotationalAcceleration.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 63f25332e1..289ab83ce1 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalSpeedTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalSpeedTestsBase.g.cs @@ -144,7 +144,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new RotationalSpeed(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -157,15 +157,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void RotationalSpeed_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + RotationalSpeedUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new RotationalSpeed(1, RotationalSpeedUnit.RadianPerSecond); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(RotationalSpeed.Zero, quantityInfo.Zero); Assert.Equal("RotationalSpeed", quantityInfo.Name); + Assert.Equal(RotationalSpeed.Zero, quantityInfo.Zero); + Assert.Equal(RotationalSpeed.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(RotationalSpeed.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -191,55 +209,55 @@ public void RadianPerSecondToRotationalSpeedUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = RotationalSpeed.From(1, RotationalSpeedUnit.CentiradianPerSecond); - AssertEx.EqualTolerance(1, quantity00.CentiradiansPerSecond, CentiradiansPerSecondTolerance); + Assert.Equal(1, quantity00.CentiradiansPerSecond); Assert.Equal(RotationalSpeedUnit.CentiradianPerSecond, quantity00.Unit); var quantity01 = RotationalSpeed.From(1, RotationalSpeedUnit.DeciradianPerSecond); - AssertEx.EqualTolerance(1, quantity01.DeciradiansPerSecond, DeciradiansPerSecondTolerance); + Assert.Equal(1, quantity01.DeciradiansPerSecond); Assert.Equal(RotationalSpeedUnit.DeciradianPerSecond, quantity01.Unit); var quantity02 = RotationalSpeed.From(1, RotationalSpeedUnit.DegreePerMinute); - AssertEx.EqualTolerance(1, quantity02.DegreesPerMinute, DegreesPerMinuteTolerance); + Assert.Equal(1, quantity02.DegreesPerMinute); Assert.Equal(RotationalSpeedUnit.DegreePerMinute, quantity02.Unit); var quantity03 = RotationalSpeed.From(1, RotationalSpeedUnit.DegreePerSecond); - AssertEx.EqualTolerance(1, quantity03.DegreesPerSecond, DegreesPerSecondTolerance); + Assert.Equal(1, quantity03.DegreesPerSecond); Assert.Equal(RotationalSpeedUnit.DegreePerSecond, quantity03.Unit); var quantity04 = RotationalSpeed.From(1, RotationalSpeedUnit.MicrodegreePerSecond); - AssertEx.EqualTolerance(1, quantity04.MicrodegreesPerSecond, MicrodegreesPerSecondTolerance); + Assert.Equal(1, quantity04.MicrodegreesPerSecond); Assert.Equal(RotationalSpeedUnit.MicrodegreePerSecond, quantity04.Unit); var quantity05 = RotationalSpeed.From(1, RotationalSpeedUnit.MicroradianPerSecond); - AssertEx.EqualTolerance(1, quantity05.MicroradiansPerSecond, MicroradiansPerSecondTolerance); + Assert.Equal(1, quantity05.MicroradiansPerSecond); Assert.Equal(RotationalSpeedUnit.MicroradianPerSecond, quantity05.Unit); var quantity06 = RotationalSpeed.From(1, RotationalSpeedUnit.MillidegreePerSecond); - AssertEx.EqualTolerance(1, quantity06.MillidegreesPerSecond, MillidegreesPerSecondTolerance); + Assert.Equal(1, quantity06.MillidegreesPerSecond); Assert.Equal(RotationalSpeedUnit.MillidegreePerSecond, quantity06.Unit); var quantity07 = RotationalSpeed.From(1, RotationalSpeedUnit.MilliradianPerSecond); - AssertEx.EqualTolerance(1, quantity07.MilliradiansPerSecond, MilliradiansPerSecondTolerance); + Assert.Equal(1, quantity07.MilliradiansPerSecond); Assert.Equal(RotationalSpeedUnit.MilliradianPerSecond, quantity07.Unit); var quantity08 = RotationalSpeed.From(1, RotationalSpeedUnit.NanodegreePerSecond); - AssertEx.EqualTolerance(1, quantity08.NanodegreesPerSecond, NanodegreesPerSecondTolerance); + Assert.Equal(1, quantity08.NanodegreesPerSecond); Assert.Equal(RotationalSpeedUnit.NanodegreePerSecond, quantity08.Unit); var quantity09 = RotationalSpeed.From(1, RotationalSpeedUnit.NanoradianPerSecond); - AssertEx.EqualTolerance(1, quantity09.NanoradiansPerSecond, NanoradiansPerSecondTolerance); + Assert.Equal(1, quantity09.NanoradiansPerSecond); Assert.Equal(RotationalSpeedUnit.NanoradianPerSecond, quantity09.Unit); var quantity10 = RotationalSpeed.From(1, RotationalSpeedUnit.RadianPerSecond); - AssertEx.EqualTolerance(1, quantity10.RadiansPerSecond, RadiansPerSecondTolerance); + Assert.Equal(1, quantity10.RadiansPerSecond); Assert.Equal(RotationalSpeedUnit.RadianPerSecond, quantity10.Unit); var quantity11 = RotationalSpeed.From(1, RotationalSpeedUnit.RevolutionPerMinute); - AssertEx.EqualTolerance(1, quantity11.RevolutionsPerMinute, RevolutionsPerMinuteTolerance); + Assert.Equal(1, quantity11.RevolutionsPerMinute); Assert.Equal(RotationalSpeedUnit.RevolutionPerMinute, quantity11.Unit); var quantity12 = RotationalSpeed.From(1, RotationalSpeedUnit.RevolutionPerSecond); - AssertEx.EqualTolerance(1, quantity12.RevolutionsPerSecond, RevolutionsPerSecondTolerance); + Assert.Equal(1, quantity12.RevolutionsPerSecond); Assert.Equal(RotationalSpeedUnit.RevolutionPerSecond, quantity12.Unit); } @@ -387,417 +405,84 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 crad/s", RotationalSpeedUnit.CentiradianPerSecond, 4.2)] + [InlineData("en-US", "4.2 drad/s", RotationalSpeedUnit.DeciradianPerSecond, 4.2)] + [InlineData("en-US", "4.2 °/min", RotationalSpeedUnit.DegreePerMinute, 4.2)] + [InlineData("en-US", "4.2 deg/min", RotationalSpeedUnit.DegreePerMinute, 4.2)] + [InlineData("en-US", "4.2 °/s", RotationalSpeedUnit.DegreePerSecond, 4.2)] + [InlineData("en-US", "4.2 deg/s", RotationalSpeedUnit.DegreePerSecond, 4.2)] + [InlineData("en-US", "4.2 µ°/s", RotationalSpeedUnit.MicrodegreePerSecond, 4.2)] + [InlineData("en-US", "4.2 µdeg/s", RotationalSpeedUnit.MicrodegreePerSecond, 4.2)] + [InlineData("en-US", "4.2 µrad/s", RotationalSpeedUnit.MicroradianPerSecond, 4.2)] + [InlineData("en-US", "4.2 m°/s", RotationalSpeedUnit.MillidegreePerSecond, 4.2)] + [InlineData("en-US", "4.2 mdeg/s", RotationalSpeedUnit.MillidegreePerSecond, 4.2)] + [InlineData("en-US", "4.2 mrad/s", RotationalSpeedUnit.MilliradianPerSecond, 4.2)] + [InlineData("en-US", "4.2 n°/s", RotationalSpeedUnit.NanodegreePerSecond, 4.2)] + [InlineData("en-US", "4.2 ndeg/s", RotationalSpeedUnit.NanodegreePerSecond, 4.2)] + [InlineData("en-US", "4.2 nrad/s", RotationalSpeedUnit.NanoradianPerSecond, 4.2)] + [InlineData("en-US", "4.2 rad/s", RotationalSpeedUnit.RadianPerSecond, 4.2)] + [InlineData("en-US", "4.2 rpm", RotationalSpeedUnit.RevolutionPerMinute, 4.2)] + [InlineData("en-US", "4.2 r/min", RotationalSpeedUnit.RevolutionPerMinute, 4.2)] + [InlineData("en-US", "4.2 r/s", RotationalSpeedUnit.RevolutionPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 срад/с", RotationalSpeedUnit.CentiradianPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 драд/с", RotationalSpeedUnit.DeciradianPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 °/с", RotationalSpeedUnit.DegreePerSecond, 4.2)] + [InlineData("ru-RU", "4,2 мк°/с", RotationalSpeedUnit.MicrodegreePerSecond, 4.2)] + [InlineData("ru-RU", "4,2 мкрад/с", RotationalSpeedUnit.MicroradianPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 м°/с", RotationalSpeedUnit.MillidegreePerSecond, 4.2)] + [InlineData("ru-RU", "4,2 мрад/с", RotationalSpeedUnit.MilliradianPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 н°/с", RotationalSpeedUnit.NanodegreePerSecond, 4.2)] + [InlineData("ru-RU", "4,2 нрад/с", RotationalSpeedUnit.NanoradianPerSecond, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = RotationalSpeed.Parse("1 crad/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentiradiansPerSecond, CentiradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.CentiradianPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 срад/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CentiradiansPerSecond, CentiradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.CentiradianPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 drad/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DeciradiansPerSecond, DeciradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.DeciradianPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 драд/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.DeciradiansPerSecond, DeciradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.DeciradianPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 °/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesPerMinute, DegreesPerMinuteTolerance); - Assert.Equal(RotationalSpeedUnit.DegreePerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 deg/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesPerMinute, DegreesPerMinuteTolerance); - Assert.Equal(RotationalSpeedUnit.DegreePerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 °/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesPerSecond, DegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.DegreePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 deg/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesPerSecond, DegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.DegreePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 °/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.DegreesPerSecond, DegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.DegreePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 µ°/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrodegreesPerSecond, MicrodegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MicrodegreePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 µdeg/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrodegreesPerSecond, MicrodegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MicrodegreePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 мк°/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MicrodegreesPerSecond, MicrodegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MicrodegreePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 µrad/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicroradiansPerSecond, MicroradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MicroradianPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 мкрад/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MicroradiansPerSecond, MicroradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MicroradianPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 m°/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillidegreesPerSecond, MillidegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MillidegreePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 mdeg/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillidegreesPerSecond, MillidegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MillidegreePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 м°/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MillidegreesPerSecond, MillidegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MillidegreePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 mrad/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilliradiansPerSecond, MilliradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MilliradianPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 мрад/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MilliradiansPerSecond, MilliradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MilliradianPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 n°/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanodegreesPerSecond, NanodegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.NanodegreePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 ndeg/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanodegreesPerSecond, NanodegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.NanodegreePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 н°/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.NanodegreesPerSecond, NanodegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.NanodegreePerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 nrad/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanoradiansPerSecond, NanoradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.NanoradianPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 нрад/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.NanoradiansPerSecond, NanoradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.NanoradianPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 rad/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.RadiansPerSecond, RadiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.RadianPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 рад/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.RadiansPerSecond, RadiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.RadianPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 rpm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.RevolutionsPerMinute, RevolutionsPerMinuteTolerance); - Assert.Equal(RotationalSpeedUnit.RevolutionPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 r/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.RevolutionsPerMinute, RevolutionsPerMinuteTolerance); - Assert.Equal(RotationalSpeedUnit.RevolutionPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 об/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.RevolutionsPerMinute, RevolutionsPerMinuteTolerance); - Assert.Equal(RotationalSpeedUnit.RevolutionPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 r/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.RevolutionsPerSecond, RevolutionsPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.RevolutionPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalSpeed.Parse("1 об/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.RevolutionsPerSecond, RevolutionsPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.RevolutionPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = RotationalSpeed.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 crad/s", RotationalSpeedUnit.CentiradianPerSecond, 4.2)] + [InlineData("en-US", "4.2 drad/s", RotationalSpeedUnit.DeciradianPerSecond, 4.2)] + [InlineData("en-US", "4.2 °/min", RotationalSpeedUnit.DegreePerMinute, 4.2)] + [InlineData("en-US", "4.2 deg/min", RotationalSpeedUnit.DegreePerMinute, 4.2)] + [InlineData("en-US", "4.2 °/s", RotationalSpeedUnit.DegreePerSecond, 4.2)] + [InlineData("en-US", "4.2 deg/s", RotationalSpeedUnit.DegreePerSecond, 4.2)] + [InlineData("en-US", "4.2 µ°/s", RotationalSpeedUnit.MicrodegreePerSecond, 4.2)] + [InlineData("en-US", "4.2 µdeg/s", RotationalSpeedUnit.MicrodegreePerSecond, 4.2)] + [InlineData("en-US", "4.2 µrad/s", RotationalSpeedUnit.MicroradianPerSecond, 4.2)] + [InlineData("en-US", "4.2 m°/s", RotationalSpeedUnit.MillidegreePerSecond, 4.2)] + [InlineData("en-US", "4.2 mdeg/s", RotationalSpeedUnit.MillidegreePerSecond, 4.2)] + [InlineData("en-US", "4.2 mrad/s", RotationalSpeedUnit.MilliradianPerSecond, 4.2)] + [InlineData("en-US", "4.2 n°/s", RotationalSpeedUnit.NanodegreePerSecond, 4.2)] + [InlineData("en-US", "4.2 ndeg/s", RotationalSpeedUnit.NanodegreePerSecond, 4.2)] + [InlineData("en-US", "4.2 nrad/s", RotationalSpeedUnit.NanoradianPerSecond, 4.2)] + [InlineData("en-US", "4.2 rad/s", RotationalSpeedUnit.RadianPerSecond, 4.2)] + [InlineData("en-US", "4.2 rpm", RotationalSpeedUnit.RevolutionPerMinute, 4.2)] + [InlineData("en-US", "4.2 r/min", RotationalSpeedUnit.RevolutionPerMinute, 4.2)] + [InlineData("en-US", "4.2 r/s", RotationalSpeedUnit.RevolutionPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 срад/с", RotationalSpeedUnit.CentiradianPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 драд/с", RotationalSpeedUnit.DeciradianPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 °/с", RotationalSpeedUnit.DegreePerSecond, 4.2)] + [InlineData("ru-RU", "4,2 мк°/с", RotationalSpeedUnit.MicrodegreePerSecond, 4.2)] + [InlineData("ru-RU", "4,2 мкрад/с", RotationalSpeedUnit.MicroradianPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 м°/с", RotationalSpeedUnit.MillidegreePerSecond, 4.2)] + [InlineData("ru-RU", "4,2 мрад/с", RotationalSpeedUnit.MilliradianPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 н°/с", RotationalSpeedUnit.NanodegreePerSecond, 4.2)] + [InlineData("ru-RU", "4,2 нрад/с", RotationalSpeedUnit.NanoradianPerSecond, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(RotationalSpeed.TryParse("1 crad/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentiradiansPerSecond, CentiradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.CentiradianPerSecond, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 срад/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentiradiansPerSecond, CentiradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.CentiradianPerSecond, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 drad/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DeciradiansPerSecond, DeciradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.DeciradianPerSecond, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 драд/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DeciradiansPerSecond, DeciradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.DeciradianPerSecond, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 °/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesPerMinute, DegreesPerMinuteTolerance); - Assert.Equal(RotationalSpeedUnit.DegreePerMinute, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 deg/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesPerMinute, DegreesPerMinuteTolerance); - Assert.Equal(RotationalSpeedUnit.DegreePerMinute, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 °/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesPerSecond, DegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.DegreePerSecond, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 deg/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesPerSecond, DegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.DegreePerSecond, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 °/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesPerSecond, DegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.DegreePerSecond, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 µ°/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrodegreesPerSecond, MicrodegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MicrodegreePerSecond, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 µdeg/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrodegreesPerSecond, MicrodegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MicrodegreePerSecond, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 мк°/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrodegreesPerSecond, MicrodegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MicrodegreePerSecond, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 µrad/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicroradiansPerSecond, MicroradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MicroradianPerSecond, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 мкрад/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicroradiansPerSecond, MicroradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MicroradianPerSecond, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 m°/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillidegreesPerSecond, MillidegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MillidegreePerSecond, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 mdeg/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillidegreesPerSecond, MillidegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MillidegreePerSecond, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 м°/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillidegreesPerSecond, MillidegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MillidegreePerSecond, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 mrad/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilliradiansPerSecond, MilliradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MilliradianPerSecond, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 мрад/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilliradiansPerSecond, MilliradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.MilliradianPerSecond, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 n°/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanodegreesPerSecond, NanodegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.NanodegreePerSecond, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 ndeg/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanodegreesPerSecond, NanodegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.NanodegreePerSecond, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 н°/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanodegreesPerSecond, NanodegreesPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.NanodegreePerSecond, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 nrad/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanoradiansPerSecond, NanoradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.NanoradianPerSecond, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 нрад/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanoradiansPerSecond, NanoradiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.NanoradianPerSecond, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 rad/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.RadiansPerSecond, RadiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.RadianPerSecond, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 рад/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.RadiansPerSecond, RadiansPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.RadianPerSecond, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 rpm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.RevolutionsPerMinute, RevolutionsPerMinuteTolerance); - Assert.Equal(RotationalSpeedUnit.RevolutionPerMinute, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 r/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.RevolutionsPerMinute, RevolutionsPerMinuteTolerance); - Assert.Equal(RotationalSpeedUnit.RevolutionPerMinute, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 об/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.RevolutionsPerMinute, RevolutionsPerMinuteTolerance); - Assert.Equal(RotationalSpeedUnit.RevolutionPerMinute, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 r/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.RevolutionsPerSecond, RevolutionsPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.RevolutionPerSecond, parsed.Unit); - } - - { - Assert.True(RotationalSpeed.TryParse("1 об/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.RevolutionsPerSecond, RevolutionsPerSecondTolerance); - Assert.Equal(RotationalSpeedUnit.RevolutionPerSecond, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(RotationalSpeed.TryParse(quantityString, out RotationalSpeed parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -1066,6 +751,51 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Rotati Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", RotationalSpeedUnit.CentiradianPerSecond, "crad/s")] + [InlineData("en-US", RotationalSpeedUnit.DeciradianPerSecond, "drad/s")] + [InlineData("en-US", RotationalSpeedUnit.DegreePerMinute, "°/min")] + [InlineData("en-US", RotationalSpeedUnit.DegreePerSecond, "°/s")] + [InlineData("en-US", RotationalSpeedUnit.MicrodegreePerSecond, "µ°/s")] + [InlineData("en-US", RotationalSpeedUnit.MicroradianPerSecond, "µrad/s")] + [InlineData("en-US", RotationalSpeedUnit.MillidegreePerSecond, "m°/s")] + [InlineData("en-US", RotationalSpeedUnit.MilliradianPerSecond, "mrad/s")] + [InlineData("en-US", RotationalSpeedUnit.NanodegreePerSecond, "n°/s")] + [InlineData("en-US", RotationalSpeedUnit.NanoradianPerSecond, "nrad/s")] + [InlineData("en-US", RotationalSpeedUnit.RadianPerSecond, "rad/s")] + [InlineData("en-US", RotationalSpeedUnit.RevolutionPerMinute, "rpm")] + [InlineData("en-US", RotationalSpeedUnit.RevolutionPerSecond, "r/s")] + [InlineData("ru-RU", RotationalSpeedUnit.CentiradianPerSecond, "срад/с")] + [InlineData("ru-RU", RotationalSpeedUnit.DeciradianPerSecond, "драд/с")] + [InlineData("ru-RU", RotationalSpeedUnit.DegreePerSecond, "°/с")] + [InlineData("ru-RU", RotationalSpeedUnit.MicrodegreePerSecond, "мк°/с")] + [InlineData("ru-RU", RotationalSpeedUnit.MicroradianPerSecond, "мкрад/с")] + [InlineData("ru-RU", RotationalSpeedUnit.MillidegreePerSecond, "м°/с")] + [InlineData("ru-RU", RotationalSpeedUnit.MilliradianPerSecond, "мрад/с")] + [InlineData("ru-RU", RotationalSpeedUnit.NanodegreePerSecond, "н°/с")] + [InlineData("ru-RU", RotationalSpeedUnit.NanoradianPerSecond, "нрад/с")] + [InlineData("ru-RU", RotationalSpeedUnit.RadianPerSecond, "рад/с")] + [InlineData("ru-RU", RotationalSpeedUnit.RevolutionPerMinute, "об/мин")] + [InlineData("ru-RU", RotationalSpeedUnit.RevolutionPerSecond, "об/с")] + public void GetAbbreviationForCulture(string culture, RotationalSpeedUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = RotationalSpeed.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(RotationalSpeed.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = RotationalSpeed.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(RotationalSpeedUnit unit) @@ -1096,6 +826,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); }); } @@ -1119,44 +850,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] @@ -1202,8 +935,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); @@ -1240,23 +971,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = RotationalSpeed.FromRadiansPerSecond(1); - Assert.True(v.Equals(RotationalSpeed.FromRadiansPerSecond(1), RadiansPerSecondTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(RotationalSpeed.Zero, RadiansPerSecondTolerance, ComparisonType.Relative)); - Assert.True(RotationalSpeed.FromRadiansPerSecond(100).Equals(RotationalSpeed.FromRadiansPerSecond(120), 0.3, ComparisonType.Relative)); - Assert.False(RotationalSpeed.FromRadiansPerSecond(100).Equals(RotationalSpeed.FromRadiansPerSecond(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = RotationalSpeed.FromRadiansPerSecond(1); - Assert.Throws(() => v.Equals(RotationalSpeed.FromRadiansPerSecond(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1271,6 +985,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(radianpersecond.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = RotationalSpeed.FromRadiansPerSecond(1); + var negativeTolerance = RotationalSpeed.FromRadiansPerSecond(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1287,6 +1027,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() { @@ -1369,158 +1121,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(RotationalSpeed))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(RotationalSpeedUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal(RotationalSpeed.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal(RotationalSpeed.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal(new {RotationalSpeed.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 a5f1c4a528..e525624ffd 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessPerLengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessPerLengthTestsBase.g.cs @@ -112,7 +112,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new RotationalStiffnessPerLength(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -125,15 +125,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void RotationalStiffnessPerLength_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + RotationalStiffnessPerLengthUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new RotationalStiffnessPerLength(1, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(RotationalStiffnessPerLength.Zero, quantityInfo.Zero); Assert.Equal("RotationalStiffnessPerLength", quantityInfo.Name); + Assert.Equal(RotationalStiffnessPerLength.Zero, quantityInfo.Zero); + Assert.Equal(RotationalStiffnessPerLength.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(RotationalStiffnessPerLength.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -151,23 +169,23 @@ public void NewtonMeterPerRadianPerMeterToRotationalStiffnessPerLengthUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = RotationalStiffnessPerLength.From(1, RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter); - AssertEx.EqualTolerance(1, quantity00.KilonewtonMetersPerRadianPerMeter, KilonewtonMetersPerRadianPerMeterTolerance); + Assert.Equal(1, quantity00.KilonewtonMetersPerRadianPerMeter); Assert.Equal(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, quantity00.Unit); var quantity01 = RotationalStiffnessPerLength.From(1, RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot); - AssertEx.EqualTolerance(1, quantity01.KilopoundForceFeetPerDegreesPerFeet, KilopoundForceFeetPerDegreesPerFeetTolerance); + Assert.Equal(1, quantity01.KilopoundForceFeetPerDegreesPerFeet); Assert.Equal(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, quantity01.Unit); var quantity02 = RotationalStiffnessPerLength.From(1, RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter); - AssertEx.EqualTolerance(1, quantity02.MeganewtonMetersPerRadianPerMeter, MeganewtonMetersPerRadianPerMeterTolerance); + Assert.Equal(1, quantity02.MeganewtonMetersPerRadianPerMeter); Assert.Equal(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, quantity02.Unit); var quantity03 = RotationalStiffnessPerLength.From(1, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter); - AssertEx.EqualTolerance(1, quantity03.NewtonMetersPerRadianPerMeter, NewtonMetersPerRadianPerMeterTolerance); + Assert.Equal(1, quantity03.NewtonMetersPerRadianPerMeter); Assert.Equal(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, quantity03.Unit); var quantity04 = RotationalStiffnessPerLength.From(1, RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot); - AssertEx.EqualTolerance(1, quantity04.PoundForceFeetPerDegreesPerFeet, PoundForceFeetPerDegreesPerFeetTolerance); + Assert.Equal(1, quantity04.PoundForceFeetPerDegreesPerFeet); Assert.Equal(RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot, quantity04.Unit); } @@ -307,183 +325,48 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 kN·m/rad/m", RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, 4.2)] + [InlineData("en-US", "4.2 kNm/rad/m", RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, 4.2)] + [InlineData("en-US", "4.2 kipf·ft/°/ft", RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, 4.2)] + [InlineData("en-US", "4.2 kip·ft/°/ft", RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, 4.2)] + [InlineData("en-US", "4.2 k·ft/°/ft", RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, 4.2)] + [InlineData("en-US", "4.2 kipf·ft/deg/ft", RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, 4.2)] + [InlineData("en-US", "4.2 kip·ft/deg/ft", RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, 4.2)] + [InlineData("en-US", "4.2 k·ft/deg/ft", RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, 4.2)] + [InlineData("en-US", "4.2 MN·m/rad/m", RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, 4.2)] + [InlineData("en-US", "4.2 MNm/rad/m", RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = RotationalStiffnessPerLength.Parse("1 kN·m/rad/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonMetersPerRadianPerMeter, KilonewtonMetersPerRadianPerMeterTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffnessPerLength.Parse("1 kNm/rad/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonMetersPerRadianPerMeter, KilonewtonMetersPerRadianPerMeterTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffnessPerLength.Parse("1 kipf·ft/°/ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundForceFeetPerDegreesPerFeet, KilopoundForceFeetPerDegreesPerFeetTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffnessPerLength.Parse("1 kip·ft/°/ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundForceFeetPerDegreesPerFeet, KilopoundForceFeetPerDegreesPerFeetTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffnessPerLength.Parse("1 k·ft/°/ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundForceFeetPerDegreesPerFeet, KilopoundForceFeetPerDegreesPerFeetTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffnessPerLength.Parse("1 kipf·ft/deg/ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundForceFeetPerDegreesPerFeet, KilopoundForceFeetPerDegreesPerFeetTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffnessPerLength.Parse("1 kip·ft/deg/ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundForceFeetPerDegreesPerFeet, KilopoundForceFeetPerDegreesPerFeetTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffnessPerLength.Parse("1 k·ft/deg/ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundForceFeetPerDegreesPerFeet, KilopoundForceFeetPerDegreesPerFeetTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffnessPerLength.Parse("1 MN·m/rad/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MeganewtonMetersPerRadianPerMeter, MeganewtonMetersPerRadianPerMeterTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffnessPerLength.Parse("1 MNm/rad/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MeganewtonMetersPerRadianPerMeter, MeganewtonMetersPerRadianPerMeterTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffnessPerLength.Parse("1 N·m/rad/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonMetersPerRadianPerMeter, NewtonMetersPerRadianPerMeterTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffnessPerLength.Parse("1 Nm/rad/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonMetersPerRadianPerMeter, NewtonMetersPerRadianPerMeterTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffnessPerLength.Parse("1 lbf·ft/deg/ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundForceFeetPerDegreesPerFeet, PoundForceFeetPerDegreesPerFeetTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = RotationalStiffnessPerLength.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 kN·m/rad/m", RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, 4.2)] + [InlineData("en-US", "4.2 kNm/rad/m", RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, 4.2)] + [InlineData("en-US", "4.2 kipf·ft/°/ft", RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, 4.2)] + [InlineData("en-US", "4.2 kip·ft/°/ft", RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, 4.2)] + [InlineData("en-US", "4.2 k·ft/°/ft", RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, 4.2)] + [InlineData("en-US", "4.2 kipf·ft/deg/ft", RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, 4.2)] + [InlineData("en-US", "4.2 kip·ft/deg/ft", RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, 4.2)] + [InlineData("en-US", "4.2 k·ft/deg/ft", RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, 4.2)] + [InlineData("en-US", "4.2 MN·m/rad/m", RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, 4.2)] + [InlineData("en-US", "4.2 MNm/rad/m", RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(RotationalStiffnessPerLength.TryParse("1 kN·m/rad/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonMetersPerRadianPerMeter, KilonewtonMetersPerRadianPerMeterTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, parsed.Unit); - } - - { - Assert.True(RotationalStiffnessPerLength.TryParse("1 kNm/rad/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonMetersPerRadianPerMeter, KilonewtonMetersPerRadianPerMeterTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, parsed.Unit); - } - - { - Assert.True(RotationalStiffnessPerLength.TryParse("1 kipf·ft/°/ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundForceFeetPerDegreesPerFeet, KilopoundForceFeetPerDegreesPerFeetTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, parsed.Unit); - } - - { - Assert.True(RotationalStiffnessPerLength.TryParse("1 kip·ft/°/ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundForceFeetPerDegreesPerFeet, KilopoundForceFeetPerDegreesPerFeetTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, parsed.Unit); - } - - { - Assert.True(RotationalStiffnessPerLength.TryParse("1 k·ft/°/ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundForceFeetPerDegreesPerFeet, KilopoundForceFeetPerDegreesPerFeetTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, parsed.Unit); - } - - { - Assert.True(RotationalStiffnessPerLength.TryParse("1 kipf·ft/deg/ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundForceFeetPerDegreesPerFeet, KilopoundForceFeetPerDegreesPerFeetTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, parsed.Unit); - } - - { - Assert.True(RotationalStiffnessPerLength.TryParse("1 kip·ft/deg/ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundForceFeetPerDegreesPerFeet, KilopoundForceFeetPerDegreesPerFeetTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, parsed.Unit); - } - - { - Assert.True(RotationalStiffnessPerLength.TryParse("1 k·ft/deg/ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundForceFeetPerDegreesPerFeet, KilopoundForceFeetPerDegreesPerFeetTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, parsed.Unit); - } - - { - Assert.True(RotationalStiffnessPerLength.TryParse("1 MN·m/rad/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MeganewtonMetersPerRadianPerMeter, MeganewtonMetersPerRadianPerMeterTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, parsed.Unit); - } - - { - Assert.True(RotationalStiffnessPerLength.TryParse("1 MNm/rad/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MeganewtonMetersPerRadianPerMeter, MeganewtonMetersPerRadianPerMeterTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, parsed.Unit); - } - - { - Assert.True(RotationalStiffnessPerLength.TryParse("1 N·m/rad/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonMetersPerRadianPerMeter, NewtonMetersPerRadianPerMeterTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, parsed.Unit); - } - - { - Assert.True(RotationalStiffnessPerLength.TryParse("1 Nm/rad/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonMetersPerRadianPerMeter, NewtonMetersPerRadianPerMeterTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, parsed.Unit); - } - - { - Assert.True(RotationalStiffnessPerLength.TryParse("1 lbf·ft/deg/ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundForceFeetPerDegreesPerFeet, PoundForceFeetPerDegreesPerFeetTolerance); - Assert.Equal(RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(RotationalStiffnessPerLength.TryParse(quantityString, out RotationalStiffnessPerLength parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -656,6 +539,31 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Rotati Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, "kN·m/rad/m")] + [InlineData("en-US", RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, "kipf·ft/°/ft")] + [InlineData("en-US", RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, "MN·m/rad/m")] + [InlineData("en-US", RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, "N·m/rad/m")] + [InlineData("en-US", RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot, "lbf·ft/deg/ft")] + public void GetAbbreviationForCulture(string culture, RotationalStiffnessPerLengthUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = RotationalStiffnessPerLength.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(RotationalStiffnessPerLength.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = RotationalStiffnessPerLength.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(RotationalStiffnessPerLengthUnit unit) @@ -686,6 +594,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); }); } @@ -709,36 +618,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] @@ -784,8 +695,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); @@ -823,34 +732,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1); - Assert.True(v.Equals(RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1), NewtonMetersPerRadianPerMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(RotationalStiffnessPerLength.Zero, NewtonMetersPerRadianPerMeterTolerance, ComparisonType.Relative)); - Assert.True(RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(100).Equals(RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(100).Equals(RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(120), 0.1, ComparisonType.Relative)); + RotationalStiffnessPerLength newtonmeterperradianpermeter = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1); + Assert.False(newtonmeterperradianpermeter.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1); - Assert.Throws(() => v.Equals(RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1), -1, ComparisonType.Relative)); + RotationalStiffnessPerLength newtonmeterperradianpermeter = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1); + Assert.False(newtonmeterperradianpermeter.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - RotationalStiffnessPerLength newtonmeterperradianpermeter = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1); - Assert.False(newtonmeterperradianpermeter.Equals(new object())); + var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(firstValue); + var otherQuantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(secondValue); + RotationalStiffnessPerLength maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - RotationalStiffnessPerLength newtonmeterperradianpermeter = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1); - Assert.False(newtonmeterperradianpermeter.Equals(null)); + var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1); + var negativeTolerance = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -869,6 +787,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() { @@ -935,158 +865,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(RotationalStiffnessPerLength))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(RotationalStiffnessPerLengthUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal(RotationalStiffnessPerLength.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal(RotationalStiffnessPerLength.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal(new {RotationalStiffnessPerLength.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 7f5b9db7b7..d487c8aa79 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessTestsBase.g.cs @@ -224,7 +224,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new RotationalStiffness(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -237,15 +237,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void RotationalStiffness_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + RotationalStiffnessUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new RotationalStiffness(1, RotationalStiffnessUnit.NewtonMeterPerRadian); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(RotationalStiffness.Zero, quantityInfo.Zero); Assert.Equal("RotationalStiffness", quantityInfo.Name); + Assert.Equal(RotationalStiffness.Zero, quantityInfo.Zero); + Assert.Equal(RotationalStiffness.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(RotationalStiffness.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void RotationalStiffnessInfo_CreateWithCustomUnitInfos() + { + RotationalStiffnessUnit[] expectedUnits = [RotationalStiffnessUnit.NewtonMeterPerRadian]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -291,135 +309,135 @@ public void NewtonMeterPerRadianToRotationalStiffnessUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = RotationalStiffness.From(1, RotationalStiffnessUnit.CentinewtonMeterPerDegree); - AssertEx.EqualTolerance(1, quantity00.CentinewtonMetersPerDegree, CentinewtonMetersPerDegreeTolerance); + Assert.Equal(1, quantity00.CentinewtonMetersPerDegree); Assert.Equal(RotationalStiffnessUnit.CentinewtonMeterPerDegree, quantity00.Unit); var quantity01 = RotationalStiffness.From(1, RotationalStiffnessUnit.CentinewtonMillimeterPerDegree); - AssertEx.EqualTolerance(1, quantity01.CentinewtonMillimetersPerDegree, CentinewtonMillimetersPerDegreeTolerance); + Assert.Equal(1, quantity01.CentinewtonMillimetersPerDegree); Assert.Equal(RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, quantity01.Unit); var quantity02 = RotationalStiffness.From(1, RotationalStiffnessUnit.CentinewtonMillimeterPerRadian); - AssertEx.EqualTolerance(1, quantity02.CentinewtonMillimetersPerRadian, CentinewtonMillimetersPerRadianTolerance); + Assert.Equal(1, quantity02.CentinewtonMillimetersPerRadian); Assert.Equal(RotationalStiffnessUnit.CentinewtonMillimeterPerRadian, quantity02.Unit); var quantity03 = RotationalStiffness.From(1, RotationalStiffnessUnit.DecanewtonMeterPerDegree); - AssertEx.EqualTolerance(1, quantity03.DecanewtonMetersPerDegree, DecanewtonMetersPerDegreeTolerance); + Assert.Equal(1, quantity03.DecanewtonMetersPerDegree); Assert.Equal(RotationalStiffnessUnit.DecanewtonMeterPerDegree, quantity03.Unit); var quantity04 = RotationalStiffness.From(1, RotationalStiffnessUnit.DecanewtonMillimeterPerDegree); - AssertEx.EqualTolerance(1, quantity04.DecanewtonMillimetersPerDegree, DecanewtonMillimetersPerDegreeTolerance); + Assert.Equal(1, quantity04.DecanewtonMillimetersPerDegree); Assert.Equal(RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, quantity04.Unit); var quantity05 = RotationalStiffness.From(1, RotationalStiffnessUnit.DecanewtonMillimeterPerRadian); - AssertEx.EqualTolerance(1, quantity05.DecanewtonMillimetersPerRadian, DecanewtonMillimetersPerRadianTolerance); + Assert.Equal(1, quantity05.DecanewtonMillimetersPerRadian); Assert.Equal(RotationalStiffnessUnit.DecanewtonMillimeterPerRadian, quantity05.Unit); var quantity06 = RotationalStiffness.From(1, RotationalStiffnessUnit.DecinewtonMeterPerDegree); - AssertEx.EqualTolerance(1, quantity06.DecinewtonMetersPerDegree, DecinewtonMetersPerDegreeTolerance); + Assert.Equal(1, quantity06.DecinewtonMetersPerDegree); Assert.Equal(RotationalStiffnessUnit.DecinewtonMeterPerDegree, quantity06.Unit); var quantity07 = RotationalStiffness.From(1, RotationalStiffnessUnit.DecinewtonMillimeterPerDegree); - AssertEx.EqualTolerance(1, quantity07.DecinewtonMillimetersPerDegree, DecinewtonMillimetersPerDegreeTolerance); + Assert.Equal(1, quantity07.DecinewtonMillimetersPerDegree); Assert.Equal(RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, quantity07.Unit); var quantity08 = RotationalStiffness.From(1, RotationalStiffnessUnit.DecinewtonMillimeterPerRadian); - AssertEx.EqualTolerance(1, quantity08.DecinewtonMillimetersPerRadian, DecinewtonMillimetersPerRadianTolerance); + Assert.Equal(1, quantity08.DecinewtonMillimetersPerRadian); Assert.Equal(RotationalStiffnessUnit.DecinewtonMillimeterPerRadian, quantity08.Unit); var quantity09 = RotationalStiffness.From(1, RotationalStiffnessUnit.KilonewtonMeterPerDegree); - AssertEx.EqualTolerance(1, quantity09.KilonewtonMetersPerDegree, KilonewtonMetersPerDegreeTolerance); + Assert.Equal(1, quantity09.KilonewtonMetersPerDegree); Assert.Equal(RotationalStiffnessUnit.KilonewtonMeterPerDegree, quantity09.Unit); var quantity10 = RotationalStiffness.From(1, RotationalStiffnessUnit.KilonewtonMeterPerRadian); - AssertEx.EqualTolerance(1, quantity10.KilonewtonMetersPerRadian, KilonewtonMetersPerRadianTolerance); + Assert.Equal(1, quantity10.KilonewtonMetersPerRadian); Assert.Equal(RotationalStiffnessUnit.KilonewtonMeterPerRadian, quantity10.Unit); var quantity11 = RotationalStiffness.From(1, RotationalStiffnessUnit.KilonewtonMillimeterPerDegree); - AssertEx.EqualTolerance(1, quantity11.KilonewtonMillimetersPerDegree, KilonewtonMillimetersPerDegreeTolerance); + Assert.Equal(1, quantity11.KilonewtonMillimetersPerDegree); Assert.Equal(RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, quantity11.Unit); var quantity12 = RotationalStiffness.From(1, RotationalStiffnessUnit.KilonewtonMillimeterPerRadian); - AssertEx.EqualTolerance(1, quantity12.KilonewtonMillimetersPerRadian, KilonewtonMillimetersPerRadianTolerance); + Assert.Equal(1, quantity12.KilonewtonMillimetersPerRadian); Assert.Equal(RotationalStiffnessUnit.KilonewtonMillimeterPerRadian, quantity12.Unit); var quantity13 = RotationalStiffness.From(1, RotationalStiffnessUnit.KilopoundForceFootPerDegrees); - AssertEx.EqualTolerance(1, quantity13.KilopoundForceFeetPerDegrees, KilopoundForceFeetPerDegreesTolerance); + Assert.Equal(1, quantity13.KilopoundForceFeetPerDegrees); Assert.Equal(RotationalStiffnessUnit.KilopoundForceFootPerDegrees, quantity13.Unit); var quantity14 = RotationalStiffness.From(1, RotationalStiffnessUnit.MeganewtonMeterPerDegree); - AssertEx.EqualTolerance(1, quantity14.MeganewtonMetersPerDegree, MeganewtonMetersPerDegreeTolerance); + Assert.Equal(1, quantity14.MeganewtonMetersPerDegree); Assert.Equal(RotationalStiffnessUnit.MeganewtonMeterPerDegree, quantity14.Unit); var quantity15 = RotationalStiffness.From(1, RotationalStiffnessUnit.MeganewtonMeterPerRadian); - AssertEx.EqualTolerance(1, quantity15.MeganewtonMetersPerRadian, MeganewtonMetersPerRadianTolerance); + Assert.Equal(1, quantity15.MeganewtonMetersPerRadian); Assert.Equal(RotationalStiffnessUnit.MeganewtonMeterPerRadian, quantity15.Unit); var quantity16 = RotationalStiffness.From(1, RotationalStiffnessUnit.MeganewtonMillimeterPerDegree); - AssertEx.EqualTolerance(1, quantity16.MeganewtonMillimetersPerDegree, MeganewtonMillimetersPerDegreeTolerance); + Assert.Equal(1, quantity16.MeganewtonMillimetersPerDegree); Assert.Equal(RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, quantity16.Unit); var quantity17 = RotationalStiffness.From(1, RotationalStiffnessUnit.MeganewtonMillimeterPerRadian); - AssertEx.EqualTolerance(1, quantity17.MeganewtonMillimetersPerRadian, MeganewtonMillimetersPerRadianTolerance); + Assert.Equal(1, quantity17.MeganewtonMillimetersPerRadian); Assert.Equal(RotationalStiffnessUnit.MeganewtonMillimeterPerRadian, quantity17.Unit); var quantity18 = RotationalStiffness.From(1, RotationalStiffnessUnit.MicronewtonMeterPerDegree); - AssertEx.EqualTolerance(1, quantity18.MicronewtonMetersPerDegree, MicronewtonMetersPerDegreeTolerance); + Assert.Equal(1, quantity18.MicronewtonMetersPerDegree); Assert.Equal(RotationalStiffnessUnit.MicronewtonMeterPerDegree, quantity18.Unit); var quantity19 = RotationalStiffness.From(1, RotationalStiffnessUnit.MicronewtonMillimeterPerDegree); - AssertEx.EqualTolerance(1, quantity19.MicronewtonMillimetersPerDegree, MicronewtonMillimetersPerDegreeTolerance); + Assert.Equal(1, quantity19.MicronewtonMillimetersPerDegree); Assert.Equal(RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, quantity19.Unit); var quantity20 = RotationalStiffness.From(1, RotationalStiffnessUnit.MicronewtonMillimeterPerRadian); - AssertEx.EqualTolerance(1, quantity20.MicronewtonMillimetersPerRadian, MicronewtonMillimetersPerRadianTolerance); + Assert.Equal(1, quantity20.MicronewtonMillimetersPerRadian); Assert.Equal(RotationalStiffnessUnit.MicronewtonMillimeterPerRadian, quantity20.Unit); var quantity21 = RotationalStiffness.From(1, RotationalStiffnessUnit.MillinewtonMeterPerDegree); - AssertEx.EqualTolerance(1, quantity21.MillinewtonMetersPerDegree, MillinewtonMetersPerDegreeTolerance); + Assert.Equal(1, quantity21.MillinewtonMetersPerDegree); Assert.Equal(RotationalStiffnessUnit.MillinewtonMeterPerDegree, quantity21.Unit); var quantity22 = RotationalStiffness.From(1, RotationalStiffnessUnit.MillinewtonMillimeterPerDegree); - AssertEx.EqualTolerance(1, quantity22.MillinewtonMillimetersPerDegree, MillinewtonMillimetersPerDegreeTolerance); + Assert.Equal(1, quantity22.MillinewtonMillimetersPerDegree); Assert.Equal(RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, quantity22.Unit); var quantity23 = RotationalStiffness.From(1, RotationalStiffnessUnit.MillinewtonMillimeterPerRadian); - AssertEx.EqualTolerance(1, quantity23.MillinewtonMillimetersPerRadian, MillinewtonMillimetersPerRadianTolerance); + Assert.Equal(1, quantity23.MillinewtonMillimetersPerRadian); Assert.Equal(RotationalStiffnessUnit.MillinewtonMillimeterPerRadian, quantity23.Unit); var quantity24 = RotationalStiffness.From(1, RotationalStiffnessUnit.NanonewtonMeterPerDegree); - AssertEx.EqualTolerance(1, quantity24.NanonewtonMetersPerDegree, NanonewtonMetersPerDegreeTolerance); + Assert.Equal(1, quantity24.NanonewtonMetersPerDegree); Assert.Equal(RotationalStiffnessUnit.NanonewtonMeterPerDegree, quantity24.Unit); var quantity25 = RotationalStiffness.From(1, RotationalStiffnessUnit.NanonewtonMillimeterPerDegree); - AssertEx.EqualTolerance(1, quantity25.NanonewtonMillimetersPerDegree, NanonewtonMillimetersPerDegreeTolerance); + Assert.Equal(1, quantity25.NanonewtonMillimetersPerDegree); Assert.Equal(RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, quantity25.Unit); var quantity26 = RotationalStiffness.From(1, RotationalStiffnessUnit.NanonewtonMillimeterPerRadian); - AssertEx.EqualTolerance(1, quantity26.NanonewtonMillimetersPerRadian, NanonewtonMillimetersPerRadianTolerance); + Assert.Equal(1, quantity26.NanonewtonMillimetersPerRadian); Assert.Equal(RotationalStiffnessUnit.NanonewtonMillimeterPerRadian, quantity26.Unit); var quantity27 = RotationalStiffness.From(1, RotationalStiffnessUnit.NewtonMeterPerDegree); - AssertEx.EqualTolerance(1, quantity27.NewtonMetersPerDegree, NewtonMetersPerDegreeTolerance); + Assert.Equal(1, quantity27.NewtonMetersPerDegree); Assert.Equal(RotationalStiffnessUnit.NewtonMeterPerDegree, quantity27.Unit); var quantity28 = RotationalStiffness.From(1, RotationalStiffnessUnit.NewtonMeterPerRadian); - AssertEx.EqualTolerance(1, quantity28.NewtonMetersPerRadian, NewtonMetersPerRadianTolerance); + Assert.Equal(1, quantity28.NewtonMetersPerRadian); Assert.Equal(RotationalStiffnessUnit.NewtonMeterPerRadian, quantity28.Unit); var quantity29 = RotationalStiffness.From(1, RotationalStiffnessUnit.NewtonMillimeterPerDegree); - AssertEx.EqualTolerance(1, quantity29.NewtonMillimetersPerDegree, NewtonMillimetersPerDegreeTolerance); + Assert.Equal(1, quantity29.NewtonMillimetersPerDegree); Assert.Equal(RotationalStiffnessUnit.NewtonMillimeterPerDegree, quantity29.Unit); var quantity30 = RotationalStiffness.From(1, RotationalStiffnessUnit.NewtonMillimeterPerRadian); - AssertEx.EqualTolerance(1, quantity30.NewtonMillimetersPerRadian, NewtonMillimetersPerRadianTolerance); + Assert.Equal(1, quantity30.NewtonMillimetersPerRadian); Assert.Equal(RotationalStiffnessUnit.NewtonMillimeterPerRadian, quantity30.Unit); var quantity31 = RotationalStiffness.From(1, RotationalStiffnessUnit.PoundForceFeetPerRadian); - AssertEx.EqualTolerance(1, quantity31.PoundForceFeetPerRadian, PoundForceFeetPerRadianTolerance); + Assert.Equal(1, quantity31.PoundForceFeetPerRadian); Assert.Equal(RotationalStiffnessUnit.PoundForceFeetPerRadian, quantity31.Unit); var quantity32 = RotationalStiffness.From(1, RotationalStiffnessUnit.PoundForceFootPerDegrees); - AssertEx.EqualTolerance(1, quantity32.PoundForceFeetPerDegrees, PoundForceFeetPerDegreesTolerance); + Assert.Equal(1, quantity32.PoundForceFeetPerDegrees); Assert.Equal(RotationalStiffnessUnit.PoundForceFootPerDegrees, quantity32.Unit); } @@ -488,1345 +506,329 @@ public virtual void BaseUnit_HasSIBase() Assert.True(baseUnitInfo.BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } - [Fact] - public virtual void As_UnitSystem_SI_ReturnsQuantityInSIUnits() - { - var quantity = new RotationalStiffness(value: 1, unit: RotationalStiffness.BaseUnit); - var expectedValue = quantity.As(RotationalStiffness.Info.GetDefaultUnit(UnitSystem.SI)); - - var convertedValue = quantity.As(UnitSystem.SI); - - Assert.Equal(expectedValue, convertedValue); - } - - [Fact] - public void As_UnitSystem_ThrowsArgumentNullExceptionIfNull() - { - var quantity = new RotationalStiffness(value: 1, unit: RotationalStiffness.BaseUnit); - UnitSystem nullUnitSystem = null!; - Assert.Throws(() => quantity.As(nullUnitSystem)); - } - - [Fact] - public void As_UnitSystem_ThrowsArgumentExceptionIfNotSupported() - { - var quantity = new RotationalStiffness(value: 1, unit: RotationalStiffness.BaseUnit); - var unsupportedUnitSystem = new UnitSystem(UnsupportedBaseUnits); - Assert.Throws(() => quantity.As(unsupportedUnitSystem)); - } - - [Fact] - public virtual void ToUnit_UnitSystem_SI_ReturnsQuantityInSIUnits() - { - var quantity = new RotationalStiffness(value: 1, unit: RotationalStiffness.BaseUnit); - var expectedUnit = RotationalStiffness.Info.GetDefaultUnit(UnitSystem.SI); - var expectedValue = quantity.As(expectedUnit); - - Assert.Multiple(() => - { - RotationalStiffness quantityToConvert = quantity; - - RotationalStiffness convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); - - Assert.Equal(expectedUnit, convertedQuantity.Unit); - Assert.Equal(expectedValue, convertedQuantity.Value); - }, () => - { - IQuantity quantityToConvert = quantity; - - IQuantity convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); - - Assert.Equal(expectedUnit, convertedQuantity.Unit); - Assert.Equal(expectedValue, convertedQuantity.Value); - }, () => - { - IQuantity quantityToConvert = quantity; - - IQuantity convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); - - Assert.Equal(expectedUnit, convertedQuantity.Unit); - Assert.Equal(expectedValue, convertedQuantity.Value); - }); - } - - [Fact] - public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() - { - UnitSystem nullUnitSystem = null!; - Assert.Multiple(() => - { - var quantity = new RotationalStiffness(value: 1, unit: RotationalStiffness.BaseUnit); - Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); - }, () => - { - IQuantity quantity = new RotationalStiffness(value: 1, unit: RotationalStiffness.BaseUnit); - Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); - }, () => - { - IQuantity quantity = new RotationalStiffness(value: 1, unit: RotationalStiffness.BaseUnit); - Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); - }); - } - - [Fact] - public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() - { - var unsupportedUnitSystem = new UnitSystem(UnsupportedBaseUnits); - Assert.Multiple(() => - { - var quantity = new RotationalStiffness(value: 1, unit: RotationalStiffness.BaseUnit); - Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); - }, () => - { - IQuantity quantity = new RotationalStiffness(value: 1, unit: RotationalStiffness.BaseUnit); - Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); - }, () => - { - IQuantity quantity = new RotationalStiffness(value: 1, unit: RotationalStiffness.BaseUnit); - Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); - }); - } - - [Fact] - public void Parse() - { - try - { - var parsed = RotationalStiffness.Parse("1 cN·m/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentinewtonMetersPerDegree, CentinewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.CentinewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 cNm/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentinewtonMetersPerDegree, CentinewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.CentinewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 cN·m/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentinewtonMetersPerDegree, CentinewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.CentinewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 cNm/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentinewtonMetersPerDegree, CentinewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.CentinewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 cN·mm/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentinewtonMillimetersPerDegree, CentinewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 cNmm/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentinewtonMillimetersPerDegree, CentinewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 cN·mm/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentinewtonMillimetersPerDegree, CentinewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 cNmm/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentinewtonMillimetersPerDegree, CentinewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 cN·mm/rad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentinewtonMillimetersPerRadian, CentinewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.CentinewtonMillimeterPerRadian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 cNmm/rad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentinewtonMillimetersPerRadian, CentinewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.CentinewtonMillimeterPerRadian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 daN·m/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecanewtonMetersPerDegree, DecanewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecanewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 daNm/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecanewtonMetersPerDegree, DecanewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecanewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 daN·m/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecanewtonMetersPerDegree, DecanewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecanewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 daNm/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecanewtonMetersPerDegree, DecanewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecanewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 daN·mm/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecanewtonMillimetersPerDegree, DecanewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 daNmm/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecanewtonMillimetersPerDegree, DecanewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 daN·mm/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecanewtonMillimetersPerDegree, DecanewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 daNmm/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecanewtonMillimetersPerDegree, DecanewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 daN·mm/rad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecanewtonMillimetersPerRadian, DecanewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.DecanewtonMillimeterPerRadian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 daNmm/rad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecanewtonMillimetersPerRadian, DecanewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.DecanewtonMillimeterPerRadian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 dN·m/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecinewtonMetersPerDegree, DecinewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecinewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 dNm/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecinewtonMetersPerDegree, DecinewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecinewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 dN·m/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecinewtonMetersPerDegree, DecinewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecinewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 dNm/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecinewtonMetersPerDegree, DecinewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecinewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 dN·mm/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecinewtonMillimetersPerDegree, DecinewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 dNmm/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecinewtonMillimetersPerDegree, DecinewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 dN·mm/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecinewtonMillimetersPerDegree, DecinewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 dNmm/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecinewtonMillimetersPerDegree, DecinewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 dN·mm/rad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecinewtonMillimetersPerRadian, DecinewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.DecinewtonMillimeterPerRadian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 dNmm/rad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecinewtonMillimetersPerRadian, DecinewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.DecinewtonMillimeterPerRadian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 kN·m/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonMetersPerDegree, KilonewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 kNm/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonMetersPerDegree, KilonewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 kN·m/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonMetersPerDegree, KilonewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 kNm/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonMetersPerDegree, KilonewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 kN·m/rad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonMetersPerRadian, KilonewtonMetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMeterPerRadian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 kNm/rad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonMetersPerRadian, KilonewtonMetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMeterPerRadian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 kN·mm/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonMillimetersPerDegree, KilonewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 kNmm/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonMillimetersPerDegree, KilonewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 kN·mm/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonMillimetersPerDegree, KilonewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 kNmm/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonMillimetersPerDegree, KilonewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 kN·mm/rad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonMillimetersPerRadian, KilonewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMillimeterPerRadian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 kNmm/rad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonMillimetersPerRadian, KilonewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMillimeterPerRadian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 kipf·ft/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundForceFeetPerDegrees, KilopoundForceFeetPerDegreesTolerance); - Assert.Equal(RotationalStiffnessUnit.KilopoundForceFootPerDegrees, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 kip·ft/°g", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundForceFeetPerDegrees, KilopoundForceFeetPerDegreesTolerance); - Assert.Equal(RotationalStiffnessUnit.KilopoundForceFootPerDegrees, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 k·ft/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundForceFeetPerDegrees, KilopoundForceFeetPerDegreesTolerance); - Assert.Equal(RotationalStiffnessUnit.KilopoundForceFootPerDegrees, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 kipf·ft/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundForceFeetPerDegrees, KilopoundForceFeetPerDegreesTolerance); - Assert.Equal(RotationalStiffnessUnit.KilopoundForceFootPerDegrees, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 kip·ft/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundForceFeetPerDegrees, KilopoundForceFeetPerDegreesTolerance); - Assert.Equal(RotationalStiffnessUnit.KilopoundForceFootPerDegrees, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 k·ft/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundForceFeetPerDegrees, KilopoundForceFeetPerDegreesTolerance); - Assert.Equal(RotationalStiffnessUnit.KilopoundForceFootPerDegrees, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 MN·m/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MeganewtonMetersPerDegree, MeganewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MeganewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 MNm/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MeganewtonMetersPerDegree, MeganewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MeganewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 MN·m/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MeganewtonMetersPerDegree, MeganewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MeganewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 MNm/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MeganewtonMetersPerDegree, MeganewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MeganewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 MN·m/rad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MeganewtonMetersPerRadian, MeganewtonMetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.MeganewtonMeterPerRadian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 MNm/rad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MeganewtonMetersPerRadian, MeganewtonMetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.MeganewtonMeterPerRadian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 MN·mm/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MeganewtonMillimetersPerDegree, MeganewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 MNmm/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MeganewtonMillimetersPerDegree, MeganewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 MN·mm/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MeganewtonMillimetersPerDegree, MeganewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 MNmm/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MeganewtonMillimetersPerDegree, MeganewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 MN·mm/rad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MeganewtonMillimetersPerRadian, MeganewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.MeganewtonMillimeterPerRadian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 MNmm/rad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MeganewtonMillimetersPerRadian, MeganewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.MeganewtonMillimeterPerRadian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 µN·m/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicronewtonMetersPerDegree, MicronewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MicronewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 µNm/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicronewtonMetersPerDegree, MicronewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MicronewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 µN·m/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicronewtonMetersPerDegree, MicronewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MicronewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 µNm/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicronewtonMetersPerDegree, MicronewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MicronewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 µN·mm/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicronewtonMillimetersPerDegree, MicronewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 µNmm/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicronewtonMillimetersPerDegree, MicronewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 µN·mm/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicronewtonMillimetersPerDegree, MicronewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 µNmm/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicronewtonMillimetersPerDegree, MicronewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 µN·mm/rad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicronewtonMillimetersPerRadian, MicronewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.MicronewtonMillimeterPerRadian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 µNmm/rad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicronewtonMillimetersPerRadian, MicronewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.MicronewtonMillimeterPerRadian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 mN·m/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillinewtonMetersPerDegree, MillinewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MillinewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 mNm/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillinewtonMetersPerDegree, MillinewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MillinewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 mN·m/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillinewtonMetersPerDegree, MillinewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MillinewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 mNm/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillinewtonMetersPerDegree, MillinewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MillinewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 mN·mm/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillinewtonMillimetersPerDegree, MillinewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 mNmm/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillinewtonMillimetersPerDegree, MillinewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 mN·mm/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillinewtonMillimetersPerDegree, MillinewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 mNmm/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillinewtonMillimetersPerDegree, MillinewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 mN·mm/rad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillinewtonMillimetersPerRadian, MillinewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.MillinewtonMillimeterPerRadian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 mNmm/rad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillinewtonMillimetersPerRadian, MillinewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.MillinewtonMillimeterPerRadian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 nN·m/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanonewtonMetersPerDegree, NanonewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NanonewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 nNm/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanonewtonMetersPerDegree, NanonewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NanonewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 nN·m/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanonewtonMetersPerDegree, NanonewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NanonewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 nNm/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanonewtonMetersPerDegree, NanonewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NanonewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 nN·mm/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanonewtonMillimetersPerDegree, NanonewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 nNmm/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanonewtonMillimetersPerDegree, NanonewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 nN·mm/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanonewtonMillimetersPerDegree, NanonewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 nNmm/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanonewtonMillimetersPerDegree, NanonewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 nN·mm/rad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanonewtonMillimetersPerRadian, NanonewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.NanonewtonMillimeterPerRadian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 nNmm/rad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanonewtonMillimetersPerRadian, NanonewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.NanonewtonMillimeterPerRadian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 N·m/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonMetersPerDegree, NewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 Nm/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonMetersPerDegree, NewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 N·m/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonMetersPerDegree, NewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 Nm/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonMetersPerDegree, NewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 N·m/rad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonMetersPerRadian, NewtonMetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMeterPerRadian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 Nm/rad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonMetersPerRadian, NewtonMetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMeterPerRadian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 N·mm/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonMillimetersPerDegree, NewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 Nmm/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonMillimetersPerDegree, NewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 N·mm/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonMillimetersPerDegree, NewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 Nmm/°", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonMillimetersPerDegree, NewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMillimeterPerDegree, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 N·mm/rad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonMillimetersPerRadian, NewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMillimeterPerRadian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 Nmm/rad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonMillimetersPerRadian, NewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMillimeterPerRadian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 lbf·ft/rad", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundForceFeetPerRadian, PoundForceFeetPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.PoundForceFeetPerRadian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = RotationalStiffness.Parse("1 lbf·ft/deg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundForceFeetPerDegrees, PoundForceFeetPerDegreesTolerance); - Assert.Equal(RotationalStiffnessUnit.PoundForceFootPerDegrees, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - } - - [Fact] - public void TryParse() - { - { - Assert.True(RotationalStiffness.TryParse("1 cN·m/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentinewtonMetersPerDegree, CentinewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.CentinewtonMeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 cNm/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentinewtonMetersPerDegree, CentinewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.CentinewtonMeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 cN·m/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentinewtonMetersPerDegree, CentinewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.CentinewtonMeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 cNm/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentinewtonMetersPerDegree, CentinewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.CentinewtonMeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 cN·mm/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentinewtonMillimetersPerDegree, CentinewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 cNmm/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentinewtonMillimetersPerDegree, CentinewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 cN·mm/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentinewtonMillimetersPerDegree, CentinewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 cNmm/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentinewtonMillimetersPerDegree, CentinewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 cN·mm/rad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentinewtonMillimetersPerRadian, CentinewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.CentinewtonMillimeterPerRadian, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 cNmm/rad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentinewtonMillimetersPerRadian, CentinewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.CentinewtonMillimeterPerRadian, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 daN·m/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecanewtonMetersPerDegree, DecanewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecanewtonMeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 daNm/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecanewtonMetersPerDegree, DecanewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecanewtonMeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 daN·m/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecanewtonMetersPerDegree, DecanewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecanewtonMeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 daNm/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecanewtonMetersPerDegree, DecanewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecanewtonMeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 daN·mm/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecanewtonMillimetersPerDegree, DecanewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 daNmm/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecanewtonMillimetersPerDegree, DecanewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 daN·mm/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecanewtonMillimetersPerDegree, DecanewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 daNmm/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecanewtonMillimetersPerDegree, DecanewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 daN·mm/rad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecanewtonMillimetersPerRadian, DecanewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.DecanewtonMillimeterPerRadian, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 daNmm/rad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecanewtonMillimetersPerRadian, DecanewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.DecanewtonMillimeterPerRadian, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 dN·m/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecinewtonMetersPerDegree, DecinewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecinewtonMeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 dNm/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecinewtonMetersPerDegree, DecinewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecinewtonMeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 dN·m/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecinewtonMetersPerDegree, DecinewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecinewtonMeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 dNm/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecinewtonMetersPerDegree, DecinewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecinewtonMeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 dN·mm/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecinewtonMillimetersPerDegree, DecinewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 dNmm/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecinewtonMillimetersPerDegree, DecinewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 dN·mm/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecinewtonMillimetersPerDegree, DecinewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 dNmm/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecinewtonMillimetersPerDegree, DecinewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 dN·mm/rad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecinewtonMillimetersPerRadian, DecinewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.DecinewtonMillimeterPerRadian, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 dNmm/rad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecinewtonMillimetersPerRadian, DecinewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.DecinewtonMillimeterPerRadian, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 kN·m/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonMetersPerDegree, KilonewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 kNm/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonMetersPerDegree, KilonewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 kN·m/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonMetersPerDegree, KilonewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 kNm/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonMetersPerDegree, KilonewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 kN·m/rad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonMetersPerRadian, KilonewtonMetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMeterPerRadian, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 kNm/rad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonMetersPerRadian, KilonewtonMetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMeterPerRadian, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 kN·mm/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonMillimetersPerDegree, KilonewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 kNmm/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonMillimetersPerDegree, KilonewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 kN·mm/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonMillimetersPerDegree, KilonewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 kNmm/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonMillimetersPerDegree, KilonewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 kN·mm/rad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonMillimetersPerRadian, KilonewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMillimeterPerRadian, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 kNmm/rad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonMillimetersPerRadian, KilonewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.KilonewtonMillimeterPerRadian, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 kipf·ft/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundForceFeetPerDegrees, KilopoundForceFeetPerDegreesTolerance); - Assert.Equal(RotationalStiffnessUnit.KilopoundForceFootPerDegrees, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 kip·ft/°g", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundForceFeetPerDegrees, KilopoundForceFeetPerDegreesTolerance); - Assert.Equal(RotationalStiffnessUnit.KilopoundForceFootPerDegrees, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 k·ft/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundForceFeetPerDegrees, KilopoundForceFeetPerDegreesTolerance); - Assert.Equal(RotationalStiffnessUnit.KilopoundForceFootPerDegrees, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 kipf·ft/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundForceFeetPerDegrees, KilopoundForceFeetPerDegreesTolerance); - Assert.Equal(RotationalStiffnessUnit.KilopoundForceFootPerDegrees, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 kip·ft/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundForceFeetPerDegrees, KilopoundForceFeetPerDegreesTolerance); - Assert.Equal(RotationalStiffnessUnit.KilopoundForceFootPerDegrees, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 k·ft/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundForceFeetPerDegrees, KilopoundForceFeetPerDegreesTolerance); - Assert.Equal(RotationalStiffnessUnit.KilopoundForceFootPerDegrees, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 MN·m/rad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MeganewtonMetersPerRadian, MeganewtonMetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.MeganewtonMeterPerRadian, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 MNm/rad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MeganewtonMetersPerRadian, MeganewtonMetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.MeganewtonMeterPerRadian, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 µN·m/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicronewtonMetersPerDegree, MicronewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MicronewtonMeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 µNm/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicronewtonMetersPerDegree, MicronewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MicronewtonMeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 µN·m/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicronewtonMetersPerDegree, MicronewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MicronewtonMeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 µNm/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicronewtonMetersPerDegree, MicronewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MicronewtonMeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 µN·mm/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicronewtonMillimetersPerDegree, MicronewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 µNmm/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicronewtonMillimetersPerDegree, MicronewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 µN·mm/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicronewtonMillimetersPerDegree, MicronewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 µNmm/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicronewtonMillimetersPerDegree, MicronewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 µN·mm/rad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicronewtonMillimetersPerRadian, MicronewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.MicronewtonMillimeterPerRadian, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 µNmm/rad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicronewtonMillimetersPerRadian, MicronewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.MicronewtonMillimeterPerRadian, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 nN·m/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanonewtonMetersPerDegree, NanonewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NanonewtonMeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 nNm/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanonewtonMetersPerDegree, NanonewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NanonewtonMeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 nN·m/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanonewtonMetersPerDegree, NanonewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NanonewtonMeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 nNm/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanonewtonMetersPerDegree, NanonewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NanonewtonMeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 nN·mm/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanonewtonMillimetersPerDegree, NanonewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, parsed.Unit); - } - - { - Assert.True(RotationalStiffness.TryParse("1 nNmm/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanonewtonMillimetersPerDegree, NanonewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, parsed.Unit); - } + [Fact] + public virtual void As_UnitSystem_SI_ReturnsQuantityInSIUnits() + { + var quantity = new RotationalStiffness(value: 1, unit: RotationalStiffness.BaseUnit); + var expectedValue = quantity.As(RotationalStiffness.Info.GetDefaultUnit(UnitSystem.SI)); - { - Assert.True(RotationalStiffness.TryParse("1 nN·mm/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanonewtonMillimetersPerDegree, NanonewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, parsed.Unit); - } + var convertedValue = quantity.As(UnitSystem.SI); - { - Assert.True(RotationalStiffness.TryParse("1 nNmm/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanonewtonMillimetersPerDegree, NanonewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, parsed.Unit); - } + Assert.Equal(expectedValue, convertedValue); + } - { - Assert.True(RotationalStiffness.TryParse("1 nN·mm/rad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanonewtonMillimetersPerRadian, NanonewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.NanonewtonMillimeterPerRadian, parsed.Unit); - } + [Fact] + public void As_UnitSystem_ThrowsArgumentNullExceptionIfNull() + { + var quantity = new RotationalStiffness(value: 1, unit: RotationalStiffness.BaseUnit); + UnitSystem nullUnitSystem = null!; + Assert.Throws(() => quantity.As(nullUnitSystem)); + } - { - Assert.True(RotationalStiffness.TryParse("1 nNmm/rad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanonewtonMillimetersPerRadian, NanonewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.NanonewtonMillimeterPerRadian, parsed.Unit); - } + [Fact] + public void As_UnitSystem_ThrowsArgumentExceptionIfNotSupported() + { + var quantity = new RotationalStiffness(value: 1, unit: RotationalStiffness.BaseUnit); + var unsupportedUnitSystem = new UnitSystem(UnsupportedBaseUnits); + Assert.Throws(() => quantity.As(unsupportedUnitSystem)); + } - { - Assert.True(RotationalStiffness.TryParse("1 N·m/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonMetersPerDegree, NewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMeterPerDegree, parsed.Unit); - } + [Fact] + public virtual void ToUnit_UnitSystem_SI_ReturnsQuantityInSIUnits() + { + var quantity = new RotationalStiffness(value: 1, unit: RotationalStiffness.BaseUnit); + var expectedUnit = RotationalStiffness.Info.GetDefaultUnit(UnitSystem.SI); + var expectedValue = quantity.As(expectedUnit); + Assert.Multiple(() => { - Assert.True(RotationalStiffness.TryParse("1 Nm/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonMetersPerDegree, NewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMeterPerDegree, parsed.Unit); - } + RotationalStiffness quantityToConvert = quantity; - { - Assert.True(RotationalStiffness.TryParse("1 N·m/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonMetersPerDegree, NewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMeterPerDegree, parsed.Unit); - } + RotationalStiffness convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); + Assert.Equal(expectedUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }, () => { - Assert.True(RotationalStiffness.TryParse("1 Nm/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonMetersPerDegree, NewtonMetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMeterPerDegree, parsed.Unit); - } + IQuantity quantityToConvert = quantity; - { - Assert.True(RotationalStiffness.TryParse("1 N·m/rad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonMetersPerRadian, NewtonMetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMeterPerRadian, parsed.Unit); - } + IQuantity convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); + Assert.Equal(expectedUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }, () => { - Assert.True(RotationalStiffness.TryParse("1 Nm/rad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonMetersPerRadian, NewtonMetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMeterPerRadian, parsed.Unit); - } + IQuantity quantityToConvert = quantity; - { - Assert.True(RotationalStiffness.TryParse("1 N·mm/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonMillimetersPerDegree, NewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMillimeterPerDegree, parsed.Unit); - } + IQuantity convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); - { - Assert.True(RotationalStiffness.TryParse("1 Nmm/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonMillimetersPerDegree, NewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMillimeterPerDegree, parsed.Unit); - } + Assert.Equal(expectedUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }); + } + [Fact] + public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() + { + UnitSystem nullUnitSystem = null!; + Assert.Multiple(() => { - Assert.True(RotationalStiffness.TryParse("1 N·mm/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonMillimetersPerDegree, NewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMillimeterPerDegree, parsed.Unit); - } - + var quantity = new RotationalStiffness(value: 1, unit: RotationalStiffness.BaseUnit); + Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); + }, () => { - Assert.True(RotationalStiffness.TryParse("1 Nmm/°", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonMillimetersPerDegree, NewtonMillimetersPerDegreeTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMillimeterPerDegree, parsed.Unit); - } - + IQuantity quantity = new RotationalStiffness(value: 1, unit: RotationalStiffness.BaseUnit); + Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); + }, () => { - Assert.True(RotationalStiffness.TryParse("1 N·mm/rad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonMillimetersPerRadian, NewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMillimeterPerRadian, parsed.Unit); - } + IQuantity quantity = new RotationalStiffness(value: 1, unit: RotationalStiffness.BaseUnit); + Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); + }); + } + [Fact] + public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() + { + var unsupportedUnitSystem = new UnitSystem(UnsupportedBaseUnits); + Assert.Multiple(() => { - Assert.True(RotationalStiffness.TryParse("1 Nmm/rad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonMillimetersPerRadian, NewtonMillimetersPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.NewtonMillimeterPerRadian, parsed.Unit); - } - + var quantity = new RotationalStiffness(value: 1, unit: RotationalStiffness.BaseUnit); + Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); + }, () => { - Assert.True(RotationalStiffness.TryParse("1 lbf·ft/rad", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundForceFeetPerRadian, PoundForceFeetPerRadianTolerance); - Assert.Equal(RotationalStiffnessUnit.PoundForceFeetPerRadian, parsed.Unit); - } - + IQuantity quantity = new RotationalStiffness(value: 1, unit: RotationalStiffness.BaseUnit); + Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); + }, () => { - Assert.True(RotationalStiffness.TryParse("1 lbf·ft/deg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundForceFeetPerDegrees, PoundForceFeetPerDegreesTolerance); - Assert.Equal(RotationalStiffnessUnit.PoundForceFootPerDegrees, parsed.Unit); - } + IQuantity quantity = new RotationalStiffness(value: 1, unit: RotationalStiffness.BaseUnit); + Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); + }); + } + + [Theory] + [InlineData("en-US", "4.2 cN·m/deg", RotationalStiffnessUnit.CentinewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 cNm/deg", RotationalStiffnessUnit.CentinewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 cN·m/°", RotationalStiffnessUnit.CentinewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 cNm/°", RotationalStiffnessUnit.CentinewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 cN·mm/deg", RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 cNmm/deg", RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 cN·mm/°", RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 cNmm/°", RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 cN·mm/rad", RotationalStiffnessUnit.CentinewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 cNmm/rad", RotationalStiffnessUnit.CentinewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 daN·m/deg", RotationalStiffnessUnit.DecanewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 daNm/deg", RotationalStiffnessUnit.DecanewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 daN·m/°", RotationalStiffnessUnit.DecanewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 daNm/°", RotationalStiffnessUnit.DecanewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 daN·mm/deg", RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 daNmm/deg", RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 daN·mm/°", RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 daNmm/°", RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 daN·mm/rad", RotationalStiffnessUnit.DecanewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 daNmm/rad", RotationalStiffnessUnit.DecanewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 dN·m/deg", RotationalStiffnessUnit.DecinewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 dNm/deg", RotationalStiffnessUnit.DecinewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 dN·m/°", RotationalStiffnessUnit.DecinewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 dNm/°", RotationalStiffnessUnit.DecinewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 dN·mm/deg", RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 dNmm/deg", RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 dN·mm/°", RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 dNmm/°", RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 dN·mm/rad", RotationalStiffnessUnit.DecinewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 dNmm/rad", RotationalStiffnessUnit.DecinewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 kN·m/deg", RotationalStiffnessUnit.KilonewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 kNm/deg", RotationalStiffnessUnit.KilonewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 kN·m/°", RotationalStiffnessUnit.KilonewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 kNm/°", RotationalStiffnessUnit.KilonewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 kN·m/rad", RotationalStiffnessUnit.KilonewtonMeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 kNm/rad", RotationalStiffnessUnit.KilonewtonMeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 kN·mm/deg", RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 kNmm/deg", RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 kN·mm/°", RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 kNmm/°", RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 kN·mm/rad", RotationalStiffnessUnit.KilonewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 kNmm/rad", RotationalStiffnessUnit.KilonewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 kipf·ft/°", RotationalStiffnessUnit.KilopoundForceFootPerDegrees, 4.2)] + [InlineData("en-US", "4.2 kip·ft/°g", RotationalStiffnessUnit.KilopoundForceFootPerDegrees, 4.2)] + [InlineData("en-US", "4.2 k·ft/°", RotationalStiffnessUnit.KilopoundForceFootPerDegrees, 4.2)] + [InlineData("en-US", "4.2 kipf·ft/deg", RotationalStiffnessUnit.KilopoundForceFootPerDegrees, 4.2)] + [InlineData("en-US", "4.2 kip·ft/deg", RotationalStiffnessUnit.KilopoundForceFootPerDegrees, 4.2)] + [InlineData("en-US", "4.2 k·ft/deg", RotationalStiffnessUnit.KilopoundForceFootPerDegrees, 4.2)] + [InlineData("en-US", "4.2 MN·m/deg", RotationalStiffnessUnit.MeganewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 MNm/deg", RotationalStiffnessUnit.MeganewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 MN·m/°", RotationalStiffnessUnit.MeganewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 MNm/°", RotationalStiffnessUnit.MeganewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 MN·m/rad", RotationalStiffnessUnit.MeganewtonMeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 MNm/rad", RotationalStiffnessUnit.MeganewtonMeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 MN·mm/deg", RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 MNmm/deg", RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 MN·mm/°", RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 MNmm/°", RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 MN·mm/rad", RotationalStiffnessUnit.MeganewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 MNmm/rad", RotationalStiffnessUnit.MeganewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 µN·m/deg", RotationalStiffnessUnit.MicronewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 µNm/deg", RotationalStiffnessUnit.MicronewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 µN·m/°", RotationalStiffnessUnit.MicronewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 µNm/°", RotationalStiffnessUnit.MicronewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 µN·mm/deg", RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 µNmm/deg", RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 µN·mm/°", RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 µNmm/°", RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 µN·mm/rad", RotationalStiffnessUnit.MicronewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 µNmm/rad", RotationalStiffnessUnit.MicronewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 mN·m/deg", RotationalStiffnessUnit.MillinewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 mNm/deg", RotationalStiffnessUnit.MillinewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 mN·m/°", RotationalStiffnessUnit.MillinewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 mNm/°", RotationalStiffnessUnit.MillinewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 mN·mm/deg", RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 mNmm/deg", RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 mN·mm/°", RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 mNmm/°", RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 mN·mm/rad", RotationalStiffnessUnit.MillinewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 mNmm/rad", RotationalStiffnessUnit.MillinewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 nN·m/deg", RotationalStiffnessUnit.NanonewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 nNm/deg", RotationalStiffnessUnit.NanonewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 nN·m/°", RotationalStiffnessUnit.NanonewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 nNm/°", RotationalStiffnessUnit.NanonewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 nN·mm/deg", RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 nNmm/deg", RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 nN·mm/°", RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 nNmm/°", RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 nN·mm/rad", RotationalStiffnessUnit.NanonewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 nNmm/rad", RotationalStiffnessUnit.NanonewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 N·m/deg", RotationalStiffnessUnit.NewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 Nm/deg", RotationalStiffnessUnit.NewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 N·m/°", RotationalStiffnessUnit.NewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 Nm/°", RotationalStiffnessUnit.NewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 N·m/rad", RotationalStiffnessUnit.NewtonMeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 Nm/rad", RotationalStiffnessUnit.NewtonMeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 N·mm/deg", RotationalStiffnessUnit.NewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 Nmm/deg", RotationalStiffnessUnit.NewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 N·mm/°", RotationalStiffnessUnit.NewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 Nmm/°", RotationalStiffnessUnit.NewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 N·mm/rad", RotationalStiffnessUnit.NewtonMillimeterPerRadian, 4.2)] + [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, decimal expectedValue) + { + using var _ = new CultureScope(culture); + var parsed = RotationalStiffness.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); + } + [Theory] + [InlineData("en-US", "4.2 cN·m/deg", RotationalStiffnessUnit.CentinewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 cNm/deg", RotationalStiffnessUnit.CentinewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 cN·m/°", RotationalStiffnessUnit.CentinewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 cNm/°", RotationalStiffnessUnit.CentinewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 cN·mm/deg", RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 cNmm/deg", RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 cN·mm/°", RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 cNmm/°", RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 cN·mm/rad", RotationalStiffnessUnit.CentinewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 cNmm/rad", RotationalStiffnessUnit.CentinewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 daN·m/deg", RotationalStiffnessUnit.DecanewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 daNm/deg", RotationalStiffnessUnit.DecanewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 daN·m/°", RotationalStiffnessUnit.DecanewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 daNm/°", RotationalStiffnessUnit.DecanewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 daN·mm/deg", RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 daNmm/deg", RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 daN·mm/°", RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 daNmm/°", RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 daN·mm/rad", RotationalStiffnessUnit.DecanewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 daNmm/rad", RotationalStiffnessUnit.DecanewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 dN·m/deg", RotationalStiffnessUnit.DecinewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 dNm/deg", RotationalStiffnessUnit.DecinewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 dN·m/°", RotationalStiffnessUnit.DecinewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 dNm/°", RotationalStiffnessUnit.DecinewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 dN·mm/deg", RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 dNmm/deg", RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 dN·mm/°", RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 dNmm/°", RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 dN·mm/rad", RotationalStiffnessUnit.DecinewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 dNmm/rad", RotationalStiffnessUnit.DecinewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 kN·m/deg", RotationalStiffnessUnit.KilonewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 kNm/deg", RotationalStiffnessUnit.KilonewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 kN·m/°", RotationalStiffnessUnit.KilonewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 kNm/°", RotationalStiffnessUnit.KilonewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 kN·m/rad", RotationalStiffnessUnit.KilonewtonMeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 kNm/rad", RotationalStiffnessUnit.KilonewtonMeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 kN·mm/deg", RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 kNmm/deg", RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 kN·mm/°", RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 kNmm/°", RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 kN·mm/rad", RotationalStiffnessUnit.KilonewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 kNmm/rad", RotationalStiffnessUnit.KilonewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 kipf·ft/°", RotationalStiffnessUnit.KilopoundForceFootPerDegrees, 4.2)] + [InlineData("en-US", "4.2 kip·ft/°g", RotationalStiffnessUnit.KilopoundForceFootPerDegrees, 4.2)] + [InlineData("en-US", "4.2 k·ft/°", RotationalStiffnessUnit.KilopoundForceFootPerDegrees, 4.2)] + [InlineData("en-US", "4.2 kipf·ft/deg", RotationalStiffnessUnit.KilopoundForceFootPerDegrees, 4.2)] + [InlineData("en-US", "4.2 kip·ft/deg", RotationalStiffnessUnit.KilopoundForceFootPerDegrees, 4.2)] + [InlineData("en-US", "4.2 k·ft/deg", RotationalStiffnessUnit.KilopoundForceFootPerDegrees, 4.2)] + [InlineData("en-US", "4.2 MN·m/deg", RotationalStiffnessUnit.MeganewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 MNm/deg", RotationalStiffnessUnit.MeganewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 MN·m/°", RotationalStiffnessUnit.MeganewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 MNm/°", RotationalStiffnessUnit.MeganewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 MN·m/rad", RotationalStiffnessUnit.MeganewtonMeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 MNm/rad", RotationalStiffnessUnit.MeganewtonMeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 MN·mm/deg", RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 MNmm/deg", RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 MN·mm/°", RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 MNmm/°", RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 MN·mm/rad", RotationalStiffnessUnit.MeganewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 MNmm/rad", RotationalStiffnessUnit.MeganewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 µN·m/deg", RotationalStiffnessUnit.MicronewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 µNm/deg", RotationalStiffnessUnit.MicronewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 µN·m/°", RotationalStiffnessUnit.MicronewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 µNm/°", RotationalStiffnessUnit.MicronewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 µN·mm/deg", RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 µNmm/deg", RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 µN·mm/°", RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 µNmm/°", RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 µN·mm/rad", RotationalStiffnessUnit.MicronewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 µNmm/rad", RotationalStiffnessUnit.MicronewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 mN·m/deg", RotationalStiffnessUnit.MillinewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 mNm/deg", RotationalStiffnessUnit.MillinewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 mN·m/°", RotationalStiffnessUnit.MillinewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 mNm/°", RotationalStiffnessUnit.MillinewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 mN·mm/deg", RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 mNmm/deg", RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 mN·mm/°", RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 mNmm/°", RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 mN·mm/rad", RotationalStiffnessUnit.MillinewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 mNmm/rad", RotationalStiffnessUnit.MillinewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 nN·m/deg", RotationalStiffnessUnit.NanonewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 nNm/deg", RotationalStiffnessUnit.NanonewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 nN·m/°", RotationalStiffnessUnit.NanonewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 nNm/°", RotationalStiffnessUnit.NanonewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 nN·mm/deg", RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 nNmm/deg", RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 nN·mm/°", RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 nNmm/°", RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 nN·mm/rad", RotationalStiffnessUnit.NanonewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 nNmm/rad", RotationalStiffnessUnit.NanonewtonMillimeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 N·m/deg", RotationalStiffnessUnit.NewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 Nm/deg", RotationalStiffnessUnit.NewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 N·m/°", RotationalStiffnessUnit.NewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 Nm/°", RotationalStiffnessUnit.NewtonMeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 N·m/rad", RotationalStiffnessUnit.NewtonMeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 Nm/rad", RotationalStiffnessUnit.NewtonMeterPerRadian, 4.2)] + [InlineData("en-US", "4.2 N·mm/deg", RotationalStiffnessUnit.NewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 Nmm/deg", RotationalStiffnessUnit.NewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 N·mm/°", RotationalStiffnessUnit.NewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 Nmm/°", RotationalStiffnessUnit.NewtonMillimeterPerDegree, 4.2)] + [InlineData("en-US", "4.2 N·mm/rad", RotationalStiffnessUnit.NewtonMillimeterPerRadian, 4.2)] + [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, decimal expectedValue) + { + using var _ = new CultureScope(culture); + Assert.True(RotationalStiffness.TryParse(quantityString, out RotationalStiffness parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -2727,6 +1729,59 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Rotati Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", RotationalStiffnessUnit.CentinewtonMeterPerDegree, "cN·m/deg")] + [InlineData("en-US", RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, "cN·mm/deg")] + [InlineData("en-US", RotationalStiffnessUnit.CentinewtonMillimeterPerRadian, "cN·mm/rad")] + [InlineData("en-US", RotationalStiffnessUnit.DecanewtonMeterPerDegree, "daN·m/deg")] + [InlineData("en-US", RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, "daN·mm/deg")] + [InlineData("en-US", RotationalStiffnessUnit.DecanewtonMillimeterPerRadian, "daN·mm/rad")] + [InlineData("en-US", RotationalStiffnessUnit.DecinewtonMeterPerDegree, "dN·m/deg")] + [InlineData("en-US", RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, "dN·mm/deg")] + [InlineData("en-US", RotationalStiffnessUnit.DecinewtonMillimeterPerRadian, "dN·mm/rad")] + [InlineData("en-US", RotationalStiffnessUnit.KilonewtonMeterPerDegree, "kN·m/deg")] + [InlineData("en-US", RotationalStiffnessUnit.KilonewtonMeterPerRadian, "kN·m/rad")] + [InlineData("en-US", RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, "kN·mm/deg")] + [InlineData("en-US", RotationalStiffnessUnit.KilonewtonMillimeterPerRadian, "kN·mm/rad")] + [InlineData("en-US", RotationalStiffnessUnit.KilopoundForceFootPerDegrees, "kipf·ft/°")] + [InlineData("en-US", RotationalStiffnessUnit.MeganewtonMeterPerDegree, "MN·m/deg")] + [InlineData("en-US", RotationalStiffnessUnit.MeganewtonMeterPerRadian, "MN·m/rad")] + [InlineData("en-US", RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, "MN·mm/deg")] + [InlineData("en-US", RotationalStiffnessUnit.MeganewtonMillimeterPerRadian, "MN·mm/rad")] + [InlineData("en-US", RotationalStiffnessUnit.MicronewtonMeterPerDegree, "µN·m/deg")] + [InlineData("en-US", RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, "µN·mm/deg")] + [InlineData("en-US", RotationalStiffnessUnit.MicronewtonMillimeterPerRadian, "µN·mm/rad")] + [InlineData("en-US", RotationalStiffnessUnit.MillinewtonMeterPerDegree, "mN·m/deg")] + [InlineData("en-US", RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, "mN·mm/deg")] + [InlineData("en-US", RotationalStiffnessUnit.MillinewtonMillimeterPerRadian, "mN·mm/rad")] + [InlineData("en-US", RotationalStiffnessUnit.NanonewtonMeterPerDegree, "nN·m/deg")] + [InlineData("en-US", RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, "nN·mm/deg")] + [InlineData("en-US", RotationalStiffnessUnit.NanonewtonMillimeterPerRadian, "nN·mm/rad")] + [InlineData("en-US", RotationalStiffnessUnit.NewtonMeterPerDegree, "N·m/deg")] + [InlineData("en-US", RotationalStiffnessUnit.NewtonMeterPerRadian, "N·m/rad")] + [InlineData("en-US", RotationalStiffnessUnit.NewtonMillimeterPerDegree, "N·mm/deg")] + [InlineData("en-US", RotationalStiffnessUnit.NewtonMillimeterPerRadian, "N·mm/rad")] + [InlineData("en-US", RotationalStiffnessUnit.PoundForceFeetPerRadian, "lbf·ft/rad")] + [InlineData("en-US", RotationalStiffnessUnit.PoundForceFootPerDegrees, "lbf·ft/deg")] + public void GetAbbreviationForCulture(string culture, RotationalStiffnessUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = RotationalStiffness.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(RotationalStiffness.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = RotationalStiffness.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(RotationalStiffnessUnit unit) @@ -2757,6 +1812,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); }); } @@ -2780,64 +1836,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] @@ -2883,8 +1941,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); @@ -2921,23 +1977,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = RotationalStiffness.FromNewtonMetersPerRadian(1); - Assert.True(v.Equals(RotationalStiffness.FromNewtonMetersPerRadian(1), NewtonMetersPerRadianTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(RotationalStiffness.Zero, NewtonMetersPerRadianTolerance, ComparisonType.Relative)); - Assert.True(RotationalStiffness.FromNewtonMetersPerRadian(100).Equals(RotationalStiffness.FromNewtonMetersPerRadian(120), 0.3, ComparisonType.Relative)); - Assert.False(RotationalStiffness.FromNewtonMetersPerRadian(100).Equals(RotationalStiffness.FromNewtonMetersPerRadian(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = RotationalStiffness.FromNewtonMetersPerRadian(1); - Assert.Throws(() => v.Equals(RotationalStiffness.FromNewtonMetersPerRadian(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -2952,6 +1991,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(newtonmeterperradian.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1); + var negativeTolerance = RotationalStiffness.FromNewtonMetersPerRadian(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -2968,6 +2033,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() { @@ -3090,158 +2167,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(RotationalStiffness))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(RotationalStiffnessUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal(RotationalStiffness.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal(RotationalStiffness.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal(new {RotationalStiffness.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 5ec1d0e605..80d1279caa 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ScalarTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ScalarTestsBase.g.cs @@ -88,15 +88,33 @@ public void Ctor_WithNaNValue_DoNotThrowsArgumentException() [Fact] public void Scalar_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ScalarUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Scalar(1, ScalarUnit.Amount); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Scalar.Zero, quantityInfo.Zero); Assert.Equal("Scalar", quantityInfo.Name); + Assert.Equal(Scalar.Zero, quantityInfo.Zero); + Assert.Equal(Scalar.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Scalar.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -110,7 +128,7 @@ public void AmountToScalarUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Scalar.From(1, ScalarUnit.Amount); - AssertEx.EqualTolerance(1, quantity00.Amount, AmountTolerance); + Assert.Equal(1, quantity00.Amount); Assert.Equal(ScalarUnit.Amount, quantity00.Unit); } @@ -207,27 +225,24 @@ public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 ", ScalarUnit.Amount, 4.2)] + public void Parse(string culture, string quantityString, ScalarUnit expectedUnit, decimal expectedValue) { - try - { - var parsed = Scalar.Parse("1 ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Amount, AmountTolerance); - Assert.Equal(ScalarUnit.Amount, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Scalar.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 ", ScalarUnit.Amount, 4.2)] + public void TryParse(string culture, string quantityString, ScalarUnit expectedUnit, decimal expectedValue) { - { - Assert.True(Scalar.TryParse("1 ", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Amount, AmountTolerance); - Assert.Equal(ScalarUnit.Amount, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Scalar.TryParse(quantityString, out Scalar parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -304,6 +319,27 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Scalar Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ScalarUnit.Amount, "")] + public void GetAbbreviationForCulture(string culture, ScalarUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Scalar.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Scalar.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Scalar.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ScalarUnit unit) @@ -334,6 +370,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); }); } @@ -357,32 +394,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] @@ -428,7 +467,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); @@ -466,34 +504,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = Scalar.FromAmount(1); - Assert.True(v.Equals(Scalar.FromAmount(1), AmountTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Scalar.Zero, AmountTolerance, ComparisonType.Relative)); - Assert.True(Scalar.FromAmount(100).Equals(Scalar.FromAmount(120), 0.3, ComparisonType.Relative)); - Assert.False(Scalar.FromAmount(100).Equals(Scalar.FromAmount(120), 0.1, ComparisonType.Relative)); + Scalar amount = Scalar.FromAmount(1); + Assert.False(amount.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = Scalar.FromAmount(1); - Assert.Throws(() => v.Equals(Scalar.FromAmount(1), -1, ComparisonType.Relative)); + Scalar amount = Scalar.FromAmount(1); + Assert.False(amount.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - Scalar amount = Scalar.FromAmount(1); - Assert.False(amount.Equals(new object())); + var quantity = Scalar.FromAmount(firstValue); + var otherQuantity = Scalar.FromAmount(secondValue); + Scalar maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - Scalar amount = Scalar.FromAmount(1); - Assert.False(amount.Equals(null)); + var quantity = Scalar.FromAmount(1); + var negativeTolerance = Scalar.FromAmount(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -512,6 +559,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() { @@ -570,158 +629,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Scalar.FromAmount(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Scalar.FromAmount(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Scalar.FromAmount(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Scalar))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ScalarUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal(Scalar.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal(Scalar.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Scalar.FromAmount(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Scalar.FromAmount(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Scalar.FromAmount(1.0); - Assert.Equal(new {Scalar.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 c368c75ce6..4f16c4201c 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SolidAngleTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SolidAngleTestsBase.g.cs @@ -88,15 +88,33 @@ public void Ctor_WithNaNValue_DoNotThrowsArgumentException() [Fact] public void SolidAngle_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + SolidAngleUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new SolidAngle(1, SolidAngleUnit.Steradian); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(SolidAngle.Zero, quantityInfo.Zero); Assert.Equal("SolidAngle", quantityInfo.Name); + Assert.Equal(SolidAngle.Zero, quantityInfo.Zero); + Assert.Equal(SolidAngle.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(SolidAngle.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -110,7 +128,7 @@ public void SteradianToSolidAngleUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = SolidAngle.From(1, SolidAngleUnit.Steradian); - AssertEx.EqualTolerance(1, quantity00.Steradians, SteradiansTolerance); + Assert.Equal(1, quantity00.Steradians); Assert.Equal(SolidAngleUnit.Steradian, quantity00.Unit); } @@ -207,27 +225,24 @@ public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 sr", SolidAngleUnit.Steradian, 4.2)] + public void Parse(string culture, string quantityString, SolidAngleUnit expectedUnit, decimal expectedValue) { - try - { - var parsed = SolidAngle.Parse("1 sr", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Steradians, SteradiansTolerance); - Assert.Equal(SolidAngleUnit.Steradian, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = SolidAngle.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 sr", SolidAngleUnit.Steradian, 4.2)] + public void TryParse(string culture, string quantityString, SolidAngleUnit expectedUnit, decimal expectedValue) { - { - Assert.True(SolidAngle.TryParse("1 sr", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Steradians, SteradiansTolerance); - Assert.Equal(SolidAngleUnit.Steradian, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(SolidAngle.TryParse(quantityString, out SolidAngle parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -304,6 +319,27 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, SolidA Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", SolidAngleUnit.Steradian, "sr")] + public void GetAbbreviationForCulture(string culture, SolidAngleUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = SolidAngle.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(SolidAngle.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = SolidAngle.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(SolidAngleUnit unit) @@ -334,6 +370,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); }); } @@ -357,32 +394,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] @@ -428,7 +467,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); @@ -466,34 +504,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = SolidAngle.FromSteradians(1); - Assert.True(v.Equals(SolidAngle.FromSteradians(1), SteradiansTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(SolidAngle.Zero, SteradiansTolerance, ComparisonType.Relative)); - Assert.True(SolidAngle.FromSteradians(100).Equals(SolidAngle.FromSteradians(120), 0.3, ComparisonType.Relative)); - Assert.False(SolidAngle.FromSteradians(100).Equals(SolidAngle.FromSteradians(120), 0.1, ComparisonType.Relative)); + SolidAngle steradian = SolidAngle.FromSteradians(1); + Assert.False(steradian.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = SolidAngle.FromSteradians(1); - Assert.Throws(() => v.Equals(SolidAngle.FromSteradians(1), -1, ComparisonType.Relative)); + SolidAngle steradian = SolidAngle.FromSteradians(1); + Assert.False(steradian.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - SolidAngle steradian = SolidAngle.FromSteradians(1); - Assert.False(steradian.Equals(new object())); + var quantity = SolidAngle.FromSteradians(firstValue); + var otherQuantity = SolidAngle.FromSteradians(secondValue); + SolidAngle maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - SolidAngle steradian = SolidAngle.FromSteradians(1); - Assert.False(steradian.Equals(null)); + var quantity = SolidAngle.FromSteradians(1); + var negativeTolerance = SolidAngle.FromSteradians(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -512,6 +559,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() { @@ -570,158 +629,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(SolidAngle))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(SolidAngleUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal(SolidAngle.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal(SolidAngle.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal(new {SolidAngle.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 03876689f4..56882625bd 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEnergyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEnergyTestsBase.g.cs @@ -212,7 +212,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new SpecificEnergy(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -225,15 +225,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void SpecificEnergy_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + SpecificEnergyUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new SpecificEnergy(1, SpecificEnergyUnit.JoulePerKilogram); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(SpecificEnergy.Zero, quantityInfo.Zero); Assert.Equal("SpecificEnergy", quantityInfo.Name); + Assert.Equal(SpecificEnergy.Zero, quantityInfo.Zero); + Assert.Equal(SpecificEnergy.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(SpecificEnergy.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -276,123 +294,123 @@ public void JoulePerKilogramToSpecificEnergyUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = SpecificEnergy.From(1, SpecificEnergyUnit.BtuPerPound); - AssertEx.EqualTolerance(1, quantity00.BtuPerPound, BtuPerPoundTolerance); + Assert.Equal(1, quantity00.BtuPerPound); Assert.Equal(SpecificEnergyUnit.BtuPerPound, quantity00.Unit); var quantity01 = SpecificEnergy.From(1, SpecificEnergyUnit.CaloriePerGram); - AssertEx.EqualTolerance(1, quantity01.CaloriesPerGram, CaloriesPerGramTolerance); + Assert.Equal(1, quantity01.CaloriesPerGram); Assert.Equal(SpecificEnergyUnit.CaloriePerGram, quantity01.Unit); var quantity02 = SpecificEnergy.From(1, SpecificEnergyUnit.GigawattDayPerKilogram); - AssertEx.EqualTolerance(1, quantity02.GigawattDaysPerKilogram, GigawattDaysPerKilogramTolerance); + Assert.Equal(1, quantity02.GigawattDaysPerKilogram); Assert.Equal(SpecificEnergyUnit.GigawattDayPerKilogram, quantity02.Unit); var quantity03 = SpecificEnergy.From(1, SpecificEnergyUnit.GigawattDayPerShortTon); - AssertEx.EqualTolerance(1, quantity03.GigawattDaysPerShortTon, GigawattDaysPerShortTonTolerance); + Assert.Equal(1, quantity03.GigawattDaysPerShortTon); Assert.Equal(SpecificEnergyUnit.GigawattDayPerShortTon, quantity03.Unit); var quantity04 = SpecificEnergy.From(1, SpecificEnergyUnit.GigawattDayPerTonne); - AssertEx.EqualTolerance(1, quantity04.GigawattDaysPerTonne, GigawattDaysPerTonneTolerance); + Assert.Equal(1, quantity04.GigawattDaysPerTonne); Assert.Equal(SpecificEnergyUnit.GigawattDayPerTonne, quantity04.Unit); var quantity05 = SpecificEnergy.From(1, SpecificEnergyUnit.GigawattHourPerKilogram); - AssertEx.EqualTolerance(1, quantity05.GigawattHoursPerKilogram, GigawattHoursPerKilogramTolerance); + Assert.Equal(1, quantity05.GigawattHoursPerKilogram); Assert.Equal(SpecificEnergyUnit.GigawattHourPerKilogram, quantity05.Unit); var quantity06 = SpecificEnergy.From(1, SpecificEnergyUnit.GigawattHourPerPound); - AssertEx.EqualTolerance(1, quantity06.GigawattHoursPerPound, GigawattHoursPerPoundTolerance); + Assert.Equal(1, quantity06.GigawattHoursPerPound); Assert.Equal(SpecificEnergyUnit.GigawattHourPerPound, quantity06.Unit); var quantity07 = SpecificEnergy.From(1, SpecificEnergyUnit.JoulePerKilogram); - AssertEx.EqualTolerance(1, quantity07.JoulesPerKilogram, JoulesPerKilogramTolerance); + Assert.Equal(1, quantity07.JoulesPerKilogram); Assert.Equal(SpecificEnergyUnit.JoulePerKilogram, quantity07.Unit); var quantity08 = SpecificEnergy.From(1, SpecificEnergyUnit.KilocaloriePerGram); - AssertEx.EqualTolerance(1, quantity08.KilocaloriesPerGram, KilocaloriesPerGramTolerance); + Assert.Equal(1, quantity08.KilocaloriesPerGram); Assert.Equal(SpecificEnergyUnit.KilocaloriePerGram, quantity08.Unit); var quantity09 = SpecificEnergy.From(1, SpecificEnergyUnit.KilojoulePerKilogram); - AssertEx.EqualTolerance(1, quantity09.KilojoulesPerKilogram, KilojoulesPerKilogramTolerance); + Assert.Equal(1, quantity09.KilojoulesPerKilogram); Assert.Equal(SpecificEnergyUnit.KilojoulePerKilogram, quantity09.Unit); var quantity10 = SpecificEnergy.From(1, SpecificEnergyUnit.KilowattDayPerKilogram); - AssertEx.EqualTolerance(1, quantity10.KilowattDaysPerKilogram, KilowattDaysPerKilogramTolerance); + Assert.Equal(1, quantity10.KilowattDaysPerKilogram); Assert.Equal(SpecificEnergyUnit.KilowattDayPerKilogram, quantity10.Unit); var quantity11 = SpecificEnergy.From(1, SpecificEnergyUnit.KilowattDayPerShortTon); - AssertEx.EqualTolerance(1, quantity11.KilowattDaysPerShortTon, KilowattDaysPerShortTonTolerance); + Assert.Equal(1, quantity11.KilowattDaysPerShortTon); Assert.Equal(SpecificEnergyUnit.KilowattDayPerShortTon, quantity11.Unit); var quantity12 = SpecificEnergy.From(1, SpecificEnergyUnit.KilowattDayPerTonne); - AssertEx.EqualTolerance(1, quantity12.KilowattDaysPerTonne, KilowattDaysPerTonneTolerance); + Assert.Equal(1, quantity12.KilowattDaysPerTonne); Assert.Equal(SpecificEnergyUnit.KilowattDayPerTonne, quantity12.Unit); var quantity13 = SpecificEnergy.From(1, SpecificEnergyUnit.KilowattHourPerKilogram); - AssertEx.EqualTolerance(1, quantity13.KilowattHoursPerKilogram, KilowattHoursPerKilogramTolerance); + Assert.Equal(1, quantity13.KilowattHoursPerKilogram); Assert.Equal(SpecificEnergyUnit.KilowattHourPerKilogram, quantity13.Unit); var quantity14 = SpecificEnergy.From(1, SpecificEnergyUnit.KilowattHourPerPound); - AssertEx.EqualTolerance(1, quantity14.KilowattHoursPerPound, KilowattHoursPerPoundTolerance); + Assert.Equal(1, quantity14.KilowattHoursPerPound); Assert.Equal(SpecificEnergyUnit.KilowattHourPerPound, quantity14.Unit); var quantity15 = SpecificEnergy.From(1, SpecificEnergyUnit.MegajoulePerKilogram); - AssertEx.EqualTolerance(1, quantity15.MegajoulesPerKilogram, MegajoulesPerKilogramTolerance); + Assert.Equal(1, quantity15.MegajoulesPerKilogram); Assert.Equal(SpecificEnergyUnit.MegajoulePerKilogram, quantity15.Unit); var quantity16 = SpecificEnergy.From(1, SpecificEnergyUnit.MegaJoulePerTonne); - AssertEx.EqualTolerance(1, quantity16.MegaJoulesPerTonne, MegaJoulesPerTonneTolerance); + Assert.Equal(1, quantity16.MegaJoulesPerTonne); Assert.Equal(SpecificEnergyUnit.MegaJoulePerTonne, quantity16.Unit); var quantity17 = SpecificEnergy.From(1, SpecificEnergyUnit.MegawattDayPerKilogram); - AssertEx.EqualTolerance(1, quantity17.MegawattDaysPerKilogram, MegawattDaysPerKilogramTolerance); + Assert.Equal(1, quantity17.MegawattDaysPerKilogram); Assert.Equal(SpecificEnergyUnit.MegawattDayPerKilogram, quantity17.Unit); var quantity18 = SpecificEnergy.From(1, SpecificEnergyUnit.MegawattDayPerShortTon); - AssertEx.EqualTolerance(1, quantity18.MegawattDaysPerShortTon, MegawattDaysPerShortTonTolerance); + Assert.Equal(1, quantity18.MegawattDaysPerShortTon); Assert.Equal(SpecificEnergyUnit.MegawattDayPerShortTon, quantity18.Unit); var quantity19 = SpecificEnergy.From(1, SpecificEnergyUnit.MegawattDayPerTonne); - AssertEx.EqualTolerance(1, quantity19.MegawattDaysPerTonne, MegawattDaysPerTonneTolerance); + Assert.Equal(1, quantity19.MegawattDaysPerTonne); Assert.Equal(SpecificEnergyUnit.MegawattDayPerTonne, quantity19.Unit); var quantity20 = SpecificEnergy.From(1, SpecificEnergyUnit.MegawattHourPerKilogram); - AssertEx.EqualTolerance(1, quantity20.MegawattHoursPerKilogram, MegawattHoursPerKilogramTolerance); + Assert.Equal(1, quantity20.MegawattHoursPerKilogram); Assert.Equal(SpecificEnergyUnit.MegawattHourPerKilogram, quantity20.Unit); var quantity21 = SpecificEnergy.From(1, SpecificEnergyUnit.MegawattHourPerPound); - AssertEx.EqualTolerance(1, quantity21.MegawattHoursPerPound, MegawattHoursPerPoundTolerance); + Assert.Equal(1, quantity21.MegawattHoursPerPound); Assert.Equal(SpecificEnergyUnit.MegawattHourPerPound, quantity21.Unit); var quantity22 = SpecificEnergy.From(1, SpecificEnergyUnit.TerawattDayPerKilogram); - AssertEx.EqualTolerance(1, quantity22.TerawattDaysPerKilogram, TerawattDaysPerKilogramTolerance); + Assert.Equal(1, quantity22.TerawattDaysPerKilogram); Assert.Equal(SpecificEnergyUnit.TerawattDayPerKilogram, quantity22.Unit); var quantity23 = SpecificEnergy.From(1, SpecificEnergyUnit.TerawattDayPerShortTon); - AssertEx.EqualTolerance(1, quantity23.TerawattDaysPerShortTon, TerawattDaysPerShortTonTolerance); + Assert.Equal(1, quantity23.TerawattDaysPerShortTon); Assert.Equal(SpecificEnergyUnit.TerawattDayPerShortTon, quantity23.Unit); var quantity24 = SpecificEnergy.From(1, SpecificEnergyUnit.TerawattDayPerTonne); - AssertEx.EqualTolerance(1, quantity24.TerawattDaysPerTonne, TerawattDaysPerTonneTolerance); + Assert.Equal(1, quantity24.TerawattDaysPerTonne); Assert.Equal(SpecificEnergyUnit.TerawattDayPerTonne, quantity24.Unit); var quantity25 = SpecificEnergy.From(1, SpecificEnergyUnit.WattDayPerKilogram); - AssertEx.EqualTolerance(1, quantity25.WattDaysPerKilogram, WattDaysPerKilogramTolerance); + Assert.Equal(1, quantity25.WattDaysPerKilogram); Assert.Equal(SpecificEnergyUnit.WattDayPerKilogram, quantity25.Unit); var quantity26 = SpecificEnergy.From(1, SpecificEnergyUnit.WattDayPerShortTon); - AssertEx.EqualTolerance(1, quantity26.WattDaysPerShortTon, WattDaysPerShortTonTolerance); + Assert.Equal(1, quantity26.WattDaysPerShortTon); Assert.Equal(SpecificEnergyUnit.WattDayPerShortTon, quantity26.Unit); var quantity27 = SpecificEnergy.From(1, SpecificEnergyUnit.WattDayPerTonne); - AssertEx.EqualTolerance(1, quantity27.WattDaysPerTonne, WattDaysPerTonneTolerance); + Assert.Equal(1, quantity27.WattDaysPerTonne); Assert.Equal(SpecificEnergyUnit.WattDayPerTonne, quantity27.Unit); var quantity28 = SpecificEnergy.From(1, SpecificEnergyUnit.WattHourPerKilogram); - AssertEx.EqualTolerance(1, quantity28.WattHoursPerKilogram, WattHoursPerKilogramTolerance); + Assert.Equal(1, quantity28.WattHoursPerKilogram); Assert.Equal(SpecificEnergyUnit.WattHourPerKilogram, quantity28.Unit); var quantity29 = SpecificEnergy.From(1, SpecificEnergyUnit.WattHourPerPound); - AssertEx.EqualTolerance(1, quantity29.WattHoursPerPound, WattHoursPerPoundTolerance); + Assert.Equal(1, quantity29.WattHoursPerPound); Assert.Equal(SpecificEnergyUnit.WattHourPerPound, quantity29.Unit); } @@ -557,404 +575,82 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 btu/lb", SpecificEnergyUnit.BtuPerPound, 4.2)] + [InlineData("en-US", "4.2 cal/g", SpecificEnergyUnit.CaloriePerGram, 4.2)] + [InlineData("en-US", "4.2 GWd/kg", SpecificEnergyUnit.GigawattDayPerKilogram, 4.2)] + [InlineData("en-US", "4.2 GWd/ST", SpecificEnergyUnit.GigawattDayPerShortTon, 4.2)] + [InlineData("en-US", "4.2 GWd/t", SpecificEnergyUnit.GigawattDayPerTonne, 4.2)] + [InlineData("en-US", "4.2 GWh/kg", SpecificEnergyUnit.GigawattHourPerKilogram, 4.2)] + [InlineData("en-US", "4.2 GWh/lbs", SpecificEnergyUnit.GigawattHourPerPound, 4.2)] + [InlineData("en-US", "4.2 J/kg", SpecificEnergyUnit.JoulePerKilogram, 4.2)] + [InlineData("en-US", "4.2 kcal/g", SpecificEnergyUnit.KilocaloriePerGram, 4.2)] + [InlineData("en-US", "4.2 kJ/kg", SpecificEnergyUnit.KilojoulePerKilogram, 4.2)] + [InlineData("en-US", "4.2 kWd/kg", SpecificEnergyUnit.KilowattDayPerKilogram, 4.2)] + [InlineData("en-US", "4.2 kWd/ST", SpecificEnergyUnit.KilowattDayPerShortTon, 4.2)] + [InlineData("en-US", "4.2 kWd/t", SpecificEnergyUnit.KilowattDayPerTonne, 4.2)] + [InlineData("en-US", "4.2 kWh/kg", SpecificEnergyUnit.KilowattHourPerKilogram, 4.2)] + [InlineData("en-US", "4.2 kWh/lbs", SpecificEnergyUnit.KilowattHourPerPound, 4.2)] + [InlineData("en-US", "4.2 MJ/kg", SpecificEnergyUnit.MegajoulePerKilogram, 4.2)] + [InlineData("en-US", "4.2 MJ/t", SpecificEnergyUnit.MegaJoulePerTonne, 4.2)] + [InlineData("en-US", "4.2 MWd/kg", SpecificEnergyUnit.MegawattDayPerKilogram, 4.2)] + [InlineData("en-US", "4.2 MWd/ST", SpecificEnergyUnit.MegawattDayPerShortTon, 4.2)] + [InlineData("en-US", "4.2 MWd/t", SpecificEnergyUnit.MegawattDayPerTonne, 4.2)] + [InlineData("en-US", "4.2 MWh/kg", SpecificEnergyUnit.MegawattHourPerKilogram, 4.2)] + [InlineData("en-US", "4.2 MWh/lbs", SpecificEnergyUnit.MegawattHourPerPound, 4.2)] + [InlineData("en-US", "4.2 TWd/kg", SpecificEnergyUnit.TerawattDayPerKilogram, 4.2)] + [InlineData("en-US", "4.2 TWd/ST", SpecificEnergyUnit.TerawattDayPerShortTon, 4.2)] + [InlineData("en-US", "4.2 TWd/t", SpecificEnergyUnit.TerawattDayPerTonne, 4.2)] + [InlineData("en-US", "4.2 Wd/kg", SpecificEnergyUnit.WattDayPerKilogram, 4.2)] + [InlineData("en-US", "4.2 Wd/ST", SpecificEnergyUnit.WattDayPerShortTon, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = SpecificEnergy.Parse("1 btu/lb", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.BtuPerPound, BtuPerPoundTolerance); - Assert.Equal(SpecificEnergyUnit.BtuPerPound, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 cal/g", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CaloriesPerGram, CaloriesPerGramTolerance); - Assert.Equal(SpecificEnergyUnit.CaloriePerGram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 GWd/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GigawattDaysPerKilogram, GigawattDaysPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.GigawattDayPerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 GWd/ST", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GigawattDaysPerShortTon, GigawattDaysPerShortTonTolerance); - Assert.Equal(SpecificEnergyUnit.GigawattDayPerShortTon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 GWd/t", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GigawattDaysPerTonne, GigawattDaysPerTonneTolerance); - Assert.Equal(SpecificEnergyUnit.GigawattDayPerTonne, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 GWh/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GigawattHoursPerKilogram, GigawattHoursPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.GigawattHourPerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 GWh/lbs", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GigawattHoursPerPound, GigawattHoursPerPoundTolerance); - Assert.Equal(SpecificEnergyUnit.GigawattHourPerPound, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 J/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.JoulesPerKilogram, JoulesPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.JoulePerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 kcal/g", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilocaloriesPerGram, KilocaloriesPerGramTolerance); - Assert.Equal(SpecificEnergyUnit.KilocaloriePerGram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 kJ/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilojoulesPerKilogram, KilojoulesPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.KilojoulePerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 kWd/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilowattDaysPerKilogram, KilowattDaysPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.KilowattDayPerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 kWd/ST", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilowattDaysPerShortTon, KilowattDaysPerShortTonTolerance); - Assert.Equal(SpecificEnergyUnit.KilowattDayPerShortTon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 kWd/t", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilowattDaysPerTonne, KilowattDaysPerTonneTolerance); - Assert.Equal(SpecificEnergyUnit.KilowattDayPerTonne, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 kWh/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilowattHoursPerKilogram, KilowattHoursPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.KilowattHourPerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 kWh/lbs", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilowattHoursPerPound, KilowattHoursPerPoundTolerance); - Assert.Equal(SpecificEnergyUnit.KilowattHourPerPound, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 MJ/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegajoulesPerKilogram, MegajoulesPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.MegajoulePerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 MJ/t", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegaJoulesPerTonne, MegaJoulesPerTonneTolerance); - Assert.Equal(SpecificEnergyUnit.MegaJoulePerTonne, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 MWd/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegawattDaysPerKilogram, MegawattDaysPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.MegawattDayPerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 MWd/ST", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegawattDaysPerShortTon, MegawattDaysPerShortTonTolerance); - Assert.Equal(SpecificEnergyUnit.MegawattDayPerShortTon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 MWd/t", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegawattDaysPerTonne, MegawattDaysPerTonneTolerance); - Assert.Equal(SpecificEnergyUnit.MegawattDayPerTonne, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 MWh/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegawattHoursPerKilogram, MegawattHoursPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.MegawattHourPerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 MWh/lbs", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegawattHoursPerPound, MegawattHoursPerPoundTolerance); - Assert.Equal(SpecificEnergyUnit.MegawattHourPerPound, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 TWd/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TerawattDaysPerKilogram, TerawattDaysPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.TerawattDayPerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 TWd/ST", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TerawattDaysPerShortTon, TerawattDaysPerShortTonTolerance); - Assert.Equal(SpecificEnergyUnit.TerawattDayPerShortTon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 TWd/t", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TerawattDaysPerTonne, TerawattDaysPerTonneTolerance); - Assert.Equal(SpecificEnergyUnit.TerawattDayPerTonne, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 Wd/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WattDaysPerKilogram, WattDaysPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.WattDayPerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 Wd/ST", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WattDaysPerShortTon, WattDaysPerShortTonTolerance); - Assert.Equal(SpecificEnergyUnit.WattDayPerShortTon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 Wd/t", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WattDaysPerTonne, WattDaysPerTonneTolerance); - Assert.Equal(SpecificEnergyUnit.WattDayPerTonne, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 Wh/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WattHoursPerKilogram, WattHoursPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.WattHourPerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEnergy.Parse("1 Wh/lbs", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WattHoursPerPound, WattHoursPerPoundTolerance); - Assert.Equal(SpecificEnergyUnit.WattHourPerPound, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = SpecificEnergy.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 btu/lb", SpecificEnergyUnit.BtuPerPound, 4.2)] + [InlineData("en-US", "4.2 cal/g", SpecificEnergyUnit.CaloriePerGram, 4.2)] + [InlineData("en-US", "4.2 GWd/kg", SpecificEnergyUnit.GigawattDayPerKilogram, 4.2)] + [InlineData("en-US", "4.2 GWd/ST", SpecificEnergyUnit.GigawattDayPerShortTon, 4.2)] + [InlineData("en-US", "4.2 GWd/t", SpecificEnergyUnit.GigawattDayPerTonne, 4.2)] + [InlineData("en-US", "4.2 GWh/kg", SpecificEnergyUnit.GigawattHourPerKilogram, 4.2)] + [InlineData("en-US", "4.2 GWh/lbs", SpecificEnergyUnit.GigawattHourPerPound, 4.2)] + [InlineData("en-US", "4.2 J/kg", SpecificEnergyUnit.JoulePerKilogram, 4.2)] + [InlineData("en-US", "4.2 kcal/g", SpecificEnergyUnit.KilocaloriePerGram, 4.2)] + [InlineData("en-US", "4.2 kJ/kg", SpecificEnergyUnit.KilojoulePerKilogram, 4.2)] + [InlineData("en-US", "4.2 kWd/kg", SpecificEnergyUnit.KilowattDayPerKilogram, 4.2)] + [InlineData("en-US", "4.2 kWd/ST", SpecificEnergyUnit.KilowattDayPerShortTon, 4.2)] + [InlineData("en-US", "4.2 kWd/t", SpecificEnergyUnit.KilowattDayPerTonne, 4.2)] + [InlineData("en-US", "4.2 kWh/kg", SpecificEnergyUnit.KilowattHourPerKilogram, 4.2)] + [InlineData("en-US", "4.2 kWh/lbs", SpecificEnergyUnit.KilowattHourPerPound, 4.2)] + [InlineData("en-US", "4.2 MJ/kg", SpecificEnergyUnit.MegajoulePerKilogram, 4.2)] + [InlineData("en-US", "4.2 MJ/t", SpecificEnergyUnit.MegaJoulePerTonne, 4.2)] + [InlineData("en-US", "4.2 MWd/kg", SpecificEnergyUnit.MegawattDayPerKilogram, 4.2)] + [InlineData("en-US", "4.2 MWd/ST", SpecificEnergyUnit.MegawattDayPerShortTon, 4.2)] + [InlineData("en-US", "4.2 MWd/t", SpecificEnergyUnit.MegawattDayPerTonne, 4.2)] + [InlineData("en-US", "4.2 MWh/kg", SpecificEnergyUnit.MegawattHourPerKilogram, 4.2)] + [InlineData("en-US", "4.2 MWh/lbs", SpecificEnergyUnit.MegawattHourPerPound, 4.2)] + [InlineData("en-US", "4.2 TWd/kg", SpecificEnergyUnit.TerawattDayPerKilogram, 4.2)] + [InlineData("en-US", "4.2 TWd/ST", SpecificEnergyUnit.TerawattDayPerShortTon, 4.2)] + [InlineData("en-US", "4.2 TWd/t", SpecificEnergyUnit.TerawattDayPerTonne, 4.2)] + [InlineData("en-US", "4.2 Wd/kg", SpecificEnergyUnit.WattDayPerKilogram, 4.2)] + [InlineData("en-US", "4.2 Wd/ST", SpecificEnergyUnit.WattDayPerShortTon, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(SpecificEnergy.TryParse("1 btu/lb", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BtuPerPound, BtuPerPoundTolerance); - Assert.Equal(SpecificEnergyUnit.BtuPerPound, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 cal/g", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CaloriesPerGram, CaloriesPerGramTolerance); - Assert.Equal(SpecificEnergyUnit.CaloriePerGram, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 GWd/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigawattDaysPerKilogram, GigawattDaysPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.GigawattDayPerKilogram, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 GWd/ST", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigawattDaysPerShortTon, GigawattDaysPerShortTonTolerance); - Assert.Equal(SpecificEnergyUnit.GigawattDayPerShortTon, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 GWd/t", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigawattDaysPerTonne, GigawattDaysPerTonneTolerance); - Assert.Equal(SpecificEnergyUnit.GigawattDayPerTonne, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 GWh/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigawattHoursPerKilogram, GigawattHoursPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.GigawattHourPerKilogram, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 GWh/lbs", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GigawattHoursPerPound, GigawattHoursPerPoundTolerance); - Assert.Equal(SpecificEnergyUnit.GigawattHourPerPound, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 J/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.JoulesPerKilogram, JoulesPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.JoulePerKilogram, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 kcal/g", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilocaloriesPerGram, KilocaloriesPerGramTolerance); - Assert.Equal(SpecificEnergyUnit.KilocaloriePerGram, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 kJ/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilojoulesPerKilogram, KilojoulesPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.KilojoulePerKilogram, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 kWd/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilowattDaysPerKilogram, KilowattDaysPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.KilowattDayPerKilogram, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 kWd/ST", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilowattDaysPerShortTon, KilowattDaysPerShortTonTolerance); - Assert.Equal(SpecificEnergyUnit.KilowattDayPerShortTon, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 kWd/t", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilowattDaysPerTonne, KilowattDaysPerTonneTolerance); - Assert.Equal(SpecificEnergyUnit.KilowattDayPerTonne, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 kWh/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilowattHoursPerKilogram, KilowattHoursPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.KilowattHourPerKilogram, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 kWh/lbs", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilowattHoursPerPound, KilowattHoursPerPoundTolerance); - Assert.Equal(SpecificEnergyUnit.KilowattHourPerPound, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 MJ/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegajoulesPerKilogram, MegajoulesPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.MegajoulePerKilogram, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 MJ/t", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegaJoulesPerTonne, MegaJoulesPerTonneTolerance); - Assert.Equal(SpecificEnergyUnit.MegaJoulePerTonne, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 MWd/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegawattDaysPerKilogram, MegawattDaysPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.MegawattDayPerKilogram, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 MWd/ST", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegawattDaysPerShortTon, MegawattDaysPerShortTonTolerance); - Assert.Equal(SpecificEnergyUnit.MegawattDayPerShortTon, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 MWd/t", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegawattDaysPerTonne, MegawattDaysPerTonneTolerance); - Assert.Equal(SpecificEnergyUnit.MegawattDayPerTonne, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 MWh/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegawattHoursPerKilogram, MegawattHoursPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.MegawattHourPerKilogram, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 MWh/lbs", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegawattHoursPerPound, MegawattHoursPerPoundTolerance); - Assert.Equal(SpecificEnergyUnit.MegawattHourPerPound, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 TWd/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TerawattDaysPerKilogram, TerawattDaysPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.TerawattDayPerKilogram, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 TWd/ST", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TerawattDaysPerShortTon, TerawattDaysPerShortTonTolerance); - Assert.Equal(SpecificEnergyUnit.TerawattDayPerShortTon, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 TWd/t", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TerawattDaysPerTonne, TerawattDaysPerTonneTolerance); - Assert.Equal(SpecificEnergyUnit.TerawattDayPerTonne, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 Wd/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattDaysPerKilogram, WattDaysPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.WattDayPerKilogram, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 Wd/ST", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattDaysPerShortTon, WattDaysPerShortTonTolerance); - Assert.Equal(SpecificEnergyUnit.WattDayPerShortTon, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 Wd/t", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattDaysPerTonne, WattDaysPerTonneTolerance); - Assert.Equal(SpecificEnergyUnit.WattDayPerTonne, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 Wh/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattHoursPerKilogram, WattHoursPerKilogramTolerance); - Assert.Equal(SpecificEnergyUnit.WattHourPerKilogram, parsed.Unit); - } - - { - Assert.True(SpecificEnergy.TryParse("1 Wh/lbs", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattHoursPerPound, WattHoursPerPoundTolerance); - Assert.Equal(SpecificEnergyUnit.WattHourPerPound, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(SpecificEnergy.TryParse(quantityString, out SpecificEnergy parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -1263,6 +959,56 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Specif Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", SpecificEnergyUnit.BtuPerPound, "btu/lb")] + [InlineData("en-US", SpecificEnergyUnit.CaloriePerGram, "cal/g")] + [InlineData("en-US", SpecificEnergyUnit.GigawattDayPerKilogram, "GWd/kg")] + [InlineData("en-US", SpecificEnergyUnit.GigawattDayPerShortTon, "GWd/ST")] + [InlineData("en-US", SpecificEnergyUnit.GigawattDayPerTonne, "GWd/t")] + [InlineData("en-US", SpecificEnergyUnit.GigawattHourPerKilogram, "GWh/kg")] + [InlineData("en-US", SpecificEnergyUnit.GigawattHourPerPound, "GWh/lbs")] + [InlineData("en-US", SpecificEnergyUnit.JoulePerKilogram, "J/kg")] + [InlineData("en-US", SpecificEnergyUnit.KilocaloriePerGram, "kcal/g")] + [InlineData("en-US", SpecificEnergyUnit.KilojoulePerKilogram, "kJ/kg")] + [InlineData("en-US", SpecificEnergyUnit.KilowattDayPerKilogram, "kWd/kg")] + [InlineData("en-US", SpecificEnergyUnit.KilowattDayPerShortTon, "kWd/ST")] + [InlineData("en-US", SpecificEnergyUnit.KilowattDayPerTonne, "kWd/t")] + [InlineData("en-US", SpecificEnergyUnit.KilowattHourPerKilogram, "kWh/kg")] + [InlineData("en-US", SpecificEnergyUnit.KilowattHourPerPound, "kWh/lbs")] + [InlineData("en-US", SpecificEnergyUnit.MegajoulePerKilogram, "MJ/kg")] + [InlineData("en-US", SpecificEnergyUnit.MegaJoulePerTonne, "MJ/t")] + [InlineData("en-US", SpecificEnergyUnit.MegawattDayPerKilogram, "MWd/kg")] + [InlineData("en-US", SpecificEnergyUnit.MegawattDayPerShortTon, "MWd/ST")] + [InlineData("en-US", SpecificEnergyUnit.MegawattDayPerTonne, "MWd/t")] + [InlineData("en-US", SpecificEnergyUnit.MegawattHourPerKilogram, "MWh/kg")] + [InlineData("en-US", SpecificEnergyUnit.MegawattHourPerPound, "MWh/lbs")] + [InlineData("en-US", SpecificEnergyUnit.TerawattDayPerKilogram, "TWd/kg")] + [InlineData("en-US", SpecificEnergyUnit.TerawattDayPerShortTon, "TWd/ST")] + [InlineData("en-US", SpecificEnergyUnit.TerawattDayPerTonne, "TWd/t")] + [InlineData("en-US", SpecificEnergyUnit.WattDayPerKilogram, "Wd/kg")] + [InlineData("en-US", SpecificEnergyUnit.WattDayPerShortTon, "Wd/ST")] + [InlineData("en-US", SpecificEnergyUnit.WattDayPerTonne, "Wd/t")] + [InlineData("en-US", SpecificEnergyUnit.WattHourPerKilogram, "Wh/kg")] + [InlineData("en-US", SpecificEnergyUnit.WattHourPerPound, "Wh/lbs")] + public void GetAbbreviationForCulture(string culture, SpecificEnergyUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = SpecificEnergy.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(SpecificEnergy.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = SpecificEnergy.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(SpecificEnergyUnit unit) @@ -1293,6 +1039,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); }); } @@ -1316,61 +1063,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] @@ -1416,8 +1165,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); @@ -1454,23 +1201,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = SpecificEnergy.FromJoulesPerKilogram(1); - Assert.True(v.Equals(SpecificEnergy.FromJoulesPerKilogram(1), JoulesPerKilogramTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(SpecificEnergy.Zero, JoulesPerKilogramTolerance, ComparisonType.Relative)); - Assert.True(SpecificEnergy.FromJoulesPerKilogram(100).Equals(SpecificEnergy.FromJoulesPerKilogram(120), 0.3, ComparisonType.Relative)); - Assert.False(SpecificEnergy.FromJoulesPerKilogram(100).Equals(SpecificEnergy.FromJoulesPerKilogram(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = SpecificEnergy.FromJoulesPerKilogram(1); - Assert.Throws(() => v.Equals(SpecificEnergy.FromJoulesPerKilogram(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1485,6 +1215,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(jouleperkilogram.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = SpecificEnergy.FromJoulesPerKilogram(1); + var negativeTolerance = SpecificEnergy.FromJoulesPerKilogram(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1501,6 +1257,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() { @@ -1617,158 +1385,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(SpecificEnergy))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(SpecificEnergyUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal(SpecificEnergy.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal(SpecificEnergy.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal(new {SpecificEnergy.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 368c4bc32d..b9832408bb 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEntropyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEntropyTestsBase.g.cs @@ -128,7 +128,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new SpecificEntropy(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -141,15 +141,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void SpecificEntropy_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + SpecificEntropyUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new SpecificEntropy(1, SpecificEntropyUnit.JoulePerKilogramKelvin); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(SpecificEntropy.Zero, quantityInfo.Zero); Assert.Equal("SpecificEntropy", quantityInfo.Name); + Assert.Equal(SpecificEntropy.Zero, quantityInfo.Zero); + Assert.Equal(SpecificEntropy.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(SpecificEntropy.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -171,39 +189,39 @@ public void JoulePerKilogramKelvinToSpecificEntropyUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = SpecificEntropy.From(1, SpecificEntropyUnit.BtuPerPoundFahrenheit); - AssertEx.EqualTolerance(1, quantity00.BtusPerPoundFahrenheit, BtusPerPoundFahrenheitTolerance); + Assert.Equal(1, quantity00.BtusPerPoundFahrenheit); Assert.Equal(SpecificEntropyUnit.BtuPerPoundFahrenheit, quantity00.Unit); var quantity01 = SpecificEntropy.From(1, SpecificEntropyUnit.CaloriePerGramKelvin); - AssertEx.EqualTolerance(1, quantity01.CaloriesPerGramKelvin, CaloriesPerGramKelvinTolerance); + Assert.Equal(1, quantity01.CaloriesPerGramKelvin); Assert.Equal(SpecificEntropyUnit.CaloriePerGramKelvin, quantity01.Unit); var quantity02 = SpecificEntropy.From(1, SpecificEntropyUnit.JoulePerKilogramDegreeCelsius); - AssertEx.EqualTolerance(1, quantity02.JoulesPerKilogramDegreeCelsius, JoulesPerKilogramDegreeCelsiusTolerance); + Assert.Equal(1, quantity02.JoulesPerKilogramDegreeCelsius); Assert.Equal(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius, quantity02.Unit); var quantity03 = SpecificEntropy.From(1, SpecificEntropyUnit.JoulePerKilogramKelvin); - AssertEx.EqualTolerance(1, quantity03.JoulesPerKilogramKelvin, JoulesPerKilogramKelvinTolerance); + Assert.Equal(1, quantity03.JoulesPerKilogramKelvin); Assert.Equal(SpecificEntropyUnit.JoulePerKilogramKelvin, quantity03.Unit); var quantity04 = SpecificEntropy.From(1, SpecificEntropyUnit.KilocaloriePerGramKelvin); - AssertEx.EqualTolerance(1, quantity04.KilocaloriesPerGramKelvin, KilocaloriesPerGramKelvinTolerance); + Assert.Equal(1, quantity04.KilocaloriesPerGramKelvin); Assert.Equal(SpecificEntropyUnit.KilocaloriePerGramKelvin, quantity04.Unit); var quantity05 = SpecificEntropy.From(1, SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius); - AssertEx.EqualTolerance(1, quantity05.KilojoulesPerKilogramDegreeCelsius, KilojoulesPerKilogramDegreeCelsiusTolerance); + Assert.Equal(1, quantity05.KilojoulesPerKilogramDegreeCelsius); Assert.Equal(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius, quantity05.Unit); var quantity06 = SpecificEntropy.From(1, SpecificEntropyUnit.KilojoulePerKilogramKelvin); - AssertEx.EqualTolerance(1, quantity06.KilojoulesPerKilogramKelvin, KilojoulesPerKilogramKelvinTolerance); + Assert.Equal(1, quantity06.KilojoulesPerKilogramKelvin); Assert.Equal(SpecificEntropyUnit.KilojoulePerKilogramKelvin, quantity06.Unit); var quantity07 = SpecificEntropy.From(1, SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius); - AssertEx.EqualTolerance(1, quantity07.MegajoulesPerKilogramDegreeCelsius, MegajoulesPerKilogramDegreeCelsiusTolerance); + Assert.Equal(1, quantity07.MegajoulesPerKilogramDegreeCelsius); Assert.Equal(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius, quantity07.Unit); var quantity08 = SpecificEntropy.From(1, SpecificEntropyUnit.MegajoulePerKilogramKelvin); - AssertEx.EqualTolerance(1, quantity08.MegajoulesPerKilogramKelvin, MegajoulesPerKilogramKelvinTolerance); + Assert.Equal(1, quantity08.MegajoulesPerKilogramKelvin); Assert.Equal(SpecificEntropyUnit.MegajoulePerKilogramKelvin, quantity08.Unit); } @@ -347,144 +365,42 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 BTU/(lb·°F)", SpecificEntropyUnit.BtuPerPoundFahrenheit, 4.2)] + [InlineData("en-US", "4.2 BTU/(lbm·°F)", SpecificEntropyUnit.BtuPerPoundFahrenheit, 4.2)] + [InlineData("en-US", "4.2 cal/g·K", SpecificEntropyUnit.CaloriePerGramKelvin, 4.2)] + [InlineData("en-US", "4.2 J/kg·°C", SpecificEntropyUnit.JoulePerKilogramDegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 J/kg·K", SpecificEntropyUnit.JoulePerKilogramKelvin, 4.2)] + [InlineData("en-US", "4.2 kcal/g·K", SpecificEntropyUnit.KilocaloriePerGramKelvin, 4.2)] + [InlineData("en-US", "4.2 kJ/kg·°C", SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = SpecificEntropy.Parse("1 BTU/(lb·°F)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.BtusPerPoundFahrenheit, BtusPerPoundFahrenheitTolerance); - Assert.Equal(SpecificEntropyUnit.BtuPerPoundFahrenheit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEntropy.Parse("1 BTU/(lbm·°F)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.BtusPerPoundFahrenheit, BtusPerPoundFahrenheitTolerance); - Assert.Equal(SpecificEntropyUnit.BtuPerPoundFahrenheit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEntropy.Parse("1 cal/g·K", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CaloriesPerGramKelvin, CaloriesPerGramKelvinTolerance); - Assert.Equal(SpecificEntropyUnit.CaloriePerGramKelvin, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEntropy.Parse("1 J/kg·°C", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.JoulesPerKilogramDegreeCelsius, JoulesPerKilogramDegreeCelsiusTolerance); - Assert.Equal(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEntropy.Parse("1 J/kg·K", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.JoulesPerKilogramKelvin, JoulesPerKilogramKelvinTolerance); - Assert.Equal(SpecificEntropyUnit.JoulePerKilogramKelvin, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEntropy.Parse("1 kcal/g·K", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilocaloriesPerGramKelvin, KilocaloriesPerGramKelvinTolerance); - Assert.Equal(SpecificEntropyUnit.KilocaloriePerGramKelvin, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEntropy.Parse("1 kJ/kg·°C", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilojoulesPerKilogramDegreeCelsius, KilojoulesPerKilogramDegreeCelsiusTolerance); - Assert.Equal(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEntropy.Parse("1 kJ/kg·K", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilojoulesPerKilogramKelvin, KilojoulesPerKilogramKelvinTolerance); - Assert.Equal(SpecificEntropyUnit.KilojoulePerKilogramKelvin, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEntropy.Parse("1 MJ/kg·°C", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegajoulesPerKilogramDegreeCelsius, MegajoulesPerKilogramDegreeCelsiusTolerance); - Assert.Equal(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificEntropy.Parse("1 MJ/kg·K", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegajoulesPerKilogramKelvin, MegajoulesPerKilogramKelvinTolerance); - Assert.Equal(SpecificEntropyUnit.MegajoulePerKilogramKelvin, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = SpecificEntropy.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 BTU/(lb·°F)", SpecificEntropyUnit.BtuPerPoundFahrenheit, 4.2)] + [InlineData("en-US", "4.2 BTU/(lbm·°F)", SpecificEntropyUnit.BtuPerPoundFahrenheit, 4.2)] + [InlineData("en-US", "4.2 cal/g·K", SpecificEntropyUnit.CaloriePerGramKelvin, 4.2)] + [InlineData("en-US", "4.2 J/kg·°C", SpecificEntropyUnit.JoulePerKilogramDegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 J/kg·K", SpecificEntropyUnit.JoulePerKilogramKelvin, 4.2)] + [InlineData("en-US", "4.2 kcal/g·K", SpecificEntropyUnit.KilocaloriePerGramKelvin, 4.2)] + [InlineData("en-US", "4.2 kJ/kg·°C", SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(SpecificEntropy.TryParse("1 BTU/(lb·°F)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BtusPerPoundFahrenheit, BtusPerPoundFahrenheitTolerance); - Assert.Equal(SpecificEntropyUnit.BtuPerPoundFahrenheit, parsed.Unit); - } - - { - Assert.True(SpecificEntropy.TryParse("1 BTU/(lbm·°F)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BtusPerPoundFahrenheit, BtusPerPoundFahrenheitTolerance); - Assert.Equal(SpecificEntropyUnit.BtuPerPoundFahrenheit, parsed.Unit); - } - - { - Assert.True(SpecificEntropy.TryParse("1 cal/g·K", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CaloriesPerGramKelvin, CaloriesPerGramKelvinTolerance); - Assert.Equal(SpecificEntropyUnit.CaloriePerGramKelvin, parsed.Unit); - } - - { - Assert.True(SpecificEntropy.TryParse("1 J/kg·°C", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.JoulesPerKilogramDegreeCelsius, JoulesPerKilogramDegreeCelsiusTolerance); - Assert.Equal(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius, parsed.Unit); - } - - { - Assert.True(SpecificEntropy.TryParse("1 J/kg·K", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.JoulesPerKilogramKelvin, JoulesPerKilogramKelvinTolerance); - Assert.Equal(SpecificEntropyUnit.JoulePerKilogramKelvin, parsed.Unit); - } - - { - Assert.True(SpecificEntropy.TryParse("1 kcal/g·K", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilocaloriesPerGramKelvin, KilocaloriesPerGramKelvinTolerance); - Assert.Equal(SpecificEntropyUnit.KilocaloriePerGramKelvin, parsed.Unit); - } - - { - Assert.True(SpecificEntropy.TryParse("1 kJ/kg·°C", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilojoulesPerKilogramDegreeCelsius, KilojoulesPerKilogramDegreeCelsiusTolerance); - Assert.Equal(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius, parsed.Unit); - } - - { - Assert.True(SpecificEntropy.TryParse("1 kJ/kg·K", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilojoulesPerKilogramKelvin, KilojoulesPerKilogramKelvinTolerance); - Assert.Equal(SpecificEntropyUnit.KilojoulePerKilogramKelvin, parsed.Unit); - } - - { - Assert.True(SpecificEntropy.TryParse("1 MJ/kg·°C", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegajoulesPerKilogramDegreeCelsius, MegajoulesPerKilogramDegreeCelsiusTolerance); - Assert.Equal(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius, parsed.Unit); - } - - { - Assert.True(SpecificEntropy.TryParse("1 MJ/kg·K", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegajoulesPerKilogramKelvin, MegajoulesPerKilogramKelvinTolerance); - Assert.Equal(SpecificEntropyUnit.MegajoulePerKilogramKelvin, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(SpecificEntropy.TryParse(quantityString, out SpecificEntropy parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -633,6 +549,35 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Specif Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", SpecificEntropyUnit.BtuPerPoundFahrenheit, "BTU/(lb·°F)")] + [InlineData("en-US", SpecificEntropyUnit.CaloriePerGramKelvin, "cal/g·K")] + [InlineData("en-US", SpecificEntropyUnit.JoulePerKilogramDegreeCelsius, "J/kg·°C")] + [InlineData("en-US", SpecificEntropyUnit.JoulePerKilogramKelvin, "J/kg·K")] + [InlineData("en-US", SpecificEntropyUnit.KilocaloriePerGramKelvin, "kcal/g·K")] + [InlineData("en-US", SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius, "kJ/kg·°C")] + [InlineData("en-US", SpecificEntropyUnit.KilojoulePerKilogramKelvin, "kJ/kg·K")] + [InlineData("en-US", SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius, "MJ/kg·°C")] + [InlineData("en-US", SpecificEntropyUnit.MegajoulePerKilogramKelvin, "MJ/kg·K")] + public void GetAbbreviationForCulture(string culture, SpecificEntropyUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = SpecificEntropy.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(SpecificEntropy.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = SpecificEntropy.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(SpecificEntropyUnit unit) @@ -663,6 +608,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); }); } @@ -686,40 +632,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] @@ -765,8 +713,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); @@ -804,34 +750,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = SpecificEntropy.FromJoulesPerKilogramKelvin(1); - Assert.True(v.Equals(SpecificEntropy.FromJoulesPerKilogramKelvin(1), JoulesPerKilogramKelvinTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(SpecificEntropy.Zero, JoulesPerKilogramKelvinTolerance, ComparisonType.Relative)); - Assert.True(SpecificEntropy.FromJoulesPerKilogramKelvin(100).Equals(SpecificEntropy.FromJoulesPerKilogramKelvin(120), 0.3, ComparisonType.Relative)); - Assert.False(SpecificEntropy.FromJoulesPerKilogramKelvin(100).Equals(SpecificEntropy.FromJoulesPerKilogramKelvin(120), 0.1, ComparisonType.Relative)); + SpecificEntropy jouleperkilogramkelvin = SpecificEntropy.FromJoulesPerKilogramKelvin(1); + Assert.False(jouleperkilogramkelvin.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = SpecificEntropy.FromJoulesPerKilogramKelvin(1); - Assert.Throws(() => v.Equals(SpecificEntropy.FromJoulesPerKilogramKelvin(1), -1, ComparisonType.Relative)); + SpecificEntropy jouleperkilogramkelvin = SpecificEntropy.FromJoulesPerKilogramKelvin(1); + Assert.False(jouleperkilogramkelvin.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - SpecificEntropy jouleperkilogramkelvin = SpecificEntropy.FromJoulesPerKilogramKelvin(1); - Assert.False(jouleperkilogramkelvin.Equals(new object())); + var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(firstValue); + var otherQuantity = SpecificEntropy.FromJoulesPerKilogramKelvin(secondValue); + SpecificEntropy maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - SpecificEntropy jouleperkilogramkelvin = SpecificEntropy.FromJoulesPerKilogramKelvin(1); - Assert.False(jouleperkilogramkelvin.Equals(null)); + var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1); + var negativeTolerance = SpecificEntropy.FromJoulesPerKilogramKelvin(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -850,6 +805,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() { @@ -924,158 +891,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(SpecificEntropy))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(SpecificEntropyUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal(SpecificEntropy.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal(SpecificEntropy.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal(new {SpecificEntropy.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 30ae2f499b..c3a992781e 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificFuelConsumptionTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificFuelConsumptionTestsBase.g.cs @@ -108,7 +108,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new SpecificFuelConsumption(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -121,15 +121,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void SpecificFuelConsumption_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + SpecificFuelConsumptionUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new SpecificFuelConsumption(1, SpecificFuelConsumptionUnit.GramPerKilonewtonSecond); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(SpecificFuelConsumption.Zero, quantityInfo.Zero); Assert.Equal("SpecificFuelConsumption", quantityInfo.Name); + Assert.Equal(SpecificFuelConsumption.Zero, quantityInfo.Zero); + Assert.Equal(SpecificFuelConsumption.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(SpecificFuelConsumption.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void SpecificFuelConsumptionInfo_CreateWithCustomUnitInfos() + { + SpecificFuelConsumptionUnit[] expectedUnits = [SpecificFuelConsumptionUnit.GramPerKilonewtonSecond]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -146,19 +164,19 @@ public void GramPerKilonewtonSecondToSpecificFuelConsumptionUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = SpecificFuelConsumption.From(1, SpecificFuelConsumptionUnit.GramPerKilonewtonSecond); - AssertEx.EqualTolerance(1, quantity00.GramsPerKilonewtonSecond, GramsPerKilonewtonSecondTolerance); + Assert.Equal(1, quantity00.GramsPerKilonewtonSecond); Assert.Equal(SpecificFuelConsumptionUnit.GramPerKilonewtonSecond, quantity00.Unit); var quantity01 = SpecificFuelConsumption.From(1, SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour); - AssertEx.EqualTolerance(1, quantity01.KilogramsPerKilogramForceHour, KilogramsPerKilogramForceHourTolerance); + Assert.Equal(1, quantity01.KilogramsPerKilogramForceHour); Assert.Equal(SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, quantity01.Unit); var quantity02 = SpecificFuelConsumption.From(1, SpecificFuelConsumptionUnit.KilogramPerKilonewtonSecond); - AssertEx.EqualTolerance(1, quantity02.KilogramsPerKilonewtonSecond, KilogramsPerKilonewtonSecondTolerance); + Assert.Equal(1, quantity02.KilogramsPerKilonewtonSecond); Assert.Equal(SpecificFuelConsumptionUnit.KilogramPerKilonewtonSecond, quantity02.Unit); var quantity03 = SpecificFuelConsumption.From(1, SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour); - AssertEx.EqualTolerance(1, quantity03.PoundsMassPerPoundForceHour, PoundsMassPerPoundForceHourTolerance); + Assert.Equal(1, quantity03.PoundsMassPerPoundForceHour); Assert.Equal(SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour, quantity03.Unit); } @@ -297,66 +315,30 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 g/(kN·s)", SpecificFuelConsumptionUnit.GramPerKilonewtonSecond, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = SpecificFuelConsumption.Parse("1 g/(kN·s)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramsPerKilonewtonSecond, GramsPerKilonewtonSecondTolerance); - Assert.Equal(SpecificFuelConsumptionUnit.GramPerKilonewtonSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificFuelConsumption.Parse("1 kg/(kgf·h)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerKilogramForceHour, KilogramsPerKilogramForceHourTolerance); - Assert.Equal(SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificFuelConsumption.Parse("1 kg/(kN·s)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsPerKilonewtonSecond, KilogramsPerKilonewtonSecondTolerance); - Assert.Equal(SpecificFuelConsumptionUnit.KilogramPerKilonewtonSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificFuelConsumption.Parse("1 lb/(lbf·h)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsMassPerPoundForceHour, PoundsMassPerPoundForceHourTolerance); - Assert.Equal(SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = SpecificFuelConsumption.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 g/(kN·s)", SpecificFuelConsumptionUnit.GramPerKilonewtonSecond, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(SpecificFuelConsumption.TryParse("1 g/(kN·s)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramsPerKilonewtonSecond, GramsPerKilonewtonSecondTolerance); - Assert.Equal(SpecificFuelConsumptionUnit.GramPerKilonewtonSecond, parsed.Unit); - } - - { - Assert.True(SpecificFuelConsumption.TryParse("1 kg/(kgf·h)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerKilogramForceHour, KilogramsPerKilogramForceHourTolerance); - Assert.Equal(SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, parsed.Unit); - } - - { - Assert.True(SpecificFuelConsumption.TryParse("1 kg/(kN·s)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsPerKilonewtonSecond, KilogramsPerKilonewtonSecondTolerance); - Assert.Equal(SpecificFuelConsumptionUnit.KilogramPerKilonewtonSecond, parsed.Unit); - } - - { - Assert.True(SpecificFuelConsumption.TryParse("1 lb/(lbf·h)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsMassPerPoundForceHour, PoundsMassPerPoundForceHourTolerance); - Assert.Equal(SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(SpecificFuelConsumption.TryParse(quantityString, out SpecificFuelConsumption parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -457,6 +439,30 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Specif Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", SpecificFuelConsumptionUnit.GramPerKilonewtonSecond, "g/(kN·s)")] + [InlineData("en-US", SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, "kg/(kgf·h)")] + [InlineData("en-US", SpecificFuelConsumptionUnit.KilogramPerKilonewtonSecond, "kg/(kN·s)")] + [InlineData("en-US", SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour, "lb/(lbf·h)")] + public void GetAbbreviationForCulture(string culture, SpecificFuelConsumptionUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = SpecificFuelConsumption.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(SpecificFuelConsumption.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = SpecificFuelConsumption.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(SpecificFuelConsumptionUnit unit) @@ -487,6 +493,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); }); } @@ -510,35 +517,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] @@ -584,8 +593,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); @@ -623,34 +630,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1); - Assert.True(v.Equals(SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1), GramsPerKilonewtonSecondTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(SpecificFuelConsumption.Zero, GramsPerKilonewtonSecondTolerance, ComparisonType.Relative)); - Assert.True(SpecificFuelConsumption.FromGramsPerKilonewtonSecond(100).Equals(SpecificFuelConsumption.FromGramsPerKilonewtonSecond(120), 0.3, ComparisonType.Relative)); - Assert.False(SpecificFuelConsumption.FromGramsPerKilonewtonSecond(100).Equals(SpecificFuelConsumption.FromGramsPerKilonewtonSecond(120), 0.1, ComparisonType.Relative)); + SpecificFuelConsumption gramperkilonewtonsecond = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1); + Assert.False(gramperkilonewtonsecond.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1); - Assert.Throws(() => v.Equals(SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1), -1, ComparisonType.Relative)); + SpecificFuelConsumption gramperkilonewtonsecond = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1); + Assert.False(gramperkilonewtonsecond.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - SpecificFuelConsumption gramperkilonewtonsecond = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1); - Assert.False(gramperkilonewtonsecond.Equals(new object())); + var quantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(firstValue); + var otherQuantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(secondValue); + SpecificFuelConsumption maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - SpecificFuelConsumption gramperkilonewtonsecond = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1); - Assert.False(gramperkilonewtonsecond.Equals(null)); + var quantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1); + var negativeTolerance = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -669,6 +685,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() { @@ -733,158 +761,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(SpecificFuelConsumption))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(SpecificFuelConsumptionUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1.0); - Assert.Equal(SpecificFuelConsumption.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1.0); - Assert.Equal(SpecificFuelConsumption.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1.0); - Assert.Equal(new {SpecificFuelConsumption.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 735297fd1a..9ea9fa70c7 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificVolumeTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificVolumeTestsBase.g.cs @@ -104,7 +104,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new SpecificVolume(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -117,15 +117,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void SpecificVolume_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + SpecificVolumeUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new SpecificVolume(1, SpecificVolumeUnit.CubicMeterPerKilogram); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(SpecificVolume.Zero, quantityInfo.Zero); Assert.Equal("SpecificVolume", quantityInfo.Name); + Assert.Equal(SpecificVolume.Zero, quantityInfo.Zero); + Assert.Equal(SpecificVolume.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(SpecificVolume.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void SpecificVolumeInfo_CreateWithCustomUnitInfos() + { + SpecificVolumeUnit[] expectedUnits = [SpecificVolumeUnit.CubicMeterPerKilogram]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -141,15 +159,15 @@ public void CubicMeterPerKilogramToSpecificVolumeUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = SpecificVolume.From(1, SpecificVolumeUnit.CubicFootPerPound); - AssertEx.EqualTolerance(1, quantity00.CubicFeetPerPound, CubicFeetPerPoundTolerance); + Assert.Equal(1, quantity00.CubicFeetPerPound); Assert.Equal(SpecificVolumeUnit.CubicFootPerPound, quantity00.Unit); var quantity01 = SpecificVolume.From(1, SpecificVolumeUnit.CubicMeterPerKilogram); - AssertEx.EqualTolerance(1, quantity01.CubicMetersPerKilogram, CubicMetersPerKilogramTolerance); + Assert.Equal(1, quantity01.CubicMetersPerKilogram); Assert.Equal(SpecificVolumeUnit.CubicMeterPerKilogram, quantity01.Unit); var quantity02 = SpecificVolume.From(1, SpecificVolumeUnit.MillicubicMeterPerKilogram); - AssertEx.EqualTolerance(1, quantity02.MillicubicMetersPerKilogram, MillicubicMetersPerKilogramTolerance); + Assert.Equal(1, quantity02.MillicubicMetersPerKilogram); Assert.Equal(SpecificVolumeUnit.MillicubicMeterPerKilogram, quantity02.Unit); } @@ -287,53 +305,28 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [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, decimal expectedValue) { - try - { - var parsed = SpecificVolume.Parse("1 ft³/lb", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicFeetPerPound, CubicFeetPerPoundTolerance); - Assert.Equal(SpecificVolumeUnit.CubicFootPerPound, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificVolume.Parse("1 m³/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicMetersPerKilogram, CubicMetersPerKilogramTolerance); - Assert.Equal(SpecificVolumeUnit.CubicMeterPerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificVolume.Parse("1 mm³/kg", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillicubicMetersPerKilogram, MillicubicMetersPerKilogramTolerance); - Assert.Equal(SpecificVolumeUnit.MillicubicMeterPerKilogram, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = SpecificVolume.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [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, decimal expectedValue) { - { - Assert.True(SpecificVolume.TryParse("1 ft³/lb", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicFeetPerPound, CubicFeetPerPoundTolerance); - Assert.Equal(SpecificVolumeUnit.CubicFootPerPound, parsed.Unit); - } - - { - Assert.True(SpecificVolume.TryParse("1 m³/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicMetersPerKilogram, CubicMetersPerKilogramTolerance); - Assert.Equal(SpecificVolumeUnit.CubicMeterPerKilogram, parsed.Unit); - } - - { - Assert.True(SpecificVolume.TryParse("1 mm³/kg", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillicubicMetersPerKilogram, MillicubicMetersPerKilogramTolerance); - Assert.Equal(SpecificVolumeUnit.MillicubicMeterPerKilogram, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(SpecificVolume.TryParse(quantityString, out SpecificVolume parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -426,6 +419,29 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Specif Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", SpecificVolumeUnit.CubicFootPerPound, "ft³/lb")] + [InlineData("en-US", SpecificVolumeUnit.CubicMeterPerKilogram, "m³/kg")] + [InlineData("en-US", SpecificVolumeUnit.MillicubicMeterPerKilogram, "mm³/kg")] + public void GetAbbreviationForCulture(string culture, SpecificVolumeUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = SpecificVolume.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(SpecificVolume.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = SpecificVolume.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(SpecificVolumeUnit unit) @@ -456,6 +472,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); }); } @@ -479,34 +496,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] @@ -552,8 +571,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); @@ -591,34 +608,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = SpecificVolume.FromCubicMetersPerKilogram(1); - Assert.True(v.Equals(SpecificVolume.FromCubicMetersPerKilogram(1), CubicMetersPerKilogramTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(SpecificVolume.Zero, CubicMetersPerKilogramTolerance, ComparisonType.Relative)); - Assert.True(SpecificVolume.FromCubicMetersPerKilogram(100).Equals(SpecificVolume.FromCubicMetersPerKilogram(120), 0.3, ComparisonType.Relative)); - Assert.False(SpecificVolume.FromCubicMetersPerKilogram(100).Equals(SpecificVolume.FromCubicMetersPerKilogram(120), 0.1, ComparisonType.Relative)); + SpecificVolume cubicmeterperkilogram = SpecificVolume.FromCubicMetersPerKilogram(1); + Assert.False(cubicmeterperkilogram.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = SpecificVolume.FromCubicMetersPerKilogram(1); - Assert.Throws(() => v.Equals(SpecificVolume.FromCubicMetersPerKilogram(1), -1, ComparisonType.Relative)); + SpecificVolume cubicmeterperkilogram = SpecificVolume.FromCubicMetersPerKilogram(1); + Assert.False(cubicmeterperkilogram.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - SpecificVolume cubicmeterperkilogram = SpecificVolume.FromCubicMetersPerKilogram(1); - Assert.False(cubicmeterperkilogram.Equals(new object())); + var quantity = SpecificVolume.FromCubicMetersPerKilogram(firstValue); + var otherQuantity = SpecificVolume.FromCubicMetersPerKilogram(secondValue); + SpecificVolume maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - SpecificVolume cubicmeterperkilogram = SpecificVolume.FromCubicMetersPerKilogram(1); - Assert.False(cubicmeterperkilogram.Equals(null)); + var quantity = SpecificVolume.FromCubicMetersPerKilogram(1); + var negativeTolerance = SpecificVolume.FromCubicMetersPerKilogram(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -637,6 +663,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() { @@ -699,158 +737,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(SpecificVolume))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(SpecificVolumeUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal(SpecificVolume.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal(SpecificVolume.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal(new {SpecificVolume.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 b116e63d42..95ca6afe8b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificWeightTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificWeightTestsBase.g.cs @@ -160,7 +160,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new SpecificWeight(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -173,15 +173,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void SpecificWeight_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + SpecificWeightUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new SpecificWeight(1, SpecificWeightUnit.NewtonPerCubicMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(SpecificWeight.Zero, quantityInfo.Zero); Assert.Equal("SpecificWeight", quantityInfo.Name); + Assert.Equal(SpecificWeight.Zero, quantityInfo.Zero); + Assert.Equal(SpecificWeight.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(SpecificWeight.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void SpecificWeightInfo_CreateWithCustomUnitInfos() + { + SpecificWeightUnit[] expectedUnits = [SpecificWeightUnit.NewtonPerCubicMeter]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -211,71 +229,71 @@ public void NewtonPerCubicMeterToSpecificWeightUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = SpecificWeight.From(1, SpecificWeightUnit.KilogramForcePerCubicCentimeter); - AssertEx.EqualTolerance(1, quantity00.KilogramsForcePerCubicCentimeter, KilogramsForcePerCubicCentimeterTolerance); + Assert.Equal(1, quantity00.KilogramsForcePerCubicCentimeter); Assert.Equal(SpecificWeightUnit.KilogramForcePerCubicCentimeter, quantity00.Unit); var quantity01 = SpecificWeight.From(1, SpecificWeightUnit.KilogramForcePerCubicMeter); - AssertEx.EqualTolerance(1, quantity01.KilogramsForcePerCubicMeter, KilogramsForcePerCubicMeterTolerance); + Assert.Equal(1, quantity01.KilogramsForcePerCubicMeter); Assert.Equal(SpecificWeightUnit.KilogramForcePerCubicMeter, quantity01.Unit); var quantity02 = SpecificWeight.From(1, SpecificWeightUnit.KilogramForcePerCubicMillimeter); - AssertEx.EqualTolerance(1, quantity02.KilogramsForcePerCubicMillimeter, KilogramsForcePerCubicMillimeterTolerance); + Assert.Equal(1, quantity02.KilogramsForcePerCubicMillimeter); Assert.Equal(SpecificWeightUnit.KilogramForcePerCubicMillimeter, quantity02.Unit); var quantity03 = SpecificWeight.From(1, SpecificWeightUnit.KilonewtonPerCubicCentimeter); - AssertEx.EqualTolerance(1, quantity03.KilonewtonsPerCubicCentimeter, KilonewtonsPerCubicCentimeterTolerance); + Assert.Equal(1, quantity03.KilonewtonsPerCubicCentimeter); Assert.Equal(SpecificWeightUnit.KilonewtonPerCubicCentimeter, quantity03.Unit); var quantity04 = SpecificWeight.From(1, SpecificWeightUnit.KilonewtonPerCubicMeter); - AssertEx.EqualTolerance(1, quantity04.KilonewtonsPerCubicMeter, KilonewtonsPerCubicMeterTolerance); + Assert.Equal(1, quantity04.KilonewtonsPerCubicMeter); Assert.Equal(SpecificWeightUnit.KilonewtonPerCubicMeter, quantity04.Unit); var quantity05 = SpecificWeight.From(1, SpecificWeightUnit.KilonewtonPerCubicMillimeter); - AssertEx.EqualTolerance(1, quantity05.KilonewtonsPerCubicMillimeter, KilonewtonsPerCubicMillimeterTolerance); + Assert.Equal(1, quantity05.KilonewtonsPerCubicMillimeter); Assert.Equal(SpecificWeightUnit.KilonewtonPerCubicMillimeter, quantity05.Unit); var quantity06 = SpecificWeight.From(1, SpecificWeightUnit.KilopoundForcePerCubicFoot); - AssertEx.EqualTolerance(1, quantity06.KilopoundsForcePerCubicFoot, KilopoundsForcePerCubicFootTolerance); + Assert.Equal(1, quantity06.KilopoundsForcePerCubicFoot); Assert.Equal(SpecificWeightUnit.KilopoundForcePerCubicFoot, quantity06.Unit); var quantity07 = SpecificWeight.From(1, SpecificWeightUnit.KilopoundForcePerCubicInch); - AssertEx.EqualTolerance(1, quantity07.KilopoundsForcePerCubicInch, KilopoundsForcePerCubicInchTolerance); + Assert.Equal(1, quantity07.KilopoundsForcePerCubicInch); Assert.Equal(SpecificWeightUnit.KilopoundForcePerCubicInch, quantity07.Unit); var quantity08 = SpecificWeight.From(1, SpecificWeightUnit.MeganewtonPerCubicMeter); - AssertEx.EqualTolerance(1, quantity08.MeganewtonsPerCubicMeter, MeganewtonsPerCubicMeterTolerance); + Assert.Equal(1, quantity08.MeganewtonsPerCubicMeter); Assert.Equal(SpecificWeightUnit.MeganewtonPerCubicMeter, quantity08.Unit); var quantity09 = SpecificWeight.From(1, SpecificWeightUnit.NewtonPerCubicCentimeter); - AssertEx.EqualTolerance(1, quantity09.NewtonsPerCubicCentimeter, NewtonsPerCubicCentimeterTolerance); + Assert.Equal(1, quantity09.NewtonsPerCubicCentimeter); Assert.Equal(SpecificWeightUnit.NewtonPerCubicCentimeter, quantity09.Unit); var quantity10 = SpecificWeight.From(1, SpecificWeightUnit.NewtonPerCubicMeter); - AssertEx.EqualTolerance(1, quantity10.NewtonsPerCubicMeter, NewtonsPerCubicMeterTolerance); + Assert.Equal(1, quantity10.NewtonsPerCubicMeter); Assert.Equal(SpecificWeightUnit.NewtonPerCubicMeter, quantity10.Unit); var quantity11 = SpecificWeight.From(1, SpecificWeightUnit.NewtonPerCubicMillimeter); - AssertEx.EqualTolerance(1, quantity11.NewtonsPerCubicMillimeter, NewtonsPerCubicMillimeterTolerance); + Assert.Equal(1, quantity11.NewtonsPerCubicMillimeter); Assert.Equal(SpecificWeightUnit.NewtonPerCubicMillimeter, quantity11.Unit); var quantity12 = SpecificWeight.From(1, SpecificWeightUnit.PoundForcePerCubicFoot); - AssertEx.EqualTolerance(1, quantity12.PoundsForcePerCubicFoot, PoundsForcePerCubicFootTolerance); + Assert.Equal(1, quantity12.PoundsForcePerCubicFoot); Assert.Equal(SpecificWeightUnit.PoundForcePerCubicFoot, quantity12.Unit); var quantity13 = SpecificWeight.From(1, SpecificWeightUnit.PoundForcePerCubicInch); - AssertEx.EqualTolerance(1, quantity13.PoundsForcePerCubicInch, PoundsForcePerCubicInchTolerance); + Assert.Equal(1, quantity13.PoundsForcePerCubicInch); Assert.Equal(SpecificWeightUnit.PoundForcePerCubicInch, quantity13.Unit); var quantity14 = SpecificWeight.From(1, SpecificWeightUnit.TonneForcePerCubicCentimeter); - AssertEx.EqualTolerance(1, quantity14.TonnesForcePerCubicCentimeter, TonnesForcePerCubicCentimeterTolerance); + Assert.Equal(1, quantity14.TonnesForcePerCubicCentimeter); Assert.Equal(SpecificWeightUnit.TonneForcePerCubicCentimeter, quantity14.Unit); var quantity15 = SpecificWeight.From(1, SpecificWeightUnit.TonneForcePerCubicMeter); - AssertEx.EqualTolerance(1, quantity15.TonnesForcePerCubicMeter, TonnesForcePerCubicMeterTolerance); + Assert.Equal(1, quantity15.TonnesForcePerCubicMeter); Assert.Equal(SpecificWeightUnit.TonneForcePerCubicMeter, quantity15.Unit); var quantity16 = SpecificWeight.From(1, SpecificWeightUnit.TonneForcePerCubicMillimeter); - AssertEx.EqualTolerance(1, quantity16.TonnesForcePerCubicMillimeter, TonnesForcePerCubicMillimeterTolerance); + Assert.Equal(1, quantity16.TonnesForcePerCubicMillimeter); Assert.Equal(SpecificWeightUnit.TonneForcePerCubicMillimeter, quantity16.Unit); } @@ -427,235 +445,56 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 kgf/cm³", SpecificWeightUnit.KilogramForcePerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 kgf/m³", SpecificWeightUnit.KilogramForcePerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 kgf/mm³", SpecificWeightUnit.KilogramForcePerCubicMillimeter, 4.2)] + [InlineData("en-US", "4.2 kN/cm³", SpecificWeightUnit.KilonewtonPerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 kN/m³", SpecificWeightUnit.KilonewtonPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 kN/mm³", SpecificWeightUnit.KilonewtonPerCubicMillimeter, 4.2)] + [InlineData("en-US", "4.2 kipf/ft³", SpecificWeightUnit.KilopoundForcePerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 kipf/in³", SpecificWeightUnit.KilopoundForcePerCubicInch, 4.2)] + [InlineData("en-US", "4.2 MN/m³", SpecificWeightUnit.MeganewtonPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 N/cm³", SpecificWeightUnit.NewtonPerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 N/m³", SpecificWeightUnit.NewtonPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 N/mm³", SpecificWeightUnit.NewtonPerCubicMillimeter, 4.2)] + [InlineData("en-US", "4.2 lbf/ft³", SpecificWeightUnit.PoundForcePerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 lbf/in³", SpecificWeightUnit.PoundForcePerCubicInch, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = SpecificWeight.Parse("1 kgf/cm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerCubicCentimeter, KilogramsForcePerCubicCentimeterTolerance); - Assert.Equal(SpecificWeightUnit.KilogramForcePerCubicCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificWeight.Parse("1 kgf/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerCubicMeter, KilogramsForcePerCubicMeterTolerance); - Assert.Equal(SpecificWeightUnit.KilogramForcePerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificWeight.Parse("1 kgf/mm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerCubicMillimeter, KilogramsForcePerCubicMillimeterTolerance); - Assert.Equal(SpecificWeightUnit.KilogramForcePerCubicMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificWeight.Parse("1 kN/cm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerCubicCentimeter, KilonewtonsPerCubicCentimeterTolerance); - Assert.Equal(SpecificWeightUnit.KilonewtonPerCubicCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificWeight.Parse("1 kN/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerCubicMeter, KilonewtonsPerCubicMeterTolerance); - Assert.Equal(SpecificWeightUnit.KilonewtonPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificWeight.Parse("1 kN/mm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerCubicMillimeter, KilonewtonsPerCubicMillimeterTolerance); - Assert.Equal(SpecificWeightUnit.KilonewtonPerCubicMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificWeight.Parse("1 kipf/ft³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerCubicFoot, KilopoundsForcePerCubicFootTolerance); - Assert.Equal(SpecificWeightUnit.KilopoundForcePerCubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificWeight.Parse("1 kipf/in³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerCubicInch, KilopoundsForcePerCubicInchTolerance); - Assert.Equal(SpecificWeightUnit.KilopoundForcePerCubicInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificWeight.Parse("1 MN/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MeganewtonsPerCubicMeter, MeganewtonsPerCubicMeterTolerance); - Assert.Equal(SpecificWeightUnit.MeganewtonPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificWeight.Parse("1 N/cm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonsPerCubicCentimeter, NewtonsPerCubicCentimeterTolerance); - Assert.Equal(SpecificWeightUnit.NewtonPerCubicCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificWeight.Parse("1 N/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonsPerCubicMeter, NewtonsPerCubicMeterTolerance); - Assert.Equal(SpecificWeightUnit.NewtonPerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificWeight.Parse("1 N/mm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonsPerCubicMillimeter, NewtonsPerCubicMillimeterTolerance); - Assert.Equal(SpecificWeightUnit.NewtonPerCubicMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificWeight.Parse("1 lbf/ft³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerCubicFoot, PoundsForcePerCubicFootTolerance); - Assert.Equal(SpecificWeightUnit.PoundForcePerCubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificWeight.Parse("1 lbf/in³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerCubicInch, PoundsForcePerCubicInchTolerance); - Assert.Equal(SpecificWeightUnit.PoundForcePerCubicInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificWeight.Parse("1 tf/cm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonnesForcePerCubicCentimeter, TonnesForcePerCubicCentimeterTolerance); - Assert.Equal(SpecificWeightUnit.TonneForcePerCubicCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificWeight.Parse("1 tf/m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonnesForcePerCubicMeter, TonnesForcePerCubicMeterTolerance); - Assert.Equal(SpecificWeightUnit.TonneForcePerCubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = SpecificWeight.Parse("1 tf/mm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonnesForcePerCubicMillimeter, TonnesForcePerCubicMillimeterTolerance); - Assert.Equal(SpecificWeightUnit.TonneForcePerCubicMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = SpecificWeight.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 kgf/cm³", SpecificWeightUnit.KilogramForcePerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 kgf/m³", SpecificWeightUnit.KilogramForcePerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 kgf/mm³", SpecificWeightUnit.KilogramForcePerCubicMillimeter, 4.2)] + [InlineData("en-US", "4.2 kN/cm³", SpecificWeightUnit.KilonewtonPerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 kN/m³", SpecificWeightUnit.KilonewtonPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 kN/mm³", SpecificWeightUnit.KilonewtonPerCubicMillimeter, 4.2)] + [InlineData("en-US", "4.2 kipf/ft³", SpecificWeightUnit.KilopoundForcePerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 kipf/in³", SpecificWeightUnit.KilopoundForcePerCubicInch, 4.2)] + [InlineData("en-US", "4.2 MN/m³", SpecificWeightUnit.MeganewtonPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 N/cm³", SpecificWeightUnit.NewtonPerCubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 N/m³", SpecificWeightUnit.NewtonPerCubicMeter, 4.2)] + [InlineData("en-US", "4.2 N/mm³", SpecificWeightUnit.NewtonPerCubicMillimeter, 4.2)] + [InlineData("en-US", "4.2 lbf/ft³", SpecificWeightUnit.PoundForcePerCubicFoot, 4.2)] + [InlineData("en-US", "4.2 lbf/in³", SpecificWeightUnit.PoundForcePerCubicInch, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(SpecificWeight.TryParse("1 kgf/cm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerCubicCentimeter, KilogramsForcePerCubicCentimeterTolerance); - Assert.Equal(SpecificWeightUnit.KilogramForcePerCubicCentimeter, parsed.Unit); - } - - { - Assert.True(SpecificWeight.TryParse("1 kgf/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerCubicMeter, KilogramsForcePerCubicMeterTolerance); - Assert.Equal(SpecificWeightUnit.KilogramForcePerCubicMeter, parsed.Unit); - } - - { - Assert.True(SpecificWeight.TryParse("1 kgf/mm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramsForcePerCubicMillimeter, KilogramsForcePerCubicMillimeterTolerance); - Assert.Equal(SpecificWeightUnit.KilogramForcePerCubicMillimeter, parsed.Unit); - } - - { - Assert.True(SpecificWeight.TryParse("1 kN/cm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerCubicCentimeter, KilonewtonsPerCubicCentimeterTolerance); - Assert.Equal(SpecificWeightUnit.KilonewtonPerCubicCentimeter, parsed.Unit); - } - - { - Assert.True(SpecificWeight.TryParse("1 kN/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerCubicMeter, KilonewtonsPerCubicMeterTolerance); - Assert.Equal(SpecificWeightUnit.KilonewtonPerCubicMeter, parsed.Unit); - } - - { - Assert.True(SpecificWeight.TryParse("1 kN/mm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonsPerCubicMillimeter, KilonewtonsPerCubicMillimeterTolerance); - Assert.Equal(SpecificWeightUnit.KilonewtonPerCubicMillimeter, parsed.Unit); - } - - { - Assert.True(SpecificWeight.TryParse("1 kipf/ft³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerCubicFoot, KilopoundsForcePerCubicFootTolerance); - Assert.Equal(SpecificWeightUnit.KilopoundForcePerCubicFoot, parsed.Unit); - } - - { - Assert.True(SpecificWeight.TryParse("1 kipf/in³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundsForcePerCubicInch, KilopoundsForcePerCubicInchTolerance); - Assert.Equal(SpecificWeightUnit.KilopoundForcePerCubicInch, parsed.Unit); - } - - { - Assert.True(SpecificWeight.TryParse("1 MN/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MeganewtonsPerCubicMeter, MeganewtonsPerCubicMeterTolerance); - Assert.Equal(SpecificWeightUnit.MeganewtonPerCubicMeter, parsed.Unit); - } - - { - Assert.True(SpecificWeight.TryParse("1 N/cm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonsPerCubicCentimeter, NewtonsPerCubicCentimeterTolerance); - Assert.Equal(SpecificWeightUnit.NewtonPerCubicCentimeter, parsed.Unit); - } - - { - Assert.True(SpecificWeight.TryParse("1 N/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonsPerCubicMeter, NewtonsPerCubicMeterTolerance); - Assert.Equal(SpecificWeightUnit.NewtonPerCubicMeter, parsed.Unit); - } - - { - Assert.True(SpecificWeight.TryParse("1 N/mm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonsPerCubicMillimeter, NewtonsPerCubicMillimeterTolerance); - Assert.Equal(SpecificWeightUnit.NewtonPerCubicMillimeter, parsed.Unit); - } - - { - Assert.True(SpecificWeight.TryParse("1 lbf/ft³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerCubicFoot, PoundsForcePerCubicFootTolerance); - Assert.Equal(SpecificWeightUnit.PoundForcePerCubicFoot, parsed.Unit); - } - - { - Assert.True(SpecificWeight.TryParse("1 lbf/in³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundsForcePerCubicInch, PoundsForcePerCubicInchTolerance); - Assert.Equal(SpecificWeightUnit.PoundForcePerCubicInch, parsed.Unit); - } - - { - Assert.True(SpecificWeight.TryParse("1 tf/cm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonnesForcePerCubicCentimeter, TonnesForcePerCubicCentimeterTolerance); - Assert.Equal(SpecificWeightUnit.TonneForcePerCubicCentimeter, parsed.Unit); - } - - { - Assert.True(SpecificWeight.TryParse("1 tf/m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonnesForcePerCubicMeter, TonnesForcePerCubicMeterTolerance); - Assert.Equal(SpecificWeightUnit.TonneForcePerCubicMeter, parsed.Unit); - } - - { - Assert.True(SpecificWeight.TryParse("1 tf/mm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonnesForcePerCubicMillimeter, TonnesForcePerCubicMillimeterTolerance); - Assert.Equal(SpecificWeightUnit.TonneForcePerCubicMillimeter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(SpecificWeight.TryParse(quantityString, out SpecificWeight parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -860,6 +699,43 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Specif Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", SpecificWeightUnit.KilogramForcePerCubicCentimeter, "kgf/cm³")] + [InlineData("en-US", SpecificWeightUnit.KilogramForcePerCubicMeter, "kgf/m³")] + [InlineData("en-US", SpecificWeightUnit.KilogramForcePerCubicMillimeter, "kgf/mm³")] + [InlineData("en-US", SpecificWeightUnit.KilonewtonPerCubicCentimeter, "kN/cm³")] + [InlineData("en-US", SpecificWeightUnit.KilonewtonPerCubicMeter, "kN/m³")] + [InlineData("en-US", SpecificWeightUnit.KilonewtonPerCubicMillimeter, "kN/mm³")] + [InlineData("en-US", SpecificWeightUnit.KilopoundForcePerCubicFoot, "kipf/ft³")] + [InlineData("en-US", SpecificWeightUnit.KilopoundForcePerCubicInch, "kipf/in³")] + [InlineData("en-US", SpecificWeightUnit.MeganewtonPerCubicMeter, "MN/m³")] + [InlineData("en-US", SpecificWeightUnit.NewtonPerCubicCentimeter, "N/cm³")] + [InlineData("en-US", SpecificWeightUnit.NewtonPerCubicMeter, "N/m³")] + [InlineData("en-US", SpecificWeightUnit.NewtonPerCubicMillimeter, "N/mm³")] + [InlineData("en-US", SpecificWeightUnit.PoundForcePerCubicFoot, "lbf/ft³")] + [InlineData("en-US", SpecificWeightUnit.PoundForcePerCubicInch, "lbf/in³")] + [InlineData("en-US", SpecificWeightUnit.TonneForcePerCubicCentimeter, "tf/cm³")] + [InlineData("en-US", SpecificWeightUnit.TonneForcePerCubicMeter, "tf/m³")] + [InlineData("en-US", SpecificWeightUnit.TonneForcePerCubicMillimeter, "tf/mm³")] + public void GetAbbreviationForCulture(string culture, SpecificWeightUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = SpecificWeight.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(SpecificWeight.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = SpecificWeight.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(SpecificWeightUnit unit) @@ -890,6 +766,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); }); } @@ -913,48 +790,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] @@ -1000,8 +879,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); @@ -1038,23 +915,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = SpecificWeight.FromNewtonsPerCubicMeter(1); - Assert.True(v.Equals(SpecificWeight.FromNewtonsPerCubicMeter(1), NewtonsPerCubicMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(SpecificWeight.Zero, NewtonsPerCubicMeterTolerance, ComparisonType.Relative)); - Assert.True(SpecificWeight.FromNewtonsPerCubicMeter(100).Equals(SpecificWeight.FromNewtonsPerCubicMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(SpecificWeight.FromNewtonsPerCubicMeter(100).Equals(SpecificWeight.FromNewtonsPerCubicMeter(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = SpecificWeight.FromNewtonsPerCubicMeter(1); - Assert.Throws(() => v.Equals(SpecificWeight.FromNewtonsPerCubicMeter(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1069,6 +929,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(newtonpercubicmeter.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1); + var negativeTolerance = SpecificWeight.FromNewtonsPerCubicMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1085,6 +971,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() { @@ -1175,158 +1073,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(SpecificWeight))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(SpecificWeightUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal(SpecificWeight.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal(SpecificWeight.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal(new {SpecificWeight.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 cfb621c88a..ea7ae65dda 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpeedTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpeedTestsBase.g.cs @@ -224,7 +224,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Speed(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -237,15 +237,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Speed_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + SpeedUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Speed(1, SpeedUnit.MeterPerSecond); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Speed.Zero, quantityInfo.Zero); Assert.Equal("Speed", quantityInfo.Name); + Assert.Equal(Speed.Zero, quantityInfo.Zero); + Assert.Equal(Speed.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Speed.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void SpeedInfo_CreateWithCustomUnitInfos() + { + SpeedUnit[] expectedUnits = [SpeedUnit.MeterPerSecond]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -291,135 +309,135 @@ public void MeterPerSecondToSpeedUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Speed.From(1, SpeedUnit.CentimeterPerHour); - AssertEx.EqualTolerance(1, quantity00.CentimetersPerHour, CentimetersPerHourTolerance); + Assert.Equal(1, quantity00.CentimetersPerHour); Assert.Equal(SpeedUnit.CentimeterPerHour, quantity00.Unit); var quantity01 = Speed.From(1, SpeedUnit.CentimeterPerMinute); - AssertEx.EqualTolerance(1, quantity01.CentimetersPerMinute, CentimetersPerMinuteTolerance); + Assert.Equal(1, quantity01.CentimetersPerMinute); Assert.Equal(SpeedUnit.CentimeterPerMinute, quantity01.Unit); var quantity02 = Speed.From(1, SpeedUnit.CentimeterPerSecond); - AssertEx.EqualTolerance(1, quantity02.CentimetersPerSecond, CentimetersPerSecondTolerance); + Assert.Equal(1, quantity02.CentimetersPerSecond); Assert.Equal(SpeedUnit.CentimeterPerSecond, quantity02.Unit); var quantity03 = Speed.From(1, SpeedUnit.DecimeterPerMinute); - AssertEx.EqualTolerance(1, quantity03.DecimetersPerMinute, DecimetersPerMinuteTolerance); + Assert.Equal(1, quantity03.DecimetersPerMinute); Assert.Equal(SpeedUnit.DecimeterPerMinute, quantity03.Unit); var quantity04 = Speed.From(1, SpeedUnit.DecimeterPerSecond); - AssertEx.EqualTolerance(1, quantity04.DecimetersPerSecond, DecimetersPerSecondTolerance); + Assert.Equal(1, quantity04.DecimetersPerSecond); Assert.Equal(SpeedUnit.DecimeterPerSecond, quantity04.Unit); var quantity05 = Speed.From(1, SpeedUnit.FootPerHour); - AssertEx.EqualTolerance(1, quantity05.FeetPerHour, FeetPerHourTolerance); + Assert.Equal(1, quantity05.FeetPerHour); Assert.Equal(SpeedUnit.FootPerHour, quantity05.Unit); var quantity06 = Speed.From(1, SpeedUnit.FootPerMinute); - AssertEx.EqualTolerance(1, quantity06.FeetPerMinute, FeetPerMinuteTolerance); + Assert.Equal(1, quantity06.FeetPerMinute); Assert.Equal(SpeedUnit.FootPerMinute, quantity06.Unit); var quantity07 = Speed.From(1, SpeedUnit.FootPerSecond); - AssertEx.EqualTolerance(1, quantity07.FeetPerSecond, FeetPerSecondTolerance); + Assert.Equal(1, quantity07.FeetPerSecond); Assert.Equal(SpeedUnit.FootPerSecond, quantity07.Unit); var quantity08 = Speed.From(1, SpeedUnit.InchPerHour); - AssertEx.EqualTolerance(1, quantity08.InchesPerHour, InchesPerHourTolerance); + Assert.Equal(1, quantity08.InchesPerHour); Assert.Equal(SpeedUnit.InchPerHour, quantity08.Unit); var quantity09 = Speed.From(1, SpeedUnit.InchPerMinute); - AssertEx.EqualTolerance(1, quantity09.InchesPerMinute, InchesPerMinuteTolerance); + Assert.Equal(1, quantity09.InchesPerMinute); Assert.Equal(SpeedUnit.InchPerMinute, quantity09.Unit); var quantity10 = Speed.From(1, SpeedUnit.InchPerSecond); - AssertEx.EqualTolerance(1, quantity10.InchesPerSecond, InchesPerSecondTolerance); + Assert.Equal(1, quantity10.InchesPerSecond); Assert.Equal(SpeedUnit.InchPerSecond, quantity10.Unit); var quantity11 = Speed.From(1, SpeedUnit.KilometerPerHour); - AssertEx.EqualTolerance(1, quantity11.KilometersPerHour, KilometersPerHourTolerance); + Assert.Equal(1, quantity11.KilometersPerHour); Assert.Equal(SpeedUnit.KilometerPerHour, quantity11.Unit); var quantity12 = Speed.From(1, SpeedUnit.KilometerPerMinute); - AssertEx.EqualTolerance(1, quantity12.KilometersPerMinute, KilometersPerMinuteTolerance); + Assert.Equal(1, quantity12.KilometersPerMinute); Assert.Equal(SpeedUnit.KilometerPerMinute, quantity12.Unit); var quantity13 = Speed.From(1, SpeedUnit.KilometerPerSecond); - AssertEx.EqualTolerance(1, quantity13.KilometersPerSecond, KilometersPerSecondTolerance); + Assert.Equal(1, quantity13.KilometersPerSecond); Assert.Equal(SpeedUnit.KilometerPerSecond, quantity13.Unit); var quantity14 = Speed.From(1, SpeedUnit.Knot); - AssertEx.EqualTolerance(1, quantity14.Knots, KnotsTolerance); + Assert.Equal(1, quantity14.Knots); Assert.Equal(SpeedUnit.Knot, quantity14.Unit); var quantity15 = Speed.From(1, SpeedUnit.Mach); - AssertEx.EqualTolerance(1, quantity15.Mach, MachTolerance); + Assert.Equal(1, quantity15.Mach); Assert.Equal(SpeedUnit.Mach, quantity15.Unit); var quantity16 = Speed.From(1, SpeedUnit.MeterPerHour); - AssertEx.EqualTolerance(1, quantity16.MetersPerHour, MetersPerHourTolerance); + Assert.Equal(1, quantity16.MetersPerHour); Assert.Equal(SpeedUnit.MeterPerHour, quantity16.Unit); var quantity17 = Speed.From(1, SpeedUnit.MeterPerMinute); - AssertEx.EqualTolerance(1, quantity17.MetersPerMinute, MetersPerMinuteTolerance); + Assert.Equal(1, quantity17.MetersPerMinute); Assert.Equal(SpeedUnit.MeterPerMinute, quantity17.Unit); var quantity18 = Speed.From(1, SpeedUnit.MeterPerSecond); - AssertEx.EqualTolerance(1, quantity18.MetersPerSecond, MetersPerSecondTolerance); + Assert.Equal(1, quantity18.MetersPerSecond); Assert.Equal(SpeedUnit.MeterPerSecond, quantity18.Unit); var quantity19 = Speed.From(1, SpeedUnit.MicrometerPerMinute); - AssertEx.EqualTolerance(1, quantity19.MicrometersPerMinute, MicrometersPerMinuteTolerance); + Assert.Equal(1, quantity19.MicrometersPerMinute); Assert.Equal(SpeedUnit.MicrometerPerMinute, quantity19.Unit); var quantity20 = Speed.From(1, SpeedUnit.MicrometerPerSecond); - AssertEx.EqualTolerance(1, quantity20.MicrometersPerSecond, MicrometersPerSecondTolerance); + Assert.Equal(1, quantity20.MicrometersPerSecond); Assert.Equal(SpeedUnit.MicrometerPerSecond, quantity20.Unit); var quantity21 = Speed.From(1, SpeedUnit.MilePerHour); - AssertEx.EqualTolerance(1, quantity21.MilesPerHour, MilesPerHourTolerance); + Assert.Equal(1, quantity21.MilesPerHour); Assert.Equal(SpeedUnit.MilePerHour, quantity21.Unit); var quantity22 = Speed.From(1, SpeedUnit.MillimeterPerHour); - AssertEx.EqualTolerance(1, quantity22.MillimetersPerHour, MillimetersPerHourTolerance); + Assert.Equal(1, quantity22.MillimetersPerHour); Assert.Equal(SpeedUnit.MillimeterPerHour, quantity22.Unit); var quantity23 = Speed.From(1, SpeedUnit.MillimeterPerMinute); - AssertEx.EqualTolerance(1, quantity23.MillimetersPerMinute, MillimetersPerMinuteTolerance); + Assert.Equal(1, quantity23.MillimetersPerMinute); Assert.Equal(SpeedUnit.MillimeterPerMinute, quantity23.Unit); var quantity24 = Speed.From(1, SpeedUnit.MillimeterPerSecond); - AssertEx.EqualTolerance(1, quantity24.MillimetersPerSecond, MillimetersPerSecondTolerance); + Assert.Equal(1, quantity24.MillimetersPerSecond); Assert.Equal(SpeedUnit.MillimeterPerSecond, quantity24.Unit); var quantity25 = Speed.From(1, SpeedUnit.NanometerPerMinute); - AssertEx.EqualTolerance(1, quantity25.NanometersPerMinute, NanometersPerMinuteTolerance); + Assert.Equal(1, quantity25.NanometersPerMinute); Assert.Equal(SpeedUnit.NanometerPerMinute, quantity25.Unit); var quantity26 = Speed.From(1, SpeedUnit.NanometerPerSecond); - AssertEx.EqualTolerance(1, quantity26.NanometersPerSecond, NanometersPerSecondTolerance); + Assert.Equal(1, quantity26.NanometersPerSecond); Assert.Equal(SpeedUnit.NanometerPerSecond, quantity26.Unit); var quantity27 = Speed.From(1, SpeedUnit.UsSurveyFootPerHour); - AssertEx.EqualTolerance(1, quantity27.UsSurveyFeetPerHour, UsSurveyFeetPerHourTolerance); + Assert.Equal(1, quantity27.UsSurveyFeetPerHour); Assert.Equal(SpeedUnit.UsSurveyFootPerHour, quantity27.Unit); var quantity28 = Speed.From(1, SpeedUnit.UsSurveyFootPerMinute); - AssertEx.EqualTolerance(1, quantity28.UsSurveyFeetPerMinute, UsSurveyFeetPerMinuteTolerance); + Assert.Equal(1, quantity28.UsSurveyFeetPerMinute); Assert.Equal(SpeedUnit.UsSurveyFootPerMinute, quantity28.Unit); var quantity29 = Speed.From(1, SpeedUnit.UsSurveyFootPerSecond); - AssertEx.EqualTolerance(1, quantity29.UsSurveyFeetPerSecond, UsSurveyFeetPerSecondTolerance); + Assert.Equal(1, quantity29.UsSurveyFeetPerSecond); Assert.Equal(SpeedUnit.UsSurveyFootPerSecond, quantity29.Unit); var quantity30 = Speed.From(1, SpeedUnit.YardPerHour); - AssertEx.EqualTolerance(1, quantity30.YardsPerHour, YardsPerHourTolerance); + Assert.Equal(1, quantity30.YardsPerHour); Assert.Equal(SpeedUnit.YardPerHour, quantity30.Unit); var quantity31 = Speed.From(1, SpeedUnit.YardPerMinute); - AssertEx.EqualTolerance(1, quantity31.YardsPerMinute, YardsPerMinuteTolerance); + Assert.Equal(1, quantity31.YardsPerMinute); Assert.Equal(SpeedUnit.YardPerMinute, quantity31.Unit); var quantity32 = Speed.From(1, SpeedUnit.YardPerSecond); - AssertEx.EqualTolerance(1, quantity32.YardsPerSecond, YardsPerSecondTolerance); + Assert.Equal(1, quantity32.YardsPerSecond); Assert.Equal(SpeedUnit.YardPerSecond, quantity32.Unit); } @@ -587,833 +605,148 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 cm/h", SpeedUnit.CentimeterPerHour, 4.2)] + [InlineData("en-US", "4.2 cm/min", SpeedUnit.CentimeterPerMinute, 4.2)] + [InlineData("en-US", "4.2 cm/s", SpeedUnit.CentimeterPerSecond, 4.2)] + [InlineData("en-US", "4.2 dm/min", SpeedUnit.DecimeterPerMinute, 4.2)] + [InlineData("en-US", "4.2 dm/s", SpeedUnit.DecimeterPerSecond, 4.2)] + [InlineData("en-US", "4.2 ft/h", SpeedUnit.FootPerHour, 4.2)] + [InlineData("en-US", "4.2 ft/min", SpeedUnit.FootPerMinute, 4.2)] + [InlineData("en-US", "4.2 ft/s", SpeedUnit.FootPerSecond, 4.2)] + [InlineData("en-US", "4.2 in/h", SpeedUnit.InchPerHour, 4.2)] + [InlineData("en-US", "4.2 in/min", SpeedUnit.InchPerMinute, 4.2)] + [InlineData("en-US", "4.2 in/s", SpeedUnit.InchPerSecond, 4.2)] + [InlineData("en-US", "4.2 km/h", SpeedUnit.KilometerPerHour, 4.2)] + [InlineData("en-US", "4.2 km/min", SpeedUnit.KilometerPerMinute, 4.2)] + [InlineData("en-US", "4.2 km/s", SpeedUnit.KilometerPerSecond, 4.2)] + [InlineData("en-US", "4.2 kn", SpeedUnit.Knot, 4.2)] + [InlineData("en-US", "4.2 kt", SpeedUnit.Knot, 4.2)] + [InlineData("en-US", "4.2 knot", SpeedUnit.Knot, 4.2)] + [InlineData("en-US", "4.2 knots", SpeedUnit.Knot, 4.2)] + [InlineData("en-US", "4.2 M", SpeedUnit.Mach, 4.2)] + [InlineData("en-US", "4.2 Ma", SpeedUnit.Mach, 4.2)] + [InlineData("en-US", "4.2 MN", SpeedUnit.Mach, 4.2)] + [InlineData("en-US", "4.2 MACH", SpeedUnit.Mach, 4.2)] + [InlineData("en-US", "4.2 m/h", SpeedUnit.MeterPerHour, 4.2)] + [InlineData("en-US", "4.2 m/min", SpeedUnit.MeterPerMinute, 4.2)] + [InlineData("en-US", "4.2 m/s", SpeedUnit.MeterPerSecond, 4.2)] + [InlineData("en-US", "4.2 µm/min", SpeedUnit.MicrometerPerMinute, 4.2)] + [InlineData("en-US", "4.2 µm/s", SpeedUnit.MicrometerPerSecond, 4.2)] + [InlineData("en-US", "4.2 mph", SpeedUnit.MilePerHour, 4.2)] + [InlineData("en-US", "4.2 mm/h", SpeedUnit.MillimeterPerHour, 4.2)] + [InlineData("en-US", "4.2 mm/min", SpeedUnit.MillimeterPerMinute, 4.2)] + [InlineData("en-US", "4.2 mm/s", SpeedUnit.MillimeterPerSecond, 4.2)] + [InlineData("en-US", "4.2 nm/min", SpeedUnit.NanometerPerMinute, 4.2)] + [InlineData("en-US", "4.2 nm/s", SpeedUnit.NanometerPerSecond, 4.2)] + [InlineData("en-US", "4.2 ftUS/h", SpeedUnit.UsSurveyFootPerHour, 4.2)] + [InlineData("en-US", "4.2 ftUS/min", SpeedUnit.UsSurveyFootPerMinute, 4.2)] + [InlineData("en-US", "4.2 ftUS/s", SpeedUnit.UsSurveyFootPerSecond, 4.2)] + [InlineData("en-US", "4.2 yd/h", SpeedUnit.YardPerHour, 4.2)] + [InlineData("en-US", "4.2 yd/min", SpeedUnit.YardPerMinute, 4.2)] + [InlineData("en-US", "4.2 yd/s", SpeedUnit.YardPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 см/ч", SpeedUnit.CentimeterPerHour, 4.2)] + [InlineData("ru-RU", "4,2 см/мин", SpeedUnit.CentimeterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 см/с", SpeedUnit.CentimeterPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 дм/мин", SpeedUnit.DecimeterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 дм/с", SpeedUnit.DecimeterPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 фут/ч", SpeedUnit.FootPerHour, 4.2)] + [InlineData("ru-RU", "4,2 фут/мин", SpeedUnit.FootPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 фут/с", SpeedUnit.FootPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 км/ч", SpeedUnit.KilometerPerHour, 4.2)] + [InlineData("ru-RU", "4,2 км/мин", SpeedUnit.KilometerPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 км/с", SpeedUnit.KilometerPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 уз.", SpeedUnit.Knot, 4.2)] + [InlineData("ru-RU", "4,2 мах", SpeedUnit.Mach, 4.2)] + [InlineData("ru-RU", "4,2 м/ч", SpeedUnit.MeterPerHour, 4.2)] + [InlineData("ru-RU", "4,2 м/мин", SpeedUnit.MeterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 м/с", SpeedUnit.MeterPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 мкм/мин", SpeedUnit.MicrometerPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 мкм/с", SpeedUnit.MicrometerPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 миль/ч", SpeedUnit.MilePerHour, 4.2)] + [InlineData("ru-RU", "4,2 мм/ч", SpeedUnit.MillimeterPerHour, 4.2)] + [InlineData("ru-RU", "4,2 мм/мин", SpeedUnit.MillimeterPerMinute, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = Speed.Parse("1 cm/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentimetersPerHour, CentimetersPerHourTolerance); - Assert.Equal(SpeedUnit.CentimeterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 см/ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CentimetersPerHour, CentimetersPerHourTolerance); - Assert.Equal(SpeedUnit.CentimeterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 cm/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentimetersPerMinute, CentimetersPerMinuteTolerance); - Assert.Equal(SpeedUnit.CentimeterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 см/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CentimetersPerMinute, CentimetersPerMinuteTolerance); - Assert.Equal(SpeedUnit.CentimeterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 cm/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentimetersPerSecond, CentimetersPerSecondTolerance); - Assert.Equal(SpeedUnit.CentimeterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 см/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CentimetersPerSecond, CentimetersPerSecondTolerance); - Assert.Equal(SpeedUnit.CentimeterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 dm/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecimetersPerMinute, DecimetersPerMinuteTolerance); - Assert.Equal(SpeedUnit.DecimeterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 дм/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.DecimetersPerMinute, DecimetersPerMinuteTolerance); - Assert.Equal(SpeedUnit.DecimeterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 dm/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecimetersPerSecond, DecimetersPerSecondTolerance); - Assert.Equal(SpeedUnit.DecimeterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 дм/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.DecimetersPerSecond, DecimetersPerSecondTolerance); - Assert.Equal(SpeedUnit.DecimeterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 ft/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.FeetPerHour, FeetPerHourTolerance); - Assert.Equal(SpeedUnit.FootPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 фут/ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.FeetPerHour, FeetPerHourTolerance); - Assert.Equal(SpeedUnit.FootPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 ft/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.FeetPerMinute, FeetPerMinuteTolerance); - Assert.Equal(SpeedUnit.FootPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 фут/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.FeetPerMinute, FeetPerMinuteTolerance); - Assert.Equal(SpeedUnit.FootPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 ft/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.FeetPerSecond, FeetPerSecondTolerance); - Assert.Equal(SpeedUnit.FootPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 фут/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.FeetPerSecond, FeetPerSecondTolerance); - Assert.Equal(SpeedUnit.FootPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 in/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InchesPerHour, InchesPerHourTolerance); - Assert.Equal(SpeedUnit.InchPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 in/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InchesPerMinute, InchesPerMinuteTolerance); - Assert.Equal(SpeedUnit.InchPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 in/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InchesPerSecond, InchesPerSecondTolerance); - Assert.Equal(SpeedUnit.InchPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 km/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilometersPerHour, KilometersPerHourTolerance); - Assert.Equal(SpeedUnit.KilometerPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 км/ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilometersPerHour, KilometersPerHourTolerance); - Assert.Equal(SpeedUnit.KilometerPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 km/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilometersPerMinute, KilometersPerMinuteTolerance); - Assert.Equal(SpeedUnit.KilometerPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 км/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilometersPerMinute, KilometersPerMinuteTolerance); - Assert.Equal(SpeedUnit.KilometerPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 km/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilometersPerSecond, KilometersPerSecondTolerance); - Assert.Equal(SpeedUnit.KilometerPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 км/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilometersPerSecond, KilometersPerSecondTolerance); - Assert.Equal(SpeedUnit.KilometerPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 kn", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Knots, KnotsTolerance); - Assert.Equal(SpeedUnit.Knot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 kt", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Knots, KnotsTolerance); - Assert.Equal(SpeedUnit.Knot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 knot", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Knots, KnotsTolerance); - Assert.Equal(SpeedUnit.Knot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 knots", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Knots, KnotsTolerance); - Assert.Equal(SpeedUnit.Knot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 уз.", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Knots, KnotsTolerance); - Assert.Equal(SpeedUnit.Knot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 M", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Mach, MachTolerance); - Assert.Equal(SpeedUnit.Mach, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 Ma", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Mach, MachTolerance); - Assert.Equal(SpeedUnit.Mach, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 MN", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Mach, MachTolerance); - Assert.Equal(SpeedUnit.Mach, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 MACH", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Mach, MachTolerance); - Assert.Equal(SpeedUnit.Mach, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 мах", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Mach, MachTolerance); - Assert.Equal(SpeedUnit.Mach, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 m/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MetersPerHour, MetersPerHourTolerance); - Assert.Equal(SpeedUnit.MeterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 м/ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MetersPerHour, MetersPerHourTolerance); - Assert.Equal(SpeedUnit.MeterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 m/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MetersPerMinute, MetersPerMinuteTolerance); - Assert.Equal(SpeedUnit.MeterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 м/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MetersPerMinute, MetersPerMinuteTolerance); - Assert.Equal(SpeedUnit.MeterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 m/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MetersPerSecond, MetersPerSecondTolerance); - Assert.Equal(SpeedUnit.MeterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 м/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MetersPerSecond, MetersPerSecondTolerance); - Assert.Equal(SpeedUnit.MeterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 µm/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrometersPerMinute, MicrometersPerMinuteTolerance); - Assert.Equal(SpeedUnit.MicrometerPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 мкм/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MicrometersPerMinute, MicrometersPerMinuteTolerance); - Assert.Equal(SpeedUnit.MicrometerPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 µm/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrometersPerSecond, MicrometersPerSecondTolerance); - Assert.Equal(SpeedUnit.MicrometerPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 мкм/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MicrometersPerSecond, MicrometersPerSecondTolerance); - Assert.Equal(SpeedUnit.MicrometerPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 mph", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MilesPerHour, MilesPerHourTolerance); - Assert.Equal(SpeedUnit.MilePerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 миль/ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MilesPerHour, MilesPerHourTolerance); - Assert.Equal(SpeedUnit.MilePerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 mm/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillimetersPerHour, MillimetersPerHourTolerance); - Assert.Equal(SpeedUnit.MillimeterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 мм/ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MillimetersPerHour, MillimetersPerHourTolerance); - Assert.Equal(SpeedUnit.MillimeterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 mm/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillimetersPerMinute, MillimetersPerMinuteTolerance); - Assert.Equal(SpeedUnit.MillimeterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 мм/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MillimetersPerMinute, MillimetersPerMinuteTolerance); - Assert.Equal(SpeedUnit.MillimeterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 mm/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillimetersPerSecond, MillimetersPerSecondTolerance); - Assert.Equal(SpeedUnit.MillimeterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 мм/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MillimetersPerSecond, MillimetersPerSecondTolerance); - Assert.Equal(SpeedUnit.MillimeterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 nm/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanometersPerMinute, NanometersPerMinuteTolerance); - Assert.Equal(SpeedUnit.NanometerPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 нм/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.NanometersPerMinute, NanometersPerMinuteTolerance); - Assert.Equal(SpeedUnit.NanometerPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 nm/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanometersPerSecond, NanometersPerSecondTolerance); - Assert.Equal(SpeedUnit.NanometerPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 нм/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.NanometersPerSecond, NanometersPerSecondTolerance); - Assert.Equal(SpeedUnit.NanometerPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 ftUS/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.UsSurveyFeetPerHour, UsSurveyFeetPerHourTolerance); - Assert.Equal(SpeedUnit.UsSurveyFootPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 ftUS/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.UsSurveyFeetPerMinute, UsSurveyFeetPerMinuteTolerance); - Assert.Equal(SpeedUnit.UsSurveyFootPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 ftUS/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.UsSurveyFeetPerSecond, UsSurveyFeetPerSecondTolerance); - Assert.Equal(SpeedUnit.UsSurveyFootPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 yd/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.YardsPerHour, YardsPerHourTolerance); - Assert.Equal(SpeedUnit.YardPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 yd/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.YardsPerMinute, YardsPerMinuteTolerance); - Assert.Equal(SpeedUnit.YardPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Speed.Parse("1 yd/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.YardsPerSecond, YardsPerSecondTolerance); - Assert.Equal(SpeedUnit.YardPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Speed.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 cm/h", SpeedUnit.CentimeterPerHour, 4.2)] + [InlineData("en-US", "4.2 cm/min", SpeedUnit.CentimeterPerMinute, 4.2)] + [InlineData("en-US", "4.2 cm/s", SpeedUnit.CentimeterPerSecond, 4.2)] + [InlineData("en-US", "4.2 dm/min", SpeedUnit.DecimeterPerMinute, 4.2)] + [InlineData("en-US", "4.2 dm/s", SpeedUnit.DecimeterPerSecond, 4.2)] + [InlineData("en-US", "4.2 ft/h", SpeedUnit.FootPerHour, 4.2)] + [InlineData("en-US", "4.2 ft/min", SpeedUnit.FootPerMinute, 4.2)] + [InlineData("en-US", "4.2 ft/s", SpeedUnit.FootPerSecond, 4.2)] + [InlineData("en-US", "4.2 in/h", SpeedUnit.InchPerHour, 4.2)] + [InlineData("en-US", "4.2 in/min", SpeedUnit.InchPerMinute, 4.2)] + [InlineData("en-US", "4.2 in/s", SpeedUnit.InchPerSecond, 4.2)] + [InlineData("en-US", "4.2 km/h", SpeedUnit.KilometerPerHour, 4.2)] + [InlineData("en-US", "4.2 km/min", SpeedUnit.KilometerPerMinute, 4.2)] + [InlineData("en-US", "4.2 km/s", SpeedUnit.KilometerPerSecond, 4.2)] + [InlineData("en-US", "4.2 kn", SpeedUnit.Knot, 4.2)] + [InlineData("en-US", "4.2 kt", SpeedUnit.Knot, 4.2)] + [InlineData("en-US", "4.2 knot", SpeedUnit.Knot, 4.2)] + [InlineData("en-US", "4.2 knots", SpeedUnit.Knot, 4.2)] + [InlineData("en-US", "4.2 M", SpeedUnit.Mach, 4.2)] + [InlineData("en-US", "4.2 Ma", SpeedUnit.Mach, 4.2)] + [InlineData("en-US", "4.2 MN", SpeedUnit.Mach, 4.2)] + [InlineData("en-US", "4.2 MACH", SpeedUnit.Mach, 4.2)] + [InlineData("en-US", "4.2 m/h", SpeedUnit.MeterPerHour, 4.2)] + [InlineData("en-US", "4.2 m/min", SpeedUnit.MeterPerMinute, 4.2)] + [InlineData("en-US", "4.2 m/s", SpeedUnit.MeterPerSecond, 4.2)] + [InlineData("en-US", "4.2 µm/min", SpeedUnit.MicrometerPerMinute, 4.2)] + [InlineData("en-US", "4.2 µm/s", SpeedUnit.MicrometerPerSecond, 4.2)] + [InlineData("en-US", "4.2 mph", SpeedUnit.MilePerHour, 4.2)] + [InlineData("en-US", "4.2 mm/h", SpeedUnit.MillimeterPerHour, 4.2)] + [InlineData("en-US", "4.2 mm/min", SpeedUnit.MillimeterPerMinute, 4.2)] + [InlineData("en-US", "4.2 mm/s", SpeedUnit.MillimeterPerSecond, 4.2)] + [InlineData("en-US", "4.2 nm/min", SpeedUnit.NanometerPerMinute, 4.2)] + [InlineData("en-US", "4.2 nm/s", SpeedUnit.NanometerPerSecond, 4.2)] + [InlineData("en-US", "4.2 ftUS/h", SpeedUnit.UsSurveyFootPerHour, 4.2)] + [InlineData("en-US", "4.2 ftUS/min", SpeedUnit.UsSurveyFootPerMinute, 4.2)] + [InlineData("en-US", "4.2 ftUS/s", SpeedUnit.UsSurveyFootPerSecond, 4.2)] + [InlineData("en-US", "4.2 yd/h", SpeedUnit.YardPerHour, 4.2)] + [InlineData("en-US", "4.2 yd/min", SpeedUnit.YardPerMinute, 4.2)] + [InlineData("en-US", "4.2 yd/s", SpeedUnit.YardPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 см/ч", SpeedUnit.CentimeterPerHour, 4.2)] + [InlineData("ru-RU", "4,2 см/мин", SpeedUnit.CentimeterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 см/с", SpeedUnit.CentimeterPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 дм/мин", SpeedUnit.DecimeterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 дм/с", SpeedUnit.DecimeterPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 фут/ч", SpeedUnit.FootPerHour, 4.2)] + [InlineData("ru-RU", "4,2 фут/мин", SpeedUnit.FootPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 фут/с", SpeedUnit.FootPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 км/ч", SpeedUnit.KilometerPerHour, 4.2)] + [InlineData("ru-RU", "4,2 км/мин", SpeedUnit.KilometerPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 км/с", SpeedUnit.KilometerPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 уз.", SpeedUnit.Knot, 4.2)] + [InlineData("ru-RU", "4,2 мах", SpeedUnit.Mach, 4.2)] + [InlineData("ru-RU", "4,2 м/ч", SpeedUnit.MeterPerHour, 4.2)] + [InlineData("ru-RU", "4,2 м/мин", SpeedUnit.MeterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 м/с", SpeedUnit.MeterPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 мкм/мин", SpeedUnit.MicrometerPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 мкм/с", SpeedUnit.MicrometerPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 миль/ч", SpeedUnit.MilePerHour, 4.2)] + [InlineData("ru-RU", "4,2 мм/ч", SpeedUnit.MillimeterPerHour, 4.2)] + [InlineData("ru-RU", "4,2 мм/мин", SpeedUnit.MillimeterPerMinute, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(Speed.TryParse("1 cm/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentimetersPerHour, CentimetersPerHourTolerance); - Assert.Equal(SpeedUnit.CentimeterPerHour, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 см/ч", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentimetersPerHour, CentimetersPerHourTolerance); - Assert.Equal(SpeedUnit.CentimeterPerHour, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 cm/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentimetersPerMinute, CentimetersPerMinuteTolerance); - Assert.Equal(SpeedUnit.CentimeterPerMinute, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 см/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentimetersPerMinute, CentimetersPerMinuteTolerance); - Assert.Equal(SpeedUnit.CentimeterPerMinute, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 cm/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentimetersPerSecond, CentimetersPerSecondTolerance); - Assert.Equal(SpeedUnit.CentimeterPerSecond, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 см/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentimetersPerSecond, CentimetersPerSecondTolerance); - Assert.Equal(SpeedUnit.CentimeterPerSecond, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 dm/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecimetersPerMinute, DecimetersPerMinuteTolerance); - Assert.Equal(SpeedUnit.DecimeterPerMinute, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 дм/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecimetersPerMinute, DecimetersPerMinuteTolerance); - Assert.Equal(SpeedUnit.DecimeterPerMinute, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 dm/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecimetersPerSecond, DecimetersPerSecondTolerance); - Assert.Equal(SpeedUnit.DecimeterPerSecond, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 дм/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecimetersPerSecond, DecimetersPerSecondTolerance); - Assert.Equal(SpeedUnit.DecimeterPerSecond, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 ft/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.FeetPerHour, FeetPerHourTolerance); - Assert.Equal(SpeedUnit.FootPerHour, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 фут/ч", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.FeetPerHour, FeetPerHourTolerance); - Assert.Equal(SpeedUnit.FootPerHour, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 ft/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.FeetPerMinute, FeetPerMinuteTolerance); - Assert.Equal(SpeedUnit.FootPerMinute, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 фут/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.FeetPerMinute, FeetPerMinuteTolerance); - Assert.Equal(SpeedUnit.FootPerMinute, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 ft/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.FeetPerSecond, FeetPerSecondTolerance); - Assert.Equal(SpeedUnit.FootPerSecond, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 фут/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.FeetPerSecond, FeetPerSecondTolerance); - Assert.Equal(SpeedUnit.FootPerSecond, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 in/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InchesPerHour, InchesPerHourTolerance); - Assert.Equal(SpeedUnit.InchPerHour, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 in/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InchesPerMinute, InchesPerMinuteTolerance); - Assert.Equal(SpeedUnit.InchPerMinute, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 in/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InchesPerSecond, InchesPerSecondTolerance); - Assert.Equal(SpeedUnit.InchPerSecond, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 km/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilometersPerHour, KilometersPerHourTolerance); - Assert.Equal(SpeedUnit.KilometerPerHour, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 км/ч", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilometersPerHour, KilometersPerHourTolerance); - Assert.Equal(SpeedUnit.KilometerPerHour, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 km/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilometersPerMinute, KilometersPerMinuteTolerance); - Assert.Equal(SpeedUnit.KilometerPerMinute, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 км/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilometersPerMinute, KilometersPerMinuteTolerance); - Assert.Equal(SpeedUnit.KilometerPerMinute, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 km/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilometersPerSecond, KilometersPerSecondTolerance); - Assert.Equal(SpeedUnit.KilometerPerSecond, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 км/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilometersPerSecond, KilometersPerSecondTolerance); - Assert.Equal(SpeedUnit.KilometerPerSecond, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 kn", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Knots, KnotsTolerance); - Assert.Equal(SpeedUnit.Knot, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 kt", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Knots, KnotsTolerance); - Assert.Equal(SpeedUnit.Knot, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 knot", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Knots, KnotsTolerance); - Assert.Equal(SpeedUnit.Knot, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 knots", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Knots, KnotsTolerance); - Assert.Equal(SpeedUnit.Knot, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 уз.", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Knots, KnotsTolerance); - Assert.Equal(SpeedUnit.Knot, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 M", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Mach, MachTolerance); - Assert.Equal(SpeedUnit.Mach, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 Ma", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Mach, MachTolerance); - Assert.Equal(SpeedUnit.Mach, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 MN", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Mach, MachTolerance); - Assert.Equal(SpeedUnit.Mach, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 MACH", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Mach, MachTolerance); - Assert.Equal(SpeedUnit.Mach, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 мах", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Mach, MachTolerance); - Assert.Equal(SpeedUnit.Mach, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 m/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetersPerHour, MetersPerHourTolerance); - Assert.Equal(SpeedUnit.MeterPerHour, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 м/ч", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetersPerHour, MetersPerHourTolerance); - Assert.Equal(SpeedUnit.MeterPerHour, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 m/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetersPerMinute, MetersPerMinuteTolerance); - Assert.Equal(SpeedUnit.MeterPerMinute, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 м/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetersPerMinute, MetersPerMinuteTolerance); - Assert.Equal(SpeedUnit.MeterPerMinute, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 m/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetersPerSecond, MetersPerSecondTolerance); - Assert.Equal(SpeedUnit.MeterPerSecond, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 м/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetersPerSecond, MetersPerSecondTolerance); - Assert.Equal(SpeedUnit.MeterPerSecond, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 µm/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrometersPerMinute, MicrometersPerMinuteTolerance); - Assert.Equal(SpeedUnit.MicrometerPerMinute, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 мкм/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrometersPerMinute, MicrometersPerMinuteTolerance); - Assert.Equal(SpeedUnit.MicrometerPerMinute, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 µm/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrometersPerSecond, MicrometersPerSecondTolerance); - Assert.Equal(SpeedUnit.MicrometerPerSecond, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 мкм/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrometersPerSecond, MicrometersPerSecondTolerance); - Assert.Equal(SpeedUnit.MicrometerPerSecond, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 mph", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilesPerHour, MilesPerHourTolerance); - Assert.Equal(SpeedUnit.MilePerHour, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 миль/ч", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MilesPerHour, MilesPerHourTolerance); - Assert.Equal(SpeedUnit.MilePerHour, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 mm/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimetersPerHour, MillimetersPerHourTolerance); - Assert.Equal(SpeedUnit.MillimeterPerHour, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 мм/ч", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimetersPerHour, MillimetersPerHourTolerance); - Assert.Equal(SpeedUnit.MillimeterPerHour, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 mm/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimetersPerMinute, MillimetersPerMinuteTolerance); - Assert.Equal(SpeedUnit.MillimeterPerMinute, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 мм/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimetersPerMinute, MillimetersPerMinuteTolerance); - Assert.Equal(SpeedUnit.MillimeterPerMinute, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 mm/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimetersPerSecond, MillimetersPerSecondTolerance); - Assert.Equal(SpeedUnit.MillimeterPerSecond, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 мм/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimetersPerSecond, MillimetersPerSecondTolerance); - Assert.Equal(SpeedUnit.MillimeterPerSecond, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 nm/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanometersPerMinute, NanometersPerMinuteTolerance); - Assert.Equal(SpeedUnit.NanometerPerMinute, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 нм/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanometersPerMinute, NanometersPerMinuteTolerance); - Assert.Equal(SpeedUnit.NanometerPerMinute, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 nm/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanometersPerSecond, NanometersPerSecondTolerance); - Assert.Equal(SpeedUnit.NanometerPerSecond, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 нм/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanometersPerSecond, NanometersPerSecondTolerance); - Assert.Equal(SpeedUnit.NanometerPerSecond, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 ftUS/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UsSurveyFeetPerHour, UsSurveyFeetPerHourTolerance); - Assert.Equal(SpeedUnit.UsSurveyFootPerHour, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 ftUS/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UsSurveyFeetPerMinute, UsSurveyFeetPerMinuteTolerance); - Assert.Equal(SpeedUnit.UsSurveyFootPerMinute, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 ftUS/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UsSurveyFeetPerSecond, UsSurveyFeetPerSecondTolerance); - Assert.Equal(SpeedUnit.UsSurveyFootPerSecond, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 yd/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.YardsPerHour, YardsPerHourTolerance); - Assert.Equal(SpeedUnit.YardPerHour, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 yd/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.YardsPerMinute, YardsPerMinuteTolerance); - Assert.Equal(SpeedUnit.YardPerMinute, parsed.Unit); - } - - { - Assert.True(Speed.TryParse("1 yd/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.YardsPerSecond, YardsPerSecondTolerance); - Assert.Equal(SpeedUnit.YardPerSecond, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Speed.TryParse(quantityString, out Speed parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -1890,6 +1223,83 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, SpeedU Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", SpeedUnit.CentimeterPerHour, "cm/h")] + [InlineData("en-US", SpeedUnit.CentimeterPerMinute, "cm/min")] + [InlineData("en-US", SpeedUnit.CentimeterPerSecond, "cm/s")] + [InlineData("en-US", SpeedUnit.DecimeterPerMinute, "dm/min")] + [InlineData("en-US", SpeedUnit.DecimeterPerSecond, "dm/s")] + [InlineData("en-US", SpeedUnit.FootPerHour, "ft/h")] + [InlineData("en-US", SpeedUnit.FootPerMinute, "ft/min")] + [InlineData("en-US", SpeedUnit.FootPerSecond, "ft/s")] + [InlineData("en-US", SpeedUnit.InchPerHour, "in/h")] + [InlineData("en-US", SpeedUnit.InchPerMinute, "in/min")] + [InlineData("en-US", SpeedUnit.InchPerSecond, "in/s")] + [InlineData("en-US", SpeedUnit.KilometerPerHour, "km/h")] + [InlineData("en-US", SpeedUnit.KilometerPerMinute, "km/min")] + [InlineData("en-US", SpeedUnit.KilometerPerSecond, "km/s")] + [InlineData("en-US", SpeedUnit.Knot, "kn")] + [InlineData("en-US", SpeedUnit.Mach, "M")] + [InlineData("en-US", SpeedUnit.MeterPerHour, "m/h")] + [InlineData("en-US", SpeedUnit.MeterPerMinute, "m/min")] + [InlineData("en-US", SpeedUnit.MeterPerSecond, "m/s")] + [InlineData("en-US", SpeedUnit.MicrometerPerMinute, "µm/min")] + [InlineData("en-US", SpeedUnit.MicrometerPerSecond, "µm/s")] + [InlineData("en-US", SpeedUnit.MilePerHour, "mph")] + [InlineData("en-US", SpeedUnit.MillimeterPerHour, "mm/h")] + [InlineData("en-US", SpeedUnit.MillimeterPerMinute, "mm/min")] + [InlineData("en-US", SpeedUnit.MillimeterPerSecond, "mm/s")] + [InlineData("en-US", SpeedUnit.NanometerPerMinute, "nm/min")] + [InlineData("en-US", SpeedUnit.NanometerPerSecond, "nm/s")] + [InlineData("en-US", SpeedUnit.UsSurveyFootPerHour, "ftUS/h")] + [InlineData("en-US", SpeedUnit.UsSurveyFootPerMinute, "ftUS/min")] + [InlineData("en-US", SpeedUnit.UsSurveyFootPerSecond, "ftUS/s")] + [InlineData("en-US", SpeedUnit.YardPerHour, "yd/h")] + [InlineData("en-US", SpeedUnit.YardPerMinute, "yd/min")] + [InlineData("en-US", SpeedUnit.YardPerSecond, "yd/s")] + [InlineData("ru-RU", SpeedUnit.CentimeterPerHour, "см/ч")] + [InlineData("ru-RU", SpeedUnit.CentimeterPerMinute, "см/мин")] + [InlineData("ru-RU", SpeedUnit.CentimeterPerSecond, "см/с")] + [InlineData("ru-RU", SpeedUnit.DecimeterPerMinute, "дм/мин")] + [InlineData("ru-RU", SpeedUnit.DecimeterPerSecond, "дм/с")] + [InlineData("ru-RU", SpeedUnit.FootPerHour, "фут/ч")] + [InlineData("ru-RU", SpeedUnit.FootPerMinute, "фут/мин")] + [InlineData("ru-RU", SpeedUnit.FootPerSecond, "фут/с")] + [InlineData("ru-RU", SpeedUnit.KilometerPerHour, "км/ч")] + [InlineData("ru-RU", SpeedUnit.KilometerPerMinute, "км/мин")] + [InlineData("ru-RU", SpeedUnit.KilometerPerSecond, "км/с")] + [InlineData("ru-RU", SpeedUnit.Knot, "уз.")] + [InlineData("ru-RU", SpeedUnit.Mach, "мах")] + [InlineData("ru-RU", SpeedUnit.MeterPerHour, "м/ч")] + [InlineData("ru-RU", SpeedUnit.MeterPerMinute, "м/мин")] + [InlineData("ru-RU", SpeedUnit.MeterPerSecond, "м/с")] + [InlineData("ru-RU", SpeedUnit.MicrometerPerMinute, "мкм/мин")] + [InlineData("ru-RU", SpeedUnit.MicrometerPerSecond, "мкм/с")] + [InlineData("ru-RU", SpeedUnit.MilePerHour, "миль/ч")] + [InlineData("ru-RU", SpeedUnit.MillimeterPerHour, "мм/ч")] + [InlineData("ru-RU", SpeedUnit.MillimeterPerMinute, "мм/мин")] + [InlineData("ru-RU", SpeedUnit.MillimeterPerSecond, "мм/с")] + [InlineData("ru-RU", SpeedUnit.NanometerPerMinute, "нм/мин")] + [InlineData("ru-RU", SpeedUnit.NanometerPerSecond, "нм/с")] + public void GetAbbreviationForCulture(string culture, SpeedUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Speed.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Speed.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Speed.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(SpeedUnit unit) @@ -1920,6 +1330,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); }); } @@ -1943,64 +1354,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] @@ -2046,8 +1459,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); @@ -2084,23 +1495,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = Speed.FromMetersPerSecond(1); - Assert.True(v.Equals(Speed.FromMetersPerSecond(1), MetersPerSecondTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Speed.Zero, MetersPerSecondTolerance, ComparisonType.Relative)); - Assert.True(Speed.FromMetersPerSecond(100).Equals(Speed.FromMetersPerSecond(120), 0.3, ComparisonType.Relative)); - Assert.False(Speed.FromMetersPerSecond(100).Equals(Speed.FromMetersPerSecond(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = Speed.FromMetersPerSecond(1); - Assert.Throws(() => v.Equals(Speed.FromMetersPerSecond(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -2115,6 +1509,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(meterpersecond.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = Speed.FromMetersPerSecond(1); + var negativeTolerance = Speed.FromMetersPerSecond(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -2131,6 +1551,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() { @@ -2253,158 +1685,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Speed))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(SpeedUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal(Speed.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal(Speed.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal(new {Speed.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 d0320603e4..4a48cbc106 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/StandardVolumeFlowTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/StandardVolumeFlowTestsBase.g.cs @@ -128,7 +128,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new StandardVolumeFlow(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -141,15 +141,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void StandardVolumeFlow_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + StandardVolumeFlowUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new StandardVolumeFlow(1, StandardVolumeFlowUnit.StandardCubicMeterPerSecond); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(StandardVolumeFlow.Zero, quantityInfo.Zero); Assert.Equal("StandardVolumeFlow", quantityInfo.Name); + Assert.Equal(StandardVolumeFlow.Zero, quantityInfo.Zero); + Assert.Equal(StandardVolumeFlow.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(StandardVolumeFlow.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -171,39 +189,39 @@ public void StandardCubicMeterPerSecondToStandardVolumeFlowUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = StandardVolumeFlow.From(1, StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute); - AssertEx.EqualTolerance(1, quantity00.StandardCubicCentimetersPerMinute, StandardCubicCentimetersPerMinuteTolerance); + Assert.Equal(1, quantity00.StandardCubicCentimetersPerMinute); Assert.Equal(StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute, quantity00.Unit); var quantity01 = StandardVolumeFlow.From(1, StandardVolumeFlowUnit.StandardCubicFootPerHour); - AssertEx.EqualTolerance(1, quantity01.StandardCubicFeetPerHour, StandardCubicFeetPerHourTolerance); + Assert.Equal(1, quantity01.StandardCubicFeetPerHour); Assert.Equal(StandardVolumeFlowUnit.StandardCubicFootPerHour, quantity01.Unit); var quantity02 = StandardVolumeFlow.From(1, StandardVolumeFlowUnit.StandardCubicFootPerMinute); - AssertEx.EqualTolerance(1, quantity02.StandardCubicFeetPerMinute, StandardCubicFeetPerMinuteTolerance); + Assert.Equal(1, quantity02.StandardCubicFeetPerMinute); Assert.Equal(StandardVolumeFlowUnit.StandardCubicFootPerMinute, quantity02.Unit); var quantity03 = StandardVolumeFlow.From(1, StandardVolumeFlowUnit.StandardCubicFootPerSecond); - AssertEx.EqualTolerance(1, quantity03.StandardCubicFeetPerSecond, StandardCubicFeetPerSecondTolerance); + Assert.Equal(1, quantity03.StandardCubicFeetPerSecond); Assert.Equal(StandardVolumeFlowUnit.StandardCubicFootPerSecond, quantity03.Unit); var quantity04 = StandardVolumeFlow.From(1, StandardVolumeFlowUnit.StandardCubicMeterPerDay); - AssertEx.EqualTolerance(1, quantity04.StandardCubicMetersPerDay, StandardCubicMetersPerDayTolerance); + Assert.Equal(1, quantity04.StandardCubicMetersPerDay); Assert.Equal(StandardVolumeFlowUnit.StandardCubicMeterPerDay, quantity04.Unit); var quantity05 = StandardVolumeFlow.From(1, StandardVolumeFlowUnit.StandardCubicMeterPerHour); - AssertEx.EqualTolerance(1, quantity05.StandardCubicMetersPerHour, StandardCubicMetersPerHourTolerance); + Assert.Equal(1, quantity05.StandardCubicMetersPerHour); Assert.Equal(StandardVolumeFlowUnit.StandardCubicMeterPerHour, quantity05.Unit); var quantity06 = StandardVolumeFlow.From(1, StandardVolumeFlowUnit.StandardCubicMeterPerMinute); - AssertEx.EqualTolerance(1, quantity06.StandardCubicMetersPerMinute, StandardCubicMetersPerMinuteTolerance); + Assert.Equal(1, quantity06.StandardCubicMetersPerMinute); Assert.Equal(StandardVolumeFlowUnit.StandardCubicMeterPerMinute, quantity06.Unit); var quantity07 = StandardVolumeFlow.From(1, StandardVolumeFlowUnit.StandardCubicMeterPerSecond); - AssertEx.EqualTolerance(1, quantity07.StandardCubicMetersPerSecond, StandardCubicMetersPerSecondTolerance); + Assert.Equal(1, quantity07.StandardCubicMetersPerSecond); Assert.Equal(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity07.Unit); var quantity08 = StandardVolumeFlow.From(1, StandardVolumeFlowUnit.StandardLiterPerMinute); - AssertEx.EqualTolerance(1, quantity08.StandardLitersPerMinute, StandardLitersPerMinuteTolerance); + Assert.Equal(1, quantity08.StandardLitersPerMinute); Assert.Equal(StandardVolumeFlowUnit.StandardLiterPerMinute, quantity08.Unit); } @@ -347,131 +365,40 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 sccm", StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute, 4.2)] + [InlineData("en-US", "4.2 scfh", StandardVolumeFlowUnit.StandardCubicFootPerHour, 4.2)] + [InlineData("en-US", "4.2 scfm", StandardVolumeFlowUnit.StandardCubicFootPerMinute, 4.2)] + [InlineData("en-US", "4.2 Sft³/s", StandardVolumeFlowUnit.StandardCubicFootPerSecond, 4.2)] + [InlineData("en-US", "4.2 Sm³/d", StandardVolumeFlowUnit.StandardCubicMeterPerDay, 4.2)] + [InlineData("en-US", "4.2 Sm³/h", StandardVolumeFlowUnit.StandardCubicMeterPerHour, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = StandardVolumeFlow.Parse("1 sccm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.StandardCubicCentimetersPerMinute, StandardCubicCentimetersPerMinuteTolerance); - Assert.Equal(StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = StandardVolumeFlow.Parse("1 scfh", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.StandardCubicFeetPerHour, StandardCubicFeetPerHourTolerance); - Assert.Equal(StandardVolumeFlowUnit.StandardCubicFootPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = StandardVolumeFlow.Parse("1 scfm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.StandardCubicFeetPerMinute, StandardCubicFeetPerMinuteTolerance); - Assert.Equal(StandardVolumeFlowUnit.StandardCubicFootPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = StandardVolumeFlow.Parse("1 Sft³/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.StandardCubicFeetPerSecond, StandardCubicFeetPerSecondTolerance); - Assert.Equal(StandardVolumeFlowUnit.StandardCubicFootPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = StandardVolumeFlow.Parse("1 Sm³/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.StandardCubicMetersPerDay, StandardCubicMetersPerDayTolerance); - Assert.Equal(StandardVolumeFlowUnit.StandardCubicMeterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = StandardVolumeFlow.Parse("1 Sm³/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.StandardCubicMetersPerHour, StandardCubicMetersPerHourTolerance); - Assert.Equal(StandardVolumeFlowUnit.StandardCubicMeterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = StandardVolumeFlow.Parse("1 Sm³/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.StandardCubicMetersPerMinute, StandardCubicMetersPerMinuteTolerance); - Assert.Equal(StandardVolumeFlowUnit.StandardCubicMeterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = StandardVolumeFlow.Parse("1 Sm³/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.StandardCubicMetersPerSecond, StandardCubicMetersPerSecondTolerance); - Assert.Equal(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = StandardVolumeFlow.Parse("1 slm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.StandardLitersPerMinute, StandardLitersPerMinuteTolerance); - Assert.Equal(StandardVolumeFlowUnit.StandardLiterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = StandardVolumeFlow.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 sccm", StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute, 4.2)] + [InlineData("en-US", "4.2 scfh", StandardVolumeFlowUnit.StandardCubicFootPerHour, 4.2)] + [InlineData("en-US", "4.2 scfm", StandardVolumeFlowUnit.StandardCubicFootPerMinute, 4.2)] + [InlineData("en-US", "4.2 Sft³/s", StandardVolumeFlowUnit.StandardCubicFootPerSecond, 4.2)] + [InlineData("en-US", "4.2 Sm³/d", StandardVolumeFlowUnit.StandardCubicMeterPerDay, 4.2)] + [InlineData("en-US", "4.2 Sm³/h", StandardVolumeFlowUnit.StandardCubicMeterPerHour, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(StandardVolumeFlow.TryParse("1 sccm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.StandardCubicCentimetersPerMinute, StandardCubicCentimetersPerMinuteTolerance); - Assert.Equal(StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute, parsed.Unit); - } - - { - Assert.True(StandardVolumeFlow.TryParse("1 scfh", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.StandardCubicFeetPerHour, StandardCubicFeetPerHourTolerance); - Assert.Equal(StandardVolumeFlowUnit.StandardCubicFootPerHour, parsed.Unit); - } - - { - Assert.True(StandardVolumeFlow.TryParse("1 scfm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.StandardCubicFeetPerMinute, StandardCubicFeetPerMinuteTolerance); - Assert.Equal(StandardVolumeFlowUnit.StandardCubicFootPerMinute, parsed.Unit); - } - - { - Assert.True(StandardVolumeFlow.TryParse("1 Sft³/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.StandardCubicFeetPerSecond, StandardCubicFeetPerSecondTolerance); - Assert.Equal(StandardVolumeFlowUnit.StandardCubicFootPerSecond, parsed.Unit); - } - - { - Assert.True(StandardVolumeFlow.TryParse("1 Sm³/d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.StandardCubicMetersPerDay, StandardCubicMetersPerDayTolerance); - Assert.Equal(StandardVolumeFlowUnit.StandardCubicMeterPerDay, parsed.Unit); - } - - { - Assert.True(StandardVolumeFlow.TryParse("1 Sm³/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.StandardCubicMetersPerHour, StandardCubicMetersPerHourTolerance); - Assert.Equal(StandardVolumeFlowUnit.StandardCubicMeterPerHour, parsed.Unit); - } - - { - Assert.True(StandardVolumeFlow.TryParse("1 Sm³/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.StandardCubicMetersPerMinute, StandardCubicMetersPerMinuteTolerance); - Assert.Equal(StandardVolumeFlowUnit.StandardCubicMeterPerMinute, parsed.Unit); - } - - { - Assert.True(StandardVolumeFlow.TryParse("1 Sm³/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.StandardCubicMetersPerSecond, StandardCubicMetersPerSecondTolerance); - Assert.Equal(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, parsed.Unit); - } - - { - Assert.True(StandardVolumeFlow.TryParse("1 slm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.StandardLitersPerMinute, StandardLitersPerMinuteTolerance); - Assert.Equal(StandardVolumeFlowUnit.StandardLiterPerMinute, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(StandardVolumeFlow.TryParse(quantityString, out StandardVolumeFlow parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -612,6 +539,35 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Standa Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute, "sccm")] + [InlineData("en-US", StandardVolumeFlowUnit.StandardCubicFootPerHour, "scfh")] + [InlineData("en-US", StandardVolumeFlowUnit.StandardCubicFootPerMinute, "scfm")] + [InlineData("en-US", StandardVolumeFlowUnit.StandardCubicFootPerSecond, "Sft³/s")] + [InlineData("en-US", StandardVolumeFlowUnit.StandardCubicMeterPerDay, "Sm³/d")] + [InlineData("en-US", StandardVolumeFlowUnit.StandardCubicMeterPerHour, "Sm³/h")] + [InlineData("en-US", StandardVolumeFlowUnit.StandardCubicMeterPerMinute, "Sm³/min")] + [InlineData("en-US", StandardVolumeFlowUnit.StandardCubicMeterPerSecond, "Sm³/s")] + [InlineData("en-US", StandardVolumeFlowUnit.StandardLiterPerMinute, "slm")] + public void GetAbbreviationForCulture(string culture, StandardVolumeFlowUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = StandardVolumeFlow.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(StandardVolumeFlow.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = StandardVolumeFlow.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(StandardVolumeFlowUnit unit) @@ -642,6 +598,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); }); } @@ -665,40 +622,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] @@ -744,8 +703,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); @@ -783,34 +740,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1); - Assert.True(v.Equals(StandardVolumeFlow.FromStandardCubicMetersPerSecond(1), StandardCubicMetersPerSecondTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(StandardVolumeFlow.Zero, StandardCubicMetersPerSecondTolerance, ComparisonType.Relative)); - Assert.True(StandardVolumeFlow.FromStandardCubicMetersPerSecond(100).Equals(StandardVolumeFlow.FromStandardCubicMetersPerSecond(120), 0.3, ComparisonType.Relative)); - Assert.False(StandardVolumeFlow.FromStandardCubicMetersPerSecond(100).Equals(StandardVolumeFlow.FromStandardCubicMetersPerSecond(120), 0.1, ComparisonType.Relative)); + StandardVolumeFlow standardcubicmeterpersecond = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1); + Assert.False(standardcubicmeterpersecond.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1); - Assert.Throws(() => v.Equals(StandardVolumeFlow.FromStandardCubicMetersPerSecond(1), -1, ComparisonType.Relative)); + StandardVolumeFlow standardcubicmeterpersecond = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1); + Assert.False(standardcubicmeterpersecond.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - StandardVolumeFlow standardcubicmeterpersecond = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1); - Assert.False(standardcubicmeterpersecond.Equals(new object())); + var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(firstValue); + var otherQuantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(secondValue); + StandardVolumeFlow maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - StandardVolumeFlow standardcubicmeterpersecond = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1); - Assert.False(standardcubicmeterpersecond.Equals(null)); + var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1); + var negativeTolerance = StandardVolumeFlow.FromStandardCubicMetersPerSecond(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -829,6 +795,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() { @@ -903,158 +881,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(StandardVolumeFlow))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(StandardVolumeFlowUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal(StandardVolumeFlow.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal(StandardVolumeFlow.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal(new {StandardVolumeFlow.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 66863ae5b3..a7b692c648 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureChangeRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureChangeRateTestsBase.g.cs @@ -160,7 +160,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new TemperatureChangeRate(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -173,15 +173,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void TemperatureChangeRate_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + TemperatureChangeRateUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new TemperatureChangeRate(1, TemperatureChangeRateUnit.DegreeCelsiusPerSecond); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(TemperatureChangeRate.Zero, quantityInfo.Zero); Assert.Equal("TemperatureChangeRate", quantityInfo.Name); + Assert.Equal(TemperatureChangeRate.Zero, quantityInfo.Zero); + Assert.Equal(TemperatureChangeRate.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(TemperatureChangeRate.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void TemperatureChangeRateInfo_CreateWithCustomUnitInfos() + { + TemperatureChangeRateUnit[] expectedUnits = [TemperatureChangeRateUnit.DegreeCelsiusPerSecond]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -211,71 +229,71 @@ public void DegreeCelsiusPerSecondToTemperatureChangeRateUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = TemperatureChangeRate.From(1, TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond); - AssertEx.EqualTolerance(1, quantity00.CentidegreesCelsiusPerSecond, CentidegreesCelsiusPerSecondTolerance); + Assert.Equal(1, quantity00.CentidegreesCelsiusPerSecond); Assert.Equal(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond, quantity00.Unit); var quantity01 = TemperatureChangeRate.From(1, TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond); - AssertEx.EqualTolerance(1, quantity01.DecadegreesCelsiusPerSecond, DecadegreesCelsiusPerSecondTolerance); + Assert.Equal(1, quantity01.DecadegreesCelsiusPerSecond); Assert.Equal(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond, quantity01.Unit); var quantity02 = TemperatureChangeRate.From(1, TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond); - AssertEx.EqualTolerance(1, quantity02.DecidegreesCelsiusPerSecond, DecidegreesCelsiusPerSecondTolerance); + Assert.Equal(1, quantity02.DecidegreesCelsiusPerSecond); Assert.Equal(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond, quantity02.Unit); var quantity03 = TemperatureChangeRate.From(1, TemperatureChangeRateUnit.DegreeCelsiusPerHour); - AssertEx.EqualTolerance(1, quantity03.DegreesCelsiusPerHour, DegreesCelsiusPerHourTolerance); + Assert.Equal(1, quantity03.DegreesCelsiusPerHour); Assert.Equal(TemperatureChangeRateUnit.DegreeCelsiusPerHour, quantity03.Unit); var quantity04 = TemperatureChangeRate.From(1, TemperatureChangeRateUnit.DegreeCelsiusPerMinute); - AssertEx.EqualTolerance(1, quantity04.DegreesCelsiusPerMinute, DegreesCelsiusPerMinuteTolerance); + Assert.Equal(1, quantity04.DegreesCelsiusPerMinute); Assert.Equal(TemperatureChangeRateUnit.DegreeCelsiusPerMinute, quantity04.Unit); var quantity05 = TemperatureChangeRate.From(1, TemperatureChangeRateUnit.DegreeCelsiusPerSecond); - AssertEx.EqualTolerance(1, quantity05.DegreesCelsiusPerSecond, DegreesCelsiusPerSecondTolerance); + Assert.Equal(1, quantity05.DegreesCelsiusPerSecond); Assert.Equal(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity05.Unit); var quantity06 = TemperatureChangeRate.From(1, TemperatureChangeRateUnit.DegreeFahrenheitPerHour); - AssertEx.EqualTolerance(1, quantity06.DegreesFahrenheitPerHour, DegreesFahrenheitPerHourTolerance); + Assert.Equal(1, quantity06.DegreesFahrenheitPerHour); Assert.Equal(TemperatureChangeRateUnit.DegreeFahrenheitPerHour, quantity06.Unit); var quantity07 = TemperatureChangeRate.From(1, TemperatureChangeRateUnit.DegreeFahrenheitPerMinute); - AssertEx.EqualTolerance(1, quantity07.DegreesFahrenheitPerMinute, DegreesFahrenheitPerMinuteTolerance); + Assert.Equal(1, quantity07.DegreesFahrenheitPerMinute); Assert.Equal(TemperatureChangeRateUnit.DegreeFahrenheitPerMinute, quantity07.Unit); var quantity08 = TemperatureChangeRate.From(1, TemperatureChangeRateUnit.DegreeFahrenheitPerSecond); - AssertEx.EqualTolerance(1, quantity08.DegreesFahrenheitPerSecond, DegreesFahrenheitPerSecondTolerance); + Assert.Equal(1, quantity08.DegreesFahrenheitPerSecond); Assert.Equal(TemperatureChangeRateUnit.DegreeFahrenheitPerSecond, quantity08.Unit); var quantity09 = TemperatureChangeRate.From(1, TemperatureChangeRateUnit.DegreeKelvinPerHour); - AssertEx.EqualTolerance(1, quantity09.DegreesKelvinPerHour, DegreesKelvinPerHourTolerance); + Assert.Equal(1, quantity09.DegreesKelvinPerHour); Assert.Equal(TemperatureChangeRateUnit.DegreeKelvinPerHour, quantity09.Unit); var quantity10 = TemperatureChangeRate.From(1, TemperatureChangeRateUnit.DegreeKelvinPerMinute); - AssertEx.EqualTolerance(1, quantity10.DegreesKelvinPerMinute, DegreesKelvinPerMinuteTolerance); + Assert.Equal(1, quantity10.DegreesKelvinPerMinute); Assert.Equal(TemperatureChangeRateUnit.DegreeKelvinPerMinute, quantity10.Unit); var quantity11 = TemperatureChangeRate.From(1, TemperatureChangeRateUnit.DegreeKelvinPerSecond); - AssertEx.EqualTolerance(1, quantity11.DegreesKelvinPerSecond, DegreesKelvinPerSecondTolerance); + Assert.Equal(1, quantity11.DegreesKelvinPerSecond); Assert.Equal(TemperatureChangeRateUnit.DegreeKelvinPerSecond, quantity11.Unit); var quantity12 = TemperatureChangeRate.From(1, TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond); - AssertEx.EqualTolerance(1, quantity12.HectodegreesCelsiusPerSecond, HectodegreesCelsiusPerSecondTolerance); + Assert.Equal(1, quantity12.HectodegreesCelsiusPerSecond); Assert.Equal(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond, quantity12.Unit); var quantity13 = TemperatureChangeRate.From(1, TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond); - AssertEx.EqualTolerance(1, quantity13.KilodegreesCelsiusPerSecond, KilodegreesCelsiusPerSecondTolerance); + Assert.Equal(1, quantity13.KilodegreesCelsiusPerSecond); Assert.Equal(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond, quantity13.Unit); var quantity14 = TemperatureChangeRate.From(1, TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond); - AssertEx.EqualTolerance(1, quantity14.MicrodegreesCelsiusPerSecond, MicrodegreesCelsiusPerSecondTolerance); + Assert.Equal(1, quantity14.MicrodegreesCelsiusPerSecond); Assert.Equal(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond, quantity14.Unit); var quantity15 = TemperatureChangeRate.From(1, TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond); - AssertEx.EqualTolerance(1, quantity15.MillidegreesCelsiusPerSecond, MillidegreesCelsiusPerSecondTolerance); + Assert.Equal(1, quantity15.MillidegreesCelsiusPerSecond); Assert.Equal(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond, quantity15.Unit); var quantity16 = TemperatureChangeRate.From(1, TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond); - AssertEx.EqualTolerance(1, quantity16.NanodegreesCelsiusPerSecond, NanodegreesCelsiusPerSecondTolerance); + Assert.Equal(1, quantity16.NanodegreesCelsiusPerSecond); Assert.Equal(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, quantity16.Unit); } @@ -427,235 +445,56 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 c°C/s", TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond, 4.2)] + [InlineData("en-US", "4.2 da°C/s", TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond, 4.2)] + [InlineData("en-US", "4.2 d°C/s", TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond, 4.2)] + [InlineData("en-US", "4.2 °C/h", TemperatureChangeRateUnit.DegreeCelsiusPerHour, 4.2)] + [InlineData("en-US", "4.2 °C/min", TemperatureChangeRateUnit.DegreeCelsiusPerMinute, 4.2)] + [InlineData("en-US", "4.2 °C/s", TemperatureChangeRateUnit.DegreeCelsiusPerSecond, 4.2)] + [InlineData("en-US", "4.2 °F/h", TemperatureChangeRateUnit.DegreeFahrenheitPerHour, 4.2)] + [InlineData("en-US", "4.2 °F/min", TemperatureChangeRateUnit.DegreeFahrenheitPerMinute, 4.2)] + [InlineData("en-US", "4.2 °F/s", TemperatureChangeRateUnit.DegreeFahrenheitPerSecond, 4.2)] + [InlineData("en-US", "4.2 K/h", TemperatureChangeRateUnit.DegreeKelvinPerHour, 4.2)] + [InlineData("en-US", "4.2 K/min", TemperatureChangeRateUnit.DegreeKelvinPerMinute, 4.2)] + [InlineData("en-US", "4.2 K/s", TemperatureChangeRateUnit.DegreeKelvinPerSecond, 4.2)] + [InlineData("en-US", "4.2 h°C/s", TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond, 4.2)] + [InlineData("en-US", "4.2 k°C/s", TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = TemperatureChangeRate.Parse("1 c°C/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentidegreesCelsiusPerSecond, CentidegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = TemperatureChangeRate.Parse("1 da°C/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecadegreesCelsiusPerSecond, DecadegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = TemperatureChangeRate.Parse("1 d°C/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecidegreesCelsiusPerSecond, DecidegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = TemperatureChangeRate.Parse("1 °C/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesCelsiusPerHour, DegreesCelsiusPerHourTolerance); - Assert.Equal(TemperatureChangeRateUnit.DegreeCelsiusPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = TemperatureChangeRate.Parse("1 °C/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesCelsiusPerMinute, DegreesCelsiusPerMinuteTolerance); - Assert.Equal(TemperatureChangeRateUnit.DegreeCelsiusPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = TemperatureChangeRate.Parse("1 °C/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesCelsiusPerSecond, DegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = TemperatureChangeRate.Parse("1 °F/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesFahrenheitPerHour, DegreesFahrenheitPerHourTolerance); - Assert.Equal(TemperatureChangeRateUnit.DegreeFahrenheitPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = TemperatureChangeRate.Parse("1 °F/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesFahrenheitPerMinute, DegreesFahrenheitPerMinuteTolerance); - Assert.Equal(TemperatureChangeRateUnit.DegreeFahrenheitPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = TemperatureChangeRate.Parse("1 °F/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesFahrenheitPerSecond, DegreesFahrenheitPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.DegreeFahrenheitPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = TemperatureChangeRate.Parse("1 K/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesKelvinPerHour, DegreesKelvinPerHourTolerance); - Assert.Equal(TemperatureChangeRateUnit.DegreeKelvinPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = TemperatureChangeRate.Parse("1 K/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesKelvinPerMinute, DegreesKelvinPerMinuteTolerance); - Assert.Equal(TemperatureChangeRateUnit.DegreeKelvinPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = TemperatureChangeRate.Parse("1 K/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesKelvinPerSecond, DegreesKelvinPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.DegreeKelvinPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = TemperatureChangeRate.Parse("1 h°C/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.HectodegreesCelsiusPerSecond, HectodegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = TemperatureChangeRate.Parse("1 k°C/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilodegreesCelsiusPerSecond, KilodegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = TemperatureChangeRate.Parse("1 µ°C/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrodegreesCelsiusPerSecond, MicrodegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = TemperatureChangeRate.Parse("1 m°C/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillidegreesCelsiusPerSecond, MillidegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = TemperatureChangeRate.Parse("1 n°C/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanodegreesCelsiusPerSecond, NanodegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = TemperatureChangeRate.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 c°C/s", TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond, 4.2)] + [InlineData("en-US", "4.2 da°C/s", TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond, 4.2)] + [InlineData("en-US", "4.2 d°C/s", TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond, 4.2)] + [InlineData("en-US", "4.2 °C/h", TemperatureChangeRateUnit.DegreeCelsiusPerHour, 4.2)] + [InlineData("en-US", "4.2 °C/min", TemperatureChangeRateUnit.DegreeCelsiusPerMinute, 4.2)] + [InlineData("en-US", "4.2 °C/s", TemperatureChangeRateUnit.DegreeCelsiusPerSecond, 4.2)] + [InlineData("en-US", "4.2 °F/h", TemperatureChangeRateUnit.DegreeFahrenheitPerHour, 4.2)] + [InlineData("en-US", "4.2 °F/min", TemperatureChangeRateUnit.DegreeFahrenheitPerMinute, 4.2)] + [InlineData("en-US", "4.2 °F/s", TemperatureChangeRateUnit.DegreeFahrenheitPerSecond, 4.2)] + [InlineData("en-US", "4.2 K/h", TemperatureChangeRateUnit.DegreeKelvinPerHour, 4.2)] + [InlineData("en-US", "4.2 K/min", TemperatureChangeRateUnit.DegreeKelvinPerMinute, 4.2)] + [InlineData("en-US", "4.2 K/s", TemperatureChangeRateUnit.DegreeKelvinPerSecond, 4.2)] + [InlineData("en-US", "4.2 h°C/s", TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond, 4.2)] + [InlineData("en-US", "4.2 k°C/s", TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(TemperatureChangeRate.TryParse("1 c°C/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentidegreesCelsiusPerSecond, CentidegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond, parsed.Unit); - } - - { - Assert.True(TemperatureChangeRate.TryParse("1 da°C/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecadegreesCelsiusPerSecond, DecadegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond, parsed.Unit); - } - - { - Assert.True(TemperatureChangeRate.TryParse("1 d°C/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecidegreesCelsiusPerSecond, DecidegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond, parsed.Unit); - } - - { - Assert.True(TemperatureChangeRate.TryParse("1 °C/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesCelsiusPerHour, DegreesCelsiusPerHourTolerance); - Assert.Equal(TemperatureChangeRateUnit.DegreeCelsiusPerHour, parsed.Unit); - } - - { - Assert.True(TemperatureChangeRate.TryParse("1 °C/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesCelsiusPerMinute, DegreesCelsiusPerMinuteTolerance); - Assert.Equal(TemperatureChangeRateUnit.DegreeCelsiusPerMinute, parsed.Unit); - } - - { - Assert.True(TemperatureChangeRate.TryParse("1 °C/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesCelsiusPerSecond, DegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, parsed.Unit); - } - - { - Assert.True(TemperatureChangeRate.TryParse("1 °F/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesFahrenheitPerHour, DegreesFahrenheitPerHourTolerance); - Assert.Equal(TemperatureChangeRateUnit.DegreeFahrenheitPerHour, parsed.Unit); - } - - { - Assert.True(TemperatureChangeRate.TryParse("1 °F/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesFahrenheitPerMinute, DegreesFahrenheitPerMinuteTolerance); - Assert.Equal(TemperatureChangeRateUnit.DegreeFahrenheitPerMinute, parsed.Unit); - } - - { - Assert.True(TemperatureChangeRate.TryParse("1 °F/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesFahrenheitPerSecond, DegreesFahrenheitPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.DegreeFahrenheitPerSecond, parsed.Unit); - } - - { - Assert.True(TemperatureChangeRate.TryParse("1 K/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesKelvinPerHour, DegreesKelvinPerHourTolerance); - Assert.Equal(TemperatureChangeRateUnit.DegreeKelvinPerHour, parsed.Unit); - } - - { - Assert.True(TemperatureChangeRate.TryParse("1 K/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesKelvinPerMinute, DegreesKelvinPerMinuteTolerance); - Assert.Equal(TemperatureChangeRateUnit.DegreeKelvinPerMinute, parsed.Unit); - } - - { - Assert.True(TemperatureChangeRate.TryParse("1 K/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesKelvinPerSecond, DegreesKelvinPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.DegreeKelvinPerSecond, parsed.Unit); - } - - { - Assert.True(TemperatureChangeRate.TryParse("1 h°C/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HectodegreesCelsiusPerSecond, HectodegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond, parsed.Unit); - } - - { - Assert.True(TemperatureChangeRate.TryParse("1 k°C/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilodegreesCelsiusPerSecond, KilodegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond, parsed.Unit); - } - - { - Assert.True(TemperatureChangeRate.TryParse("1 µ°C/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrodegreesCelsiusPerSecond, MicrodegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond, parsed.Unit); - } - - { - Assert.True(TemperatureChangeRate.TryParse("1 m°C/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillidegreesCelsiusPerSecond, MillidegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond, parsed.Unit); - } - - { - Assert.True(TemperatureChangeRate.TryParse("1 n°C/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanodegreesCelsiusPerSecond, NanodegreesCelsiusPerSecondTolerance); - Assert.Equal(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(TemperatureChangeRate.TryParse(quantityString, out TemperatureChangeRate parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -860,6 +699,43 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Temper Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond, "c°C/s")] + [InlineData("en-US", TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond, "da°C/s")] + [InlineData("en-US", TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond, "d°C/s")] + [InlineData("en-US", TemperatureChangeRateUnit.DegreeCelsiusPerHour, "°C/h")] + [InlineData("en-US", TemperatureChangeRateUnit.DegreeCelsiusPerMinute, "°C/min")] + [InlineData("en-US", TemperatureChangeRateUnit.DegreeCelsiusPerSecond, "°C/s")] + [InlineData("en-US", TemperatureChangeRateUnit.DegreeFahrenheitPerHour, "°F/h")] + [InlineData("en-US", TemperatureChangeRateUnit.DegreeFahrenheitPerMinute, "°F/min")] + [InlineData("en-US", TemperatureChangeRateUnit.DegreeFahrenheitPerSecond, "°F/s")] + [InlineData("en-US", TemperatureChangeRateUnit.DegreeKelvinPerHour, "K/h")] + [InlineData("en-US", TemperatureChangeRateUnit.DegreeKelvinPerMinute, "K/min")] + [InlineData("en-US", TemperatureChangeRateUnit.DegreeKelvinPerSecond, "K/s")] + [InlineData("en-US", TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond, "h°C/s")] + [InlineData("en-US", TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond, "k°C/s")] + [InlineData("en-US", TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond, "µ°C/s")] + [InlineData("en-US", TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond, "m°C/s")] + [InlineData("en-US", TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, "n°C/s")] + public void GetAbbreviationForCulture(string culture, TemperatureChangeRateUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = TemperatureChangeRate.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(TemperatureChangeRate.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = TemperatureChangeRate.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(TemperatureChangeRateUnit unit) @@ -890,6 +766,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); }); } @@ -913,48 +790,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] @@ -1000,8 +879,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); @@ -1038,23 +915,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1); - Assert.True(v.Equals(TemperatureChangeRate.FromDegreesCelsiusPerSecond(1), DegreesCelsiusPerSecondTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(TemperatureChangeRate.Zero, DegreesCelsiusPerSecondTolerance, ComparisonType.Relative)); - Assert.True(TemperatureChangeRate.FromDegreesCelsiusPerSecond(100).Equals(TemperatureChangeRate.FromDegreesCelsiusPerSecond(120), 0.3, ComparisonType.Relative)); - Assert.False(TemperatureChangeRate.FromDegreesCelsiusPerSecond(100).Equals(TemperatureChangeRate.FromDegreesCelsiusPerSecond(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1); - Assert.Throws(() => v.Equals(TemperatureChangeRate.FromDegreesCelsiusPerSecond(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1069,6 +929,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(degreecelsiuspersecond.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1); + var negativeTolerance = TemperatureChangeRate.FromDegreesCelsiusPerSecond(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1085,6 +971,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() { @@ -1175,158 +1073,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(TemperatureChangeRate))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(TemperatureChangeRateUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal(TemperatureChangeRate.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal(TemperatureChangeRate.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal(new {TemperatureChangeRate.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 ca18646750..ebe1478be5 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureDeltaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureDeltaTestsBase.g.cs @@ -128,7 +128,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new TemperatureDelta(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -141,15 +141,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void TemperatureDelta_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + TemperatureDeltaUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new TemperatureDelta(1, TemperatureDeltaUnit.Kelvin); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(TemperatureDelta.Zero, quantityInfo.Zero); Assert.Equal("TemperatureDelta", quantityInfo.Name); + Assert.Equal(TemperatureDelta.Zero, quantityInfo.Zero); + Assert.Equal(TemperatureDelta.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(TemperatureDelta.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -171,39 +189,39 @@ public void KelvinToTemperatureDeltaUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = TemperatureDelta.From(1, TemperatureDeltaUnit.DegreeCelsius); - AssertEx.EqualTolerance(1, quantity00.DegreesCelsius, DegreesCelsiusTolerance); + Assert.Equal(1, quantity00.DegreesCelsius); Assert.Equal(TemperatureDeltaUnit.DegreeCelsius, quantity00.Unit); var quantity01 = TemperatureDelta.From(1, TemperatureDeltaUnit.DegreeDelisle); - AssertEx.EqualTolerance(1, quantity01.DegreesDelisle, DegreesDelisleTolerance); + Assert.Equal(1, quantity01.DegreesDelisle); Assert.Equal(TemperatureDeltaUnit.DegreeDelisle, quantity01.Unit); var quantity02 = TemperatureDelta.From(1, TemperatureDeltaUnit.DegreeFahrenheit); - AssertEx.EqualTolerance(1, quantity02.DegreesFahrenheit, DegreesFahrenheitTolerance); + Assert.Equal(1, quantity02.DegreesFahrenheit); Assert.Equal(TemperatureDeltaUnit.DegreeFahrenheit, quantity02.Unit); var quantity03 = TemperatureDelta.From(1, TemperatureDeltaUnit.DegreeNewton); - AssertEx.EqualTolerance(1, quantity03.DegreesNewton, DegreesNewtonTolerance); + Assert.Equal(1, quantity03.DegreesNewton); Assert.Equal(TemperatureDeltaUnit.DegreeNewton, quantity03.Unit); var quantity04 = TemperatureDelta.From(1, TemperatureDeltaUnit.DegreeRankine); - AssertEx.EqualTolerance(1, quantity04.DegreesRankine, DegreesRankineTolerance); + Assert.Equal(1, quantity04.DegreesRankine); Assert.Equal(TemperatureDeltaUnit.DegreeRankine, quantity04.Unit); var quantity05 = TemperatureDelta.From(1, TemperatureDeltaUnit.DegreeReaumur); - AssertEx.EqualTolerance(1, quantity05.DegreesReaumur, DegreesReaumurTolerance); + Assert.Equal(1, quantity05.DegreesReaumur); Assert.Equal(TemperatureDeltaUnit.DegreeReaumur, quantity05.Unit); var quantity06 = TemperatureDelta.From(1, TemperatureDeltaUnit.DegreeRoemer); - AssertEx.EqualTolerance(1, quantity06.DegreesRoemer, DegreesRoemerTolerance); + Assert.Equal(1, quantity06.DegreesRoemer); Assert.Equal(TemperatureDeltaUnit.DegreeRoemer, quantity06.Unit); var quantity07 = TemperatureDelta.From(1, TemperatureDeltaUnit.Kelvin); - AssertEx.EqualTolerance(1, quantity07.Kelvins, KelvinsTolerance); + Assert.Equal(1, quantity07.Kelvins); Assert.Equal(TemperatureDeltaUnit.Kelvin, quantity07.Unit); var quantity08 = TemperatureDelta.From(1, TemperatureDeltaUnit.MillidegreeCelsius); - AssertEx.EqualTolerance(1, quantity08.MillidegreesCelsius, MillidegreesCelsiusTolerance); + Assert.Equal(1, quantity08.MillidegreesCelsius); Assert.Equal(TemperatureDeltaUnit.MillidegreeCelsius, quantity08.Unit); } @@ -347,131 +365,40 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 ∆°C", TemperatureDeltaUnit.DegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 ∆°De", TemperatureDeltaUnit.DegreeDelisle, 4.2)] + [InlineData("en-US", "4.2 ∆°F", TemperatureDeltaUnit.DegreeFahrenheit, 4.2)] + [InlineData("en-US", "4.2 ∆°N", TemperatureDeltaUnit.DegreeNewton, 4.2)] + [InlineData("en-US", "4.2 ∆°R", TemperatureDeltaUnit.DegreeRankine, 4.2)] + [InlineData("en-US", "4.2 ∆°Ré", TemperatureDeltaUnit.DegreeReaumur, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = TemperatureDelta.Parse("1 ∆°C", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesCelsius, DegreesCelsiusTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeCelsius, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = TemperatureDelta.Parse("1 ∆°De", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesDelisle, DegreesDelisleTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeDelisle, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = TemperatureDelta.Parse("1 ∆°F", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesFahrenheit, DegreesFahrenheitTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeFahrenheit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = TemperatureDelta.Parse("1 ∆°N", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesNewton, DegreesNewtonTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeNewton, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = TemperatureDelta.Parse("1 ∆°R", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesRankine, DegreesRankineTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeRankine, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = TemperatureDelta.Parse("1 ∆°Ré", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesReaumur, DegreesReaumurTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeReaumur, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = TemperatureDelta.Parse("1 ∆°Rø", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesRoemer, DegreesRoemerTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeRoemer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = TemperatureDelta.Parse("1 ∆K", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kelvins, KelvinsTolerance); - Assert.Equal(TemperatureDeltaUnit.Kelvin, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = TemperatureDelta.Parse("1 ∆m°C", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillidegreesCelsius, MillidegreesCelsiusTolerance); - Assert.Equal(TemperatureDeltaUnit.MillidegreeCelsius, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = TemperatureDelta.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 ∆°C", TemperatureDeltaUnit.DegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 ∆°De", TemperatureDeltaUnit.DegreeDelisle, 4.2)] + [InlineData("en-US", "4.2 ∆°F", TemperatureDeltaUnit.DegreeFahrenheit, 4.2)] + [InlineData("en-US", "4.2 ∆°N", TemperatureDeltaUnit.DegreeNewton, 4.2)] + [InlineData("en-US", "4.2 ∆°R", TemperatureDeltaUnit.DegreeRankine, 4.2)] + [InlineData("en-US", "4.2 ∆°Ré", TemperatureDeltaUnit.DegreeReaumur, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(TemperatureDelta.TryParse("1 ∆°C", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesCelsius, DegreesCelsiusTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeCelsius, parsed.Unit); - } - - { - Assert.True(TemperatureDelta.TryParse("1 ∆°De", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesDelisle, DegreesDelisleTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeDelisle, parsed.Unit); - } - - { - Assert.True(TemperatureDelta.TryParse("1 ∆°F", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesFahrenheit, DegreesFahrenheitTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeFahrenheit, parsed.Unit); - } - - { - Assert.True(TemperatureDelta.TryParse("1 ∆°N", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesNewton, DegreesNewtonTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeNewton, parsed.Unit); - } - - { - Assert.True(TemperatureDelta.TryParse("1 ∆°R", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesRankine, DegreesRankineTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeRankine, parsed.Unit); - } - - { - Assert.True(TemperatureDelta.TryParse("1 ∆°Ré", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesReaumur, DegreesReaumurTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeReaumur, parsed.Unit); - } - - { - Assert.True(TemperatureDelta.TryParse("1 ∆°Rø", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesRoemer, DegreesRoemerTolerance); - Assert.Equal(TemperatureDeltaUnit.DegreeRoemer, parsed.Unit); - } - - { - Assert.True(TemperatureDelta.TryParse("1 ∆K", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kelvins, KelvinsTolerance); - Assert.Equal(TemperatureDeltaUnit.Kelvin, parsed.Unit); - } - - { - Assert.True(TemperatureDelta.TryParse("1 ∆m°C", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillidegreesCelsius, MillidegreesCelsiusTolerance); - Assert.Equal(TemperatureDeltaUnit.MillidegreeCelsius, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(TemperatureDelta.TryParse(quantityString, out TemperatureDelta parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -612,6 +539,35 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Temper Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", TemperatureDeltaUnit.DegreeCelsius, "∆°C")] + [InlineData("en-US", TemperatureDeltaUnit.DegreeDelisle, "∆°De")] + [InlineData("en-US", TemperatureDeltaUnit.DegreeFahrenheit, "∆°F")] + [InlineData("en-US", TemperatureDeltaUnit.DegreeNewton, "∆°N")] + [InlineData("en-US", TemperatureDeltaUnit.DegreeRankine, "∆°R")] + [InlineData("en-US", TemperatureDeltaUnit.DegreeReaumur, "∆°Ré")] + [InlineData("en-US", TemperatureDeltaUnit.DegreeRoemer, "∆°Rø")] + [InlineData("en-US", TemperatureDeltaUnit.Kelvin, "∆K")] + [InlineData("en-US", TemperatureDeltaUnit.MillidegreeCelsius, "∆m°C")] + public void GetAbbreviationForCulture(string culture, TemperatureDeltaUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = TemperatureDelta.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(TemperatureDelta.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = TemperatureDelta.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(TemperatureDeltaUnit unit) @@ -642,6 +598,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); }); } @@ -665,40 +622,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] @@ -744,8 +703,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); @@ -783,34 +740,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = TemperatureDelta.FromKelvins(1); - Assert.True(v.Equals(TemperatureDelta.FromKelvins(1), KelvinsTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(TemperatureDelta.Zero, KelvinsTolerance, ComparisonType.Relative)); - Assert.True(TemperatureDelta.FromKelvins(100).Equals(TemperatureDelta.FromKelvins(120), 0.3, ComparisonType.Relative)); - Assert.False(TemperatureDelta.FromKelvins(100).Equals(TemperatureDelta.FromKelvins(120), 0.1, ComparisonType.Relative)); + TemperatureDelta kelvin = TemperatureDelta.FromKelvins(1); + Assert.False(kelvin.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = TemperatureDelta.FromKelvins(1); - Assert.Throws(() => v.Equals(TemperatureDelta.FromKelvins(1), -1, ComparisonType.Relative)); + TemperatureDelta kelvin = TemperatureDelta.FromKelvins(1); + Assert.False(kelvin.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - TemperatureDelta kelvin = TemperatureDelta.FromKelvins(1); - Assert.False(kelvin.Equals(new object())); + var quantity = TemperatureDelta.FromKelvins(firstValue); + var otherQuantity = TemperatureDelta.FromKelvins(secondValue); + TemperatureDelta maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - TemperatureDelta kelvin = TemperatureDelta.FromKelvins(1); - Assert.False(kelvin.Equals(null)); + var quantity = TemperatureDelta.FromKelvins(1); + var negativeTolerance = TemperatureDelta.FromKelvins(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -829,6 +795,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() { @@ -903,158 +881,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(TemperatureDelta))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(TemperatureDeltaUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal(TemperatureDelta.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal(TemperatureDelta.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal(new {TemperatureDelta.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 9744646ac9..507fb4a147 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureGradientTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureGradientTestsBase.g.cs @@ -108,7 +108,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new TemperatureGradient(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -121,15 +121,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void TemperatureGradient_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + TemperatureGradientUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new TemperatureGradient(1, TemperatureGradientUnit.KelvinPerMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(TemperatureGradient.Zero, quantityInfo.Zero); Assert.Equal("TemperatureGradient", quantityInfo.Name); + Assert.Equal(TemperatureGradient.Zero, quantityInfo.Zero); + Assert.Equal(TemperatureGradient.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(TemperatureGradient.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void TemperatureGradientInfo_CreateWithCustomUnitInfos() + { + TemperatureGradientUnit[] expectedUnits = [TemperatureGradientUnit.KelvinPerMeter]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -146,19 +164,19 @@ public void KelvinPerMeterToTemperatureGradientUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = TemperatureGradient.From(1, TemperatureGradientUnit.DegreeCelsiusPerKilometer); - AssertEx.EqualTolerance(1, quantity00.DegreesCelsiusPerKilometer, DegreesCelsiusPerKilometerTolerance); + Assert.Equal(1, quantity00.DegreesCelsiusPerKilometer); Assert.Equal(TemperatureGradientUnit.DegreeCelsiusPerKilometer, quantity00.Unit); var quantity01 = TemperatureGradient.From(1, TemperatureGradientUnit.DegreeCelsiusPerMeter); - AssertEx.EqualTolerance(1, quantity01.DegreesCelsiusPerMeter, DegreesCelsiusPerMeterTolerance); + Assert.Equal(1, quantity01.DegreesCelsiusPerMeter); Assert.Equal(TemperatureGradientUnit.DegreeCelsiusPerMeter, quantity01.Unit); var quantity02 = TemperatureGradient.From(1, TemperatureGradientUnit.DegreeFahrenheitPerFoot); - AssertEx.EqualTolerance(1, quantity02.DegreesFahrenheitPerFoot, DegreesFahrenheitPerFootTolerance); + Assert.Equal(1, quantity02.DegreesFahrenheitPerFoot); Assert.Equal(TemperatureGradientUnit.DegreeFahrenheitPerFoot, quantity02.Unit); var quantity03 = TemperatureGradient.From(1, TemperatureGradientUnit.KelvinPerMeter); - AssertEx.EqualTolerance(1, quantity03.KelvinsPerMeter, KelvinsPerMeterTolerance); + Assert.Equal(1, quantity03.KelvinsPerMeter); Assert.Equal(TemperatureGradientUnit.KelvinPerMeter, quantity03.Unit); } @@ -297,66 +315,30 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 ∆°C/km", TemperatureGradientUnit.DegreeCelsiusPerKilometer, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = TemperatureGradient.Parse("1 ∆°C/km", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesCelsiusPerKilometer, DegreesCelsiusPerKilometerTolerance); - Assert.Equal(TemperatureGradientUnit.DegreeCelsiusPerKilometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = TemperatureGradient.Parse("1 ∆°C/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesCelsiusPerMeter, DegreesCelsiusPerMeterTolerance); - Assert.Equal(TemperatureGradientUnit.DegreeCelsiusPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = TemperatureGradient.Parse("1 ∆°F/ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesFahrenheitPerFoot, DegreesFahrenheitPerFootTolerance); - Assert.Equal(TemperatureGradientUnit.DegreeFahrenheitPerFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = TemperatureGradient.Parse("1 ∆°K/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KelvinsPerMeter, KelvinsPerMeterTolerance); - Assert.Equal(TemperatureGradientUnit.KelvinPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = TemperatureGradient.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 ∆°C/km", TemperatureGradientUnit.DegreeCelsiusPerKilometer, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(TemperatureGradient.TryParse("1 ∆°C/km", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesCelsiusPerKilometer, DegreesCelsiusPerKilometerTolerance); - Assert.Equal(TemperatureGradientUnit.DegreeCelsiusPerKilometer, parsed.Unit); - } - - { - Assert.True(TemperatureGradient.TryParse("1 ∆°C/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesCelsiusPerMeter, DegreesCelsiusPerMeterTolerance); - Assert.Equal(TemperatureGradientUnit.DegreeCelsiusPerMeter, parsed.Unit); - } - - { - Assert.True(TemperatureGradient.TryParse("1 ∆°F/ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesFahrenheitPerFoot, DegreesFahrenheitPerFootTolerance); - Assert.Equal(TemperatureGradientUnit.DegreeFahrenheitPerFoot, parsed.Unit); - } - - { - Assert.True(TemperatureGradient.TryParse("1 ∆°K/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KelvinsPerMeter, KelvinsPerMeterTolerance); - Assert.Equal(TemperatureGradientUnit.KelvinPerMeter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(TemperatureGradient.TryParse(quantityString, out TemperatureGradient parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -457,6 +439,30 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Temper Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", TemperatureGradientUnit.DegreeCelsiusPerKilometer, "∆°C/km")] + [InlineData("en-US", TemperatureGradientUnit.DegreeCelsiusPerMeter, "∆°C/m")] + [InlineData("en-US", TemperatureGradientUnit.DegreeFahrenheitPerFoot, "∆°F/ft")] + [InlineData("en-US", TemperatureGradientUnit.KelvinPerMeter, "∆°K/m")] + public void GetAbbreviationForCulture(string culture, TemperatureGradientUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = TemperatureGradient.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(TemperatureGradient.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = TemperatureGradient.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(TemperatureGradientUnit unit) @@ -487,6 +493,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); }); } @@ -510,35 +517,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] @@ -584,8 +593,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); @@ -623,34 +630,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = TemperatureGradient.FromKelvinsPerMeter(1); - Assert.True(v.Equals(TemperatureGradient.FromKelvinsPerMeter(1), KelvinsPerMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(TemperatureGradient.Zero, KelvinsPerMeterTolerance, ComparisonType.Relative)); - Assert.True(TemperatureGradient.FromKelvinsPerMeter(100).Equals(TemperatureGradient.FromKelvinsPerMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(TemperatureGradient.FromKelvinsPerMeter(100).Equals(TemperatureGradient.FromKelvinsPerMeter(120), 0.1, ComparisonType.Relative)); + TemperatureGradient kelvinpermeter = TemperatureGradient.FromKelvinsPerMeter(1); + Assert.False(kelvinpermeter.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = TemperatureGradient.FromKelvinsPerMeter(1); - Assert.Throws(() => v.Equals(TemperatureGradient.FromKelvinsPerMeter(1), -1, ComparisonType.Relative)); + TemperatureGradient kelvinpermeter = TemperatureGradient.FromKelvinsPerMeter(1); + Assert.False(kelvinpermeter.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - TemperatureGradient kelvinpermeter = TemperatureGradient.FromKelvinsPerMeter(1); - Assert.False(kelvinpermeter.Equals(new object())); + var quantity = TemperatureGradient.FromKelvinsPerMeter(firstValue); + var otherQuantity = TemperatureGradient.FromKelvinsPerMeter(secondValue); + TemperatureGradient maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - TemperatureGradient kelvinpermeter = TemperatureGradient.FromKelvinsPerMeter(1); - Assert.False(kelvinpermeter.Equals(null)); + var quantity = TemperatureGradient.FromKelvinsPerMeter(1); + var negativeTolerance = TemperatureGradient.FromKelvinsPerMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -669,6 +685,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() { @@ -733,158 +761,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(TemperatureGradient))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(TemperatureGradientUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal(TemperatureGradient.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal(TemperatureGradient.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal(new {TemperatureGradient.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 234ccaf84b..ed3bb2a3d1 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureTestsBase.g.cs @@ -132,7 +132,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Temperature(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -145,15 +145,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Temperature_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + TemperatureUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Temperature(1, TemperatureUnit.Kelvin); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Temperature.Zero, quantityInfo.Zero); Assert.Equal("Temperature", quantityInfo.Name); + Assert.Equal(Temperature.Zero, quantityInfo.Zero); + Assert.Equal(Temperature.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Temperature.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -176,43 +194,43 @@ public void KelvinToTemperatureUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Temperature.From(1, TemperatureUnit.DegreeCelsius); - AssertEx.EqualTolerance(1, quantity00.DegreesCelsius, DegreesCelsiusTolerance); + Assert.Equal(1, quantity00.DegreesCelsius); Assert.Equal(TemperatureUnit.DegreeCelsius, quantity00.Unit); var quantity01 = Temperature.From(1, TemperatureUnit.DegreeDelisle); - AssertEx.EqualTolerance(1, quantity01.DegreesDelisle, DegreesDelisleTolerance); + Assert.Equal(1, quantity01.DegreesDelisle); Assert.Equal(TemperatureUnit.DegreeDelisle, quantity01.Unit); var quantity02 = Temperature.From(1, TemperatureUnit.DegreeFahrenheit); - AssertEx.EqualTolerance(1, quantity02.DegreesFahrenheit, DegreesFahrenheitTolerance); + Assert.Equal(1, quantity02.DegreesFahrenheit); Assert.Equal(TemperatureUnit.DegreeFahrenheit, quantity02.Unit); var quantity03 = Temperature.From(1, TemperatureUnit.DegreeNewton); - AssertEx.EqualTolerance(1, quantity03.DegreesNewton, DegreesNewtonTolerance); + Assert.Equal(1, quantity03.DegreesNewton); Assert.Equal(TemperatureUnit.DegreeNewton, quantity03.Unit); var quantity04 = Temperature.From(1, TemperatureUnit.DegreeRankine); - AssertEx.EqualTolerance(1, quantity04.DegreesRankine, DegreesRankineTolerance); + Assert.Equal(1, quantity04.DegreesRankine); Assert.Equal(TemperatureUnit.DegreeRankine, quantity04.Unit); var quantity05 = Temperature.From(1, TemperatureUnit.DegreeReaumur); - AssertEx.EqualTolerance(1, quantity05.DegreesReaumur, DegreesReaumurTolerance); + Assert.Equal(1, quantity05.DegreesReaumur); Assert.Equal(TemperatureUnit.DegreeReaumur, quantity05.Unit); var quantity06 = Temperature.From(1, TemperatureUnit.DegreeRoemer); - AssertEx.EqualTolerance(1, quantity06.DegreesRoemer, DegreesRoemerTolerance); + Assert.Equal(1, quantity06.DegreesRoemer); Assert.Equal(TemperatureUnit.DegreeRoemer, quantity06.Unit); var quantity07 = Temperature.From(1, TemperatureUnit.Kelvin); - AssertEx.EqualTolerance(1, quantity07.Kelvins, KelvinsTolerance); + Assert.Equal(1, quantity07.Kelvins); Assert.Equal(TemperatureUnit.Kelvin, quantity07.Unit); var quantity08 = Temperature.From(1, TemperatureUnit.MillidegreeCelsius); - AssertEx.EqualTolerance(1, quantity08.MillidegreesCelsius, MillidegreesCelsiusTolerance); + Assert.Equal(1, quantity08.MillidegreesCelsius); Assert.Equal(TemperatureUnit.MillidegreeCelsius, quantity08.Unit); var quantity09 = Temperature.From(1, TemperatureUnit.SolarTemperature); - AssertEx.EqualTolerance(1, quantity09.SolarTemperatures, SolarTemperaturesTolerance); + Assert.Equal(1, quantity09.SolarTemperatures); Assert.Equal(TemperatureUnit.SolarTemperature, quantity09.Unit); } @@ -357,144 +375,42 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 °C", TemperatureUnit.DegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 °De", TemperatureUnit.DegreeDelisle, 4.2)] + [InlineData("en-US", "4.2 °F", TemperatureUnit.DegreeFahrenheit, 4.2)] + [InlineData("en-US", "4.2 °N", TemperatureUnit.DegreeNewton, 4.2)] + [InlineData("en-US", "4.2 °R", TemperatureUnit.DegreeRankine, 4.2)] + [InlineData("en-US", "4.2 °Ré", TemperatureUnit.DegreeReaumur, 4.2)] + [InlineData("en-US", "4.2 °Rø", TemperatureUnit.DegreeRoemer, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = Temperature.Parse("1 °C", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesCelsius, DegreesCelsiusTolerance); - Assert.Equal(TemperatureUnit.DegreeCelsius, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Temperature.Parse("1 °De", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesDelisle, DegreesDelisleTolerance); - Assert.Equal(TemperatureUnit.DegreeDelisle, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Temperature.Parse("1 °F", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesFahrenheit, DegreesFahrenheitTolerance); - Assert.Equal(TemperatureUnit.DegreeFahrenheit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Temperature.Parse("1 °N", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesNewton, DegreesNewtonTolerance); - Assert.Equal(TemperatureUnit.DegreeNewton, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Temperature.Parse("1 °R", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesRankine, DegreesRankineTolerance); - Assert.Equal(TemperatureUnit.DegreeRankine, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Temperature.Parse("1 °Ré", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesReaumur, DegreesReaumurTolerance); - Assert.Equal(TemperatureUnit.DegreeReaumur, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Temperature.Parse("1 °Rø", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DegreesRoemer, DegreesRoemerTolerance); - Assert.Equal(TemperatureUnit.DegreeRoemer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Temperature.Parse("1 K", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kelvins, KelvinsTolerance); - Assert.Equal(TemperatureUnit.Kelvin, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Temperature.Parse("1 m°C", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillidegreesCelsius, MillidegreesCelsiusTolerance); - Assert.Equal(TemperatureUnit.MillidegreeCelsius, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Temperature.Parse("1 T⊙", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SolarTemperatures, SolarTemperaturesTolerance); - Assert.Equal(TemperatureUnit.SolarTemperature, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Temperature.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 °C", TemperatureUnit.DegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 °De", TemperatureUnit.DegreeDelisle, 4.2)] + [InlineData("en-US", "4.2 °F", TemperatureUnit.DegreeFahrenheit, 4.2)] + [InlineData("en-US", "4.2 °N", TemperatureUnit.DegreeNewton, 4.2)] + [InlineData("en-US", "4.2 °R", TemperatureUnit.DegreeRankine, 4.2)] + [InlineData("en-US", "4.2 °Ré", TemperatureUnit.DegreeReaumur, 4.2)] + [InlineData("en-US", "4.2 °Rø", TemperatureUnit.DegreeRoemer, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(Temperature.TryParse("1 °C", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesCelsius, DegreesCelsiusTolerance); - Assert.Equal(TemperatureUnit.DegreeCelsius, parsed.Unit); - } - - { - Assert.True(Temperature.TryParse("1 °De", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesDelisle, DegreesDelisleTolerance); - Assert.Equal(TemperatureUnit.DegreeDelisle, parsed.Unit); - } - - { - Assert.True(Temperature.TryParse("1 °F", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesFahrenheit, DegreesFahrenheitTolerance); - Assert.Equal(TemperatureUnit.DegreeFahrenheit, parsed.Unit); - } - - { - Assert.True(Temperature.TryParse("1 °N", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesNewton, DegreesNewtonTolerance); - Assert.Equal(TemperatureUnit.DegreeNewton, parsed.Unit); - } - - { - Assert.True(Temperature.TryParse("1 °R", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesRankine, DegreesRankineTolerance); - Assert.Equal(TemperatureUnit.DegreeRankine, parsed.Unit); - } - - { - Assert.True(Temperature.TryParse("1 °Ré", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesReaumur, DegreesReaumurTolerance); - Assert.Equal(TemperatureUnit.DegreeReaumur, parsed.Unit); - } - - { - Assert.True(Temperature.TryParse("1 °Rø", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DegreesRoemer, DegreesRoemerTolerance); - Assert.Equal(TemperatureUnit.DegreeRoemer, parsed.Unit); - } - - { - Assert.True(Temperature.TryParse("1 K", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kelvins, KelvinsTolerance); - Assert.Equal(TemperatureUnit.Kelvin, parsed.Unit); - } - - { - Assert.True(Temperature.TryParse("1 m°C", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillidegreesCelsius, MillidegreesCelsiusTolerance); - Assert.Equal(TemperatureUnit.MillidegreeCelsius, parsed.Unit); - } - - { - Assert.True(Temperature.TryParse("1 T⊙", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SolarTemperatures, SolarTemperaturesTolerance); - Assert.Equal(TemperatureUnit.SolarTemperature, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Temperature.TryParse(quantityString, out Temperature parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -643,6 +559,36 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Temper Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", TemperatureUnit.DegreeCelsius, "°C")] + [InlineData("en-US", TemperatureUnit.DegreeDelisle, "°De")] + [InlineData("en-US", TemperatureUnit.DegreeFahrenheit, "°F")] + [InlineData("en-US", TemperatureUnit.DegreeNewton, "°N")] + [InlineData("en-US", TemperatureUnit.DegreeRankine, "°R")] + [InlineData("en-US", TemperatureUnit.DegreeReaumur, "°Ré")] + [InlineData("en-US", TemperatureUnit.DegreeRoemer, "°Rø")] + [InlineData("en-US", TemperatureUnit.Kelvin, "K")] + [InlineData("en-US", TemperatureUnit.MillidegreeCelsius, "m°C")] + [InlineData("en-US", TemperatureUnit.SolarTemperature, "T⊙")] + public void GetAbbreviationForCulture(string culture, TemperatureUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Temperature.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Temperature.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Temperature.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(TemperatureUnit unit) @@ -673,6 +619,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); }); } @@ -696,28 +643,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); } @@ -764,8 +713,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); @@ -803,34 +750,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = Temperature.FromKelvins(1); - Assert.True(v.Equals(Temperature.FromKelvins(1), KelvinsTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Temperature.Zero, KelvinsTolerance, ComparisonType.Relative)); - Assert.True(Temperature.FromKelvins(100).Equals(Temperature.FromKelvins(120), 0.3, ComparisonType.Relative)); - Assert.False(Temperature.FromKelvins(100).Equals(Temperature.FromKelvins(120), 0.1, ComparisonType.Relative)); + Temperature kelvin = Temperature.FromKelvins(1); + Assert.False(kelvin.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = Temperature.FromKelvins(1); - Assert.Throws(() => v.Equals(Temperature.FromKelvins(1), -1, ComparisonType.Relative)); + Temperature kelvin = Temperature.FromKelvins(1); + Assert.False(kelvin.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - Temperature kelvin = Temperature.FromKelvins(1); - Assert.False(kelvin.Equals(new object())); + var quantity = Temperature.FromKelvins(firstValue); + var otherQuantity = Temperature.FromKelvins(secondValue); + TemperatureDelta maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - Temperature kelvin = Temperature.FromKelvins(1); - Assert.False(kelvin.Equals(null)); + var quantity = Temperature.FromKelvins(1); + TemperatureDelta negativeTolerance = quantity - Temperature.FromKelvins(2); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -849,6 +805,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() { @@ -925,158 +893,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Temperature.FromKelvins(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Temperature.FromKelvins(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Temperature.FromKelvins(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Temperature.FromKelvins(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Temperature.FromKelvins(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Temperature.FromKelvins(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Temperature.FromKelvins(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Temperature.FromKelvins(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Temperature.FromKelvins(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Temperature.FromKelvins(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Temperature.FromKelvins(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Temperature.FromKelvins(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Temperature.FromKelvins(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Temperature.FromKelvins(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Temperature.FromKelvins(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Temperature.FromKelvins(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Temperature))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Temperature.FromKelvins(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(TemperatureUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Temperature.FromKelvins(1.0); - Assert.Equal(Temperature.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Temperature.FromKelvins(1.0); - Assert.Equal(Temperature.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Temperature.FromKelvins(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Temperature.FromKelvins(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Temperature.FromKelvins(1.0); - Assert.Equal(new {Temperature.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 2684c7dc23..f31bcfb2e1 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalConductivityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalConductivityTestsBase.g.cs @@ -100,7 +100,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ThermalConductivity(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -113,15 +113,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ThermalConductivity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ThermalConductivityUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ThermalConductivity(1, ThermalConductivityUnit.WattPerMeterKelvin); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ThermalConductivity.Zero, quantityInfo.Zero); Assert.Equal("ThermalConductivity", quantityInfo.Name); + Assert.Equal(ThermalConductivity.Zero, quantityInfo.Zero); + Assert.Equal(ThermalConductivity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ThermalConductivity.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void ThermalConductivityInfo_CreateWithCustomUnitInfos() + { + ThermalConductivityUnit[] expectedUnits = [ThermalConductivityUnit.WattPerMeterKelvin]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -136,11 +154,11 @@ public void WattPerMeterKelvinToThermalConductivityUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ThermalConductivity.From(1, ThermalConductivityUnit.BtuPerHourFootFahrenheit); - AssertEx.EqualTolerance(1, quantity00.BtusPerHourFootFahrenheit, BtusPerHourFootFahrenheitTolerance); + Assert.Equal(1, quantity00.BtusPerHourFootFahrenheit); Assert.Equal(ThermalConductivityUnit.BtuPerHourFootFahrenheit, quantity00.Unit); var quantity01 = ThermalConductivity.From(1, ThermalConductivityUnit.WattPerMeterKelvin); - AssertEx.EqualTolerance(1, quantity01.WattsPerMeterKelvin, WattsPerMeterKelvinTolerance); + Assert.Equal(1, quantity01.WattsPerMeterKelvin); Assert.Equal(ThermalConductivityUnit.WattPerMeterKelvin, quantity01.Unit); } @@ -277,40 +295,26 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [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, decimal expectedValue) { - try - { - var parsed = ThermalConductivity.Parse("1 BTU/(h·ft·°F)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.BtusPerHourFootFahrenheit, BtusPerHourFootFahrenheitTolerance); - Assert.Equal(ThermalConductivityUnit.BtuPerHourFootFahrenheit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ThermalConductivity.Parse("1 W/(m·K)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.WattsPerMeterKelvin, WattsPerMeterKelvinTolerance); - Assert.Equal(ThermalConductivityUnit.WattPerMeterKelvin, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ThermalConductivity.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [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, decimal expectedValue) { - { - Assert.True(ThermalConductivity.TryParse("1 BTU/(h·ft·°F)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BtusPerHourFootFahrenheit, BtusPerHourFootFahrenheitTolerance); - Assert.Equal(ThermalConductivityUnit.BtuPerHourFootFahrenheit, parsed.Unit); - } - - { - Assert.True(ThermalConductivity.TryParse("1 W/(m·K)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.WattsPerMeterKelvin, WattsPerMeterKelvinTolerance); - Assert.Equal(ThermalConductivityUnit.WattPerMeterKelvin, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ThermalConductivity.TryParse(quantityString, out ThermalConductivity parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -395,6 +399,28 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Therma Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ThermalConductivityUnit.BtuPerHourFootFahrenheit, "BTU/(h·ft·°F)")] + [InlineData("en-US", ThermalConductivityUnit.WattPerMeterKelvin, "W/(m·K)")] + public void GetAbbreviationForCulture(string culture, ThermalConductivityUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ThermalConductivity.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ThermalConductivity.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ThermalConductivity.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ThermalConductivityUnit unit) @@ -425,6 +451,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); }); } @@ -448,33 +475,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] @@ -520,8 +549,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); @@ -559,34 +586,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = ThermalConductivity.FromWattsPerMeterKelvin(1); - Assert.True(v.Equals(ThermalConductivity.FromWattsPerMeterKelvin(1), WattsPerMeterKelvinTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ThermalConductivity.Zero, WattsPerMeterKelvinTolerance, ComparisonType.Relative)); - Assert.True(ThermalConductivity.FromWattsPerMeterKelvin(100).Equals(ThermalConductivity.FromWattsPerMeterKelvin(120), 0.3, ComparisonType.Relative)); - Assert.False(ThermalConductivity.FromWattsPerMeterKelvin(100).Equals(ThermalConductivity.FromWattsPerMeterKelvin(120), 0.1, ComparisonType.Relative)); + ThermalConductivity wattpermeterkelvin = ThermalConductivity.FromWattsPerMeterKelvin(1); + Assert.False(wattpermeterkelvin.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = ThermalConductivity.FromWattsPerMeterKelvin(1); - Assert.Throws(() => v.Equals(ThermalConductivity.FromWattsPerMeterKelvin(1), -1, ComparisonType.Relative)); + ThermalConductivity wattpermeterkelvin = ThermalConductivity.FromWattsPerMeterKelvin(1); + Assert.False(wattpermeterkelvin.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - ThermalConductivity wattpermeterkelvin = ThermalConductivity.FromWattsPerMeterKelvin(1); - Assert.False(wattpermeterkelvin.Equals(new object())); + var quantity = ThermalConductivity.FromWattsPerMeterKelvin(firstValue); + var otherQuantity = ThermalConductivity.FromWattsPerMeterKelvin(secondValue); + ThermalConductivity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - ThermalConductivity wattpermeterkelvin = ThermalConductivity.FromWattsPerMeterKelvin(1); - Assert.False(wattpermeterkelvin.Equals(null)); + var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1); + var negativeTolerance = ThermalConductivity.FromWattsPerMeterKelvin(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -605,6 +641,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() { @@ -665,158 +713,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ThermalConductivity))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ThermalConductivityUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal(ThermalConductivity.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal(ThermalConductivity.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal(new {ThermalConductivity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 c72f44a212..74c2aeb98d 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalInsulanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalInsulanceTestsBase.g.cs @@ -116,7 +116,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new ThermalInsulance(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -129,15 +129,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void ThermalInsulance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + ThermalInsulanceUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new ThermalInsulance(1, ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(ThermalInsulance.Zero, quantityInfo.Zero); Assert.Equal("ThermalInsulance", quantityInfo.Name); + Assert.Equal(ThermalInsulance.Zero, quantityInfo.Zero); + Assert.Equal(ThermalInsulance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(ThermalInsulance.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void ThermalInsulanceInfo_CreateWithCustomUnitInfos() + { + ThermalInsulanceUnit[] expectedUnits = [ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -156,27 +174,27 @@ public void SquareMeterKelvinPerKilowattToThermalInsulanceUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = ThermalInsulance.From(1, ThermalInsulanceUnit.HourSquareFeetDegreeFahrenheitPerBtu); - AssertEx.EqualTolerance(1, quantity00.HourSquareFeetDegreesFahrenheitPerBtu, HourSquareFeetDegreesFahrenheitPerBtuTolerance); + Assert.Equal(1, quantity00.HourSquareFeetDegreesFahrenheitPerBtu); Assert.Equal(ThermalInsulanceUnit.HourSquareFeetDegreeFahrenheitPerBtu, quantity00.Unit); var quantity01 = ThermalInsulance.From(1, ThermalInsulanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie); - AssertEx.EqualTolerance(1, quantity01.SquareCentimeterHourDegreesCelsiusPerKilocalorie, SquareCentimeterHourDegreesCelsiusPerKilocalorieTolerance); + Assert.Equal(1, quantity01.SquareCentimeterHourDegreesCelsiusPerKilocalorie); Assert.Equal(ThermalInsulanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie, quantity01.Unit); var quantity02 = ThermalInsulance.From(1, ThermalInsulanceUnit.SquareCentimeterKelvinPerWatt); - AssertEx.EqualTolerance(1, quantity02.SquareCentimeterKelvinsPerWatt, SquareCentimeterKelvinsPerWattTolerance); + Assert.Equal(1, quantity02.SquareCentimeterKelvinsPerWatt); Assert.Equal(ThermalInsulanceUnit.SquareCentimeterKelvinPerWatt, quantity02.Unit); var quantity03 = ThermalInsulance.From(1, ThermalInsulanceUnit.SquareMeterDegreeCelsiusPerWatt); - AssertEx.EqualTolerance(1, quantity03.SquareMeterDegreesCelsiusPerWatt, SquareMeterDegreesCelsiusPerWattTolerance); + Assert.Equal(1, quantity03.SquareMeterDegreesCelsiusPerWatt); Assert.Equal(ThermalInsulanceUnit.SquareMeterDegreeCelsiusPerWatt, quantity03.Unit); var quantity04 = ThermalInsulance.From(1, ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt); - AssertEx.EqualTolerance(1, quantity04.SquareMeterKelvinsPerKilowatt, SquareMeterKelvinsPerKilowattTolerance); + Assert.Equal(1, quantity04.SquareMeterKelvinsPerKilowatt); Assert.Equal(ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, quantity04.Unit); var quantity05 = ThermalInsulance.From(1, ThermalInsulanceUnit.SquareMeterKelvinPerWatt); - AssertEx.EqualTolerance(1, quantity05.SquareMeterKelvinsPerWatt, SquareMeterKelvinsPerWattTolerance); + Assert.Equal(1, quantity05.SquareMeterKelvinsPerWatt); Assert.Equal(ThermalInsulanceUnit.SquareMeterKelvinPerWatt, quantity05.Unit); } @@ -317,92 +335,34 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 Hrft²°F/Btu", ThermalInsulanceUnit.HourSquareFeetDegreeFahrenheitPerBtu, 4.2)] + [InlineData("en-US", "4.2 cm²Hr°C/kcal", ThermalInsulanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie, 4.2)] + [InlineData("en-US", "4.2 cm²K/W", ThermalInsulanceUnit.SquareCentimeterKelvinPerWatt, 4.2)] + [InlineData("en-US", "4.2 m²°C/W", ThermalInsulanceUnit.SquareMeterDegreeCelsiusPerWatt, 4.2)] + [InlineData("en-US", "4.2 m²K/kW", ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, 4.2)] + [InlineData("en-US", "4.2 m²K/W", ThermalInsulanceUnit.SquareMeterKelvinPerWatt, 4.2)] + public void Parse(string culture, string quantityString, ThermalInsulanceUnit expectedUnit, decimal expectedValue) { - try - { - var parsed = ThermalInsulance.Parse("1 Hrft²°F/Btu", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.HourSquareFeetDegreesFahrenheitPerBtu, HourSquareFeetDegreesFahrenheitPerBtuTolerance); - Assert.Equal(ThermalInsulanceUnit.HourSquareFeetDegreeFahrenheitPerBtu, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ThermalInsulance.Parse("1 cm²Hr°C/kcal", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SquareCentimeterHourDegreesCelsiusPerKilocalorie, SquareCentimeterHourDegreesCelsiusPerKilocalorieTolerance); - Assert.Equal(ThermalInsulanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ThermalInsulance.Parse("1 cm²K/W", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SquareCentimeterKelvinsPerWatt, SquareCentimeterKelvinsPerWattTolerance); - Assert.Equal(ThermalInsulanceUnit.SquareCentimeterKelvinPerWatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ThermalInsulance.Parse("1 m²°C/W", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SquareMeterDegreesCelsiusPerWatt, SquareMeterDegreesCelsiusPerWattTolerance); - Assert.Equal(ThermalInsulanceUnit.SquareMeterDegreeCelsiusPerWatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ThermalInsulance.Parse("1 m²K/kW", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SquareMeterKelvinsPerKilowatt, SquareMeterKelvinsPerKilowattTolerance); - Assert.Equal(ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = ThermalInsulance.Parse("1 m²K/W", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.SquareMeterKelvinsPerWatt, SquareMeterKelvinsPerWattTolerance); - Assert.Equal(ThermalInsulanceUnit.SquareMeterKelvinPerWatt, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = ThermalInsulance.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 Hrft²°F/Btu", ThermalInsulanceUnit.HourSquareFeetDegreeFahrenheitPerBtu, 4.2)] + [InlineData("en-US", "4.2 cm²Hr°C/kcal", ThermalInsulanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie, 4.2)] + [InlineData("en-US", "4.2 cm²K/W", ThermalInsulanceUnit.SquareCentimeterKelvinPerWatt, 4.2)] + [InlineData("en-US", "4.2 m²°C/W", ThermalInsulanceUnit.SquareMeterDegreeCelsiusPerWatt, 4.2)] + [InlineData("en-US", "4.2 m²K/kW", ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, 4.2)] + [InlineData("en-US", "4.2 m²K/W", ThermalInsulanceUnit.SquareMeterKelvinPerWatt, 4.2)] + public void TryParse(string culture, string quantityString, ThermalInsulanceUnit expectedUnit, decimal expectedValue) { - { - Assert.True(ThermalInsulance.TryParse("1 Hrft²°F/Btu", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HourSquareFeetDegreesFahrenheitPerBtu, HourSquareFeetDegreesFahrenheitPerBtuTolerance); - Assert.Equal(ThermalInsulanceUnit.HourSquareFeetDegreeFahrenheitPerBtu, parsed.Unit); - } - - { - Assert.True(ThermalInsulance.TryParse("1 cm²Hr°C/kcal", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareCentimeterHourDegreesCelsiusPerKilocalorie, SquareCentimeterHourDegreesCelsiusPerKilocalorieTolerance); - Assert.Equal(ThermalInsulanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie, parsed.Unit); - } - - { - Assert.True(ThermalInsulance.TryParse("1 cm²K/W", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareCentimeterKelvinsPerWatt, SquareCentimeterKelvinsPerWattTolerance); - Assert.Equal(ThermalInsulanceUnit.SquareCentimeterKelvinPerWatt, parsed.Unit); - } - - { - Assert.True(ThermalInsulance.TryParse("1 m²°C/W", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareMeterDegreesCelsiusPerWatt, SquareMeterDegreesCelsiusPerWattTolerance); - Assert.Equal(ThermalInsulanceUnit.SquareMeterDegreeCelsiusPerWatt, parsed.Unit); - } - - { - Assert.True(ThermalInsulance.TryParse("1 m²K/kW", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareMeterKelvinsPerKilowatt, SquareMeterKelvinsPerKilowattTolerance); - Assert.Equal(ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, parsed.Unit); - } - - { - Assert.True(ThermalInsulance.TryParse("1 m²K/W", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.SquareMeterKelvinsPerWatt, SquareMeterKelvinsPerWattTolerance); - Assert.Equal(ThermalInsulanceUnit.SquareMeterKelvinPerWatt, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(ThermalInsulance.TryParse(quantityString, out ThermalInsulance parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -519,6 +479,32 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Therma Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", ThermalInsulanceUnit.HourSquareFeetDegreeFahrenheitPerBtu, "Hrft²°F/Btu")] + [InlineData("en-US", ThermalInsulanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie, "cm²Hr°C/kcal")] + [InlineData("en-US", ThermalInsulanceUnit.SquareCentimeterKelvinPerWatt, "cm²K/W")] + [InlineData("en-US", ThermalInsulanceUnit.SquareMeterDegreeCelsiusPerWatt, "m²°C/W")] + [InlineData("en-US", ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, "m²K/kW")] + [InlineData("en-US", ThermalInsulanceUnit.SquareMeterKelvinPerWatt, "m²K/W")] + public void GetAbbreviationForCulture(string culture, ThermalInsulanceUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = ThermalInsulance.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(ThermalInsulance.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = ThermalInsulance.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(ThermalInsulanceUnit unit) @@ -549,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); }); } @@ -572,37 +559,39 @@ 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); + 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); } [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] @@ -648,8 +637,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); @@ -687,34 +674,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1); - Assert.True(v.Equals(ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1), SquareMeterKelvinsPerKilowattTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(ThermalInsulance.Zero, SquareMeterKelvinsPerKilowattTolerance, ComparisonType.Relative)); - Assert.True(ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(100).Equals(ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(120), 0.3, ComparisonType.Relative)); - Assert.False(ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(100).Equals(ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(120), 0.1, ComparisonType.Relative)); + ThermalInsulance squaremeterkelvinperkilowatt = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1); + Assert.False(squaremeterkelvinperkilowatt.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1); - Assert.Throws(() => v.Equals(ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1), -1, ComparisonType.Relative)); + ThermalInsulance squaremeterkelvinperkilowatt = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1); + Assert.False(squaremeterkelvinperkilowatt.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - ThermalInsulance squaremeterkelvinperkilowatt = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1); - Assert.False(squaremeterkelvinperkilowatt.Equals(new object())); + var quantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(firstValue); + var otherQuantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(secondValue); + ThermalInsulance maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - ThermalInsulance squaremeterkelvinperkilowatt = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1); - Assert.False(squaremeterkelvinperkilowatt.Equals(null)); + var quantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1); + var negativeTolerance = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -733,6 +729,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() { @@ -801,158 +809,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(ThermalInsulance))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(ThermalInsulanceUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal(ThermalInsulance.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal(ThermalInsulance.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal(new {ThermalInsulance.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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/TorqueTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TorqueTestsBase.g.cs index 332f883636..894a87353f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TorqueTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TorqueTestsBase.g.cs @@ -192,7 +192,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Torque(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -205,15 +205,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Torque_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + TorqueUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Torque(1, TorqueUnit.NewtonMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Torque.Zero, quantityInfo.Zero); Assert.Equal("Torque", quantityInfo.Name); + Assert.Equal(Torque.Zero, quantityInfo.Zero); + Assert.Equal(Torque.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Torque.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -251,103 +269,103 @@ public void NewtonMeterToTorqueUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Torque.From(1, TorqueUnit.GramForceCentimeter); - AssertEx.EqualTolerance(1, quantity00.GramForceCentimeters, GramForceCentimetersTolerance); + Assert.Equal(1, quantity00.GramForceCentimeters); Assert.Equal(TorqueUnit.GramForceCentimeter, quantity00.Unit); var quantity01 = Torque.From(1, TorqueUnit.GramForceMeter); - AssertEx.EqualTolerance(1, quantity01.GramForceMeters, GramForceMetersTolerance); + Assert.Equal(1, quantity01.GramForceMeters); Assert.Equal(TorqueUnit.GramForceMeter, quantity01.Unit); var quantity02 = Torque.From(1, TorqueUnit.GramForceMillimeter); - AssertEx.EqualTolerance(1, quantity02.GramForceMillimeters, GramForceMillimetersTolerance); + Assert.Equal(1, quantity02.GramForceMillimeters); Assert.Equal(TorqueUnit.GramForceMillimeter, quantity02.Unit); var quantity03 = Torque.From(1, TorqueUnit.KilogramForceCentimeter); - AssertEx.EqualTolerance(1, quantity03.KilogramForceCentimeters, KilogramForceCentimetersTolerance); + Assert.Equal(1, quantity03.KilogramForceCentimeters); Assert.Equal(TorqueUnit.KilogramForceCentimeter, quantity03.Unit); var quantity04 = Torque.From(1, TorqueUnit.KilogramForceMeter); - AssertEx.EqualTolerance(1, quantity04.KilogramForceMeters, KilogramForceMetersTolerance); + Assert.Equal(1, quantity04.KilogramForceMeters); Assert.Equal(TorqueUnit.KilogramForceMeter, quantity04.Unit); var quantity05 = Torque.From(1, TorqueUnit.KilogramForceMillimeter); - AssertEx.EqualTolerance(1, quantity05.KilogramForceMillimeters, KilogramForceMillimetersTolerance); + Assert.Equal(1, quantity05.KilogramForceMillimeters); Assert.Equal(TorqueUnit.KilogramForceMillimeter, quantity05.Unit); var quantity06 = Torque.From(1, TorqueUnit.KilonewtonCentimeter); - AssertEx.EqualTolerance(1, quantity06.KilonewtonCentimeters, KilonewtonCentimetersTolerance); + Assert.Equal(1, quantity06.KilonewtonCentimeters); Assert.Equal(TorqueUnit.KilonewtonCentimeter, quantity06.Unit); var quantity07 = Torque.From(1, TorqueUnit.KilonewtonMeter); - AssertEx.EqualTolerance(1, quantity07.KilonewtonMeters, KilonewtonMetersTolerance); + Assert.Equal(1, quantity07.KilonewtonMeters); Assert.Equal(TorqueUnit.KilonewtonMeter, quantity07.Unit); var quantity08 = Torque.From(1, TorqueUnit.KilonewtonMillimeter); - AssertEx.EqualTolerance(1, quantity08.KilonewtonMillimeters, KilonewtonMillimetersTolerance); + Assert.Equal(1, quantity08.KilonewtonMillimeters); Assert.Equal(TorqueUnit.KilonewtonMillimeter, quantity08.Unit); var quantity09 = Torque.From(1, TorqueUnit.KilopoundForceFoot); - AssertEx.EqualTolerance(1, quantity09.KilopoundForceFeet, KilopoundForceFeetTolerance); + Assert.Equal(1, quantity09.KilopoundForceFeet); Assert.Equal(TorqueUnit.KilopoundForceFoot, quantity09.Unit); var quantity10 = Torque.From(1, TorqueUnit.KilopoundForceInch); - AssertEx.EqualTolerance(1, quantity10.KilopoundForceInches, KilopoundForceInchesTolerance); + Assert.Equal(1, quantity10.KilopoundForceInches); Assert.Equal(TorqueUnit.KilopoundForceInch, quantity10.Unit); var quantity11 = Torque.From(1, TorqueUnit.MeganewtonCentimeter); - AssertEx.EqualTolerance(1, quantity11.MeganewtonCentimeters, MeganewtonCentimetersTolerance); + Assert.Equal(1, quantity11.MeganewtonCentimeters); Assert.Equal(TorqueUnit.MeganewtonCentimeter, quantity11.Unit); var quantity12 = Torque.From(1, TorqueUnit.MeganewtonMeter); - AssertEx.EqualTolerance(1, quantity12.MeganewtonMeters, MeganewtonMetersTolerance); + Assert.Equal(1, quantity12.MeganewtonMeters); Assert.Equal(TorqueUnit.MeganewtonMeter, quantity12.Unit); var quantity13 = Torque.From(1, TorqueUnit.MeganewtonMillimeter); - AssertEx.EqualTolerance(1, quantity13.MeganewtonMillimeters, MeganewtonMillimetersTolerance); + Assert.Equal(1, quantity13.MeganewtonMillimeters); Assert.Equal(TorqueUnit.MeganewtonMillimeter, quantity13.Unit); var quantity14 = Torque.From(1, TorqueUnit.MegapoundForceFoot); - AssertEx.EqualTolerance(1, quantity14.MegapoundForceFeet, MegapoundForceFeetTolerance); + Assert.Equal(1, quantity14.MegapoundForceFeet); Assert.Equal(TorqueUnit.MegapoundForceFoot, quantity14.Unit); var quantity15 = Torque.From(1, TorqueUnit.MegapoundForceInch); - AssertEx.EqualTolerance(1, quantity15.MegapoundForceInches, MegapoundForceInchesTolerance); + Assert.Equal(1, quantity15.MegapoundForceInches); Assert.Equal(TorqueUnit.MegapoundForceInch, quantity15.Unit); var quantity16 = Torque.From(1, TorqueUnit.NewtonCentimeter); - AssertEx.EqualTolerance(1, quantity16.NewtonCentimeters, NewtonCentimetersTolerance); + Assert.Equal(1, quantity16.NewtonCentimeters); Assert.Equal(TorqueUnit.NewtonCentimeter, quantity16.Unit); var quantity17 = Torque.From(1, TorqueUnit.NewtonMeter); - AssertEx.EqualTolerance(1, quantity17.NewtonMeters, NewtonMetersTolerance); + Assert.Equal(1, quantity17.NewtonMeters); Assert.Equal(TorqueUnit.NewtonMeter, quantity17.Unit); var quantity18 = Torque.From(1, TorqueUnit.NewtonMillimeter); - AssertEx.EqualTolerance(1, quantity18.NewtonMillimeters, NewtonMillimetersTolerance); + Assert.Equal(1, quantity18.NewtonMillimeters); Assert.Equal(TorqueUnit.NewtonMillimeter, quantity18.Unit); var quantity19 = Torque.From(1, TorqueUnit.PoundalFoot); - AssertEx.EqualTolerance(1, quantity19.PoundalFeet, PoundalFeetTolerance); + Assert.Equal(1, quantity19.PoundalFeet); Assert.Equal(TorqueUnit.PoundalFoot, quantity19.Unit); var quantity20 = Torque.From(1, TorqueUnit.PoundForceFoot); - AssertEx.EqualTolerance(1, quantity20.PoundForceFeet, PoundForceFeetTolerance); + Assert.Equal(1, quantity20.PoundForceFeet); Assert.Equal(TorqueUnit.PoundForceFoot, quantity20.Unit); var quantity21 = Torque.From(1, TorqueUnit.PoundForceInch); - AssertEx.EqualTolerance(1, quantity21.PoundForceInches, PoundForceInchesTolerance); + Assert.Equal(1, quantity21.PoundForceInches); Assert.Equal(TorqueUnit.PoundForceInch, quantity21.Unit); var quantity22 = Torque.From(1, TorqueUnit.TonneForceCentimeter); - AssertEx.EqualTolerance(1, quantity22.TonneForceCentimeters, TonneForceCentimetersTolerance); + Assert.Equal(1, quantity22.TonneForceCentimeters); Assert.Equal(TorqueUnit.TonneForceCentimeter, quantity22.Unit); var quantity23 = Torque.From(1, TorqueUnit.TonneForceMeter); - AssertEx.EqualTolerance(1, quantity23.TonneForceMeters, TonneForceMetersTolerance); + Assert.Equal(1, quantity23.TonneForceMeters); Assert.Equal(TorqueUnit.TonneForceMeter, quantity23.Unit); var quantity24 = Torque.From(1, TorqueUnit.TonneForceMillimeter); - AssertEx.EqualTolerance(1, quantity24.TonneForceMillimeters, TonneForceMillimetersTolerance); + Assert.Equal(1, quantity24.TonneForceMillimeters); Assert.Equal(TorqueUnit.TonneForceMillimeter, quantity24.Unit); } @@ -507,378 +525,78 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 gf·cm", TorqueUnit.GramForceCentimeter, 4.2)] + [InlineData("en-US", "4.2 gf·m", TorqueUnit.GramForceMeter, 4.2)] + [InlineData("en-US", "4.2 gf·mm", TorqueUnit.GramForceMillimeter, 4.2)] + [InlineData("en-US", "4.2 kgf·cm", TorqueUnit.KilogramForceCentimeter, 4.2)] + [InlineData("en-US", "4.2 kgf·m", TorqueUnit.KilogramForceMeter, 4.2)] + [InlineData("en-US", "4.2 kgf·mm", TorqueUnit.KilogramForceMillimeter, 4.2)] + [InlineData("en-US", "4.2 kN·cm", TorqueUnit.KilonewtonCentimeter, 4.2)] + [InlineData("en-US", "4.2 kN·m", TorqueUnit.KilonewtonMeter, 4.2)] + [InlineData("en-US", "4.2 kN·mm", TorqueUnit.KilonewtonMillimeter, 4.2)] + [InlineData("en-US", "4.2 kipf·ft", TorqueUnit.KilopoundForceFoot, 4.2)] + [InlineData("en-US", "4.2 kipf·in", TorqueUnit.KilopoundForceInch, 4.2)] + [InlineData("en-US", "4.2 MN·cm", TorqueUnit.MeganewtonCentimeter, 4.2)] + [InlineData("en-US", "4.2 MN·m", TorqueUnit.MeganewtonMeter, 4.2)] + [InlineData("en-US", "4.2 MN·mm", TorqueUnit.MeganewtonMillimeter, 4.2)] + [InlineData("en-US", "4.2 Mlbf·ft", TorqueUnit.MegapoundForceFoot, 4.2)] + [InlineData("en-US", "4.2 Mlbf·in", TorqueUnit.MegapoundForceInch, 4.2)] + [InlineData("en-US", "4.2 N·cm", TorqueUnit.NewtonCentimeter, 4.2)] + [InlineData("en-US", "4.2 N·m", TorqueUnit.NewtonMeter, 4.2)] + [InlineData("en-US", "4.2 N·mm", TorqueUnit.NewtonMillimeter, 4.2)] + [InlineData("en-US", "4.2 pdl·ft", TorqueUnit.PoundalFoot, 4.2)] + [InlineData("en-US", "4.2 lbf·ft", TorqueUnit.PoundForceFoot, 4.2)] + [InlineData("en-US", "4.2 lbf·in", TorqueUnit.PoundForceInch, 4.2)] + [InlineData("en-US", "4.2 tf·cm", TorqueUnit.TonneForceCentimeter, 4.2)] + [InlineData("en-US", "4.2 tf·m", TorqueUnit.TonneForceMeter, 4.2)] + [InlineData("en-US", "4.2 tf·mm", TorqueUnit.TonneForceMillimeter, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = Torque.Parse("1 gf·cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramForceCentimeters, GramForceCentimetersTolerance); - Assert.Equal(TorqueUnit.GramForceCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Torque.Parse("1 gf·m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramForceMeters, GramForceMetersTolerance); - Assert.Equal(TorqueUnit.GramForceMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Torque.Parse("1 gf·mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.GramForceMillimeters, GramForceMillimetersTolerance); - Assert.Equal(TorqueUnit.GramForceMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Torque.Parse("1 kgf·cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramForceCentimeters, KilogramForceCentimetersTolerance); - Assert.Equal(TorqueUnit.KilogramForceCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Torque.Parse("1 kgf·m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramForceMeters, KilogramForceMetersTolerance); - Assert.Equal(TorqueUnit.KilogramForceMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Torque.Parse("1 kgf·mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilogramForceMillimeters, KilogramForceMillimetersTolerance); - Assert.Equal(TorqueUnit.KilogramForceMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Torque.Parse("1 kN·cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonCentimeters, KilonewtonCentimetersTolerance); - Assert.Equal(TorqueUnit.KilonewtonCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Torque.Parse("1 kN·m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonMeters, KilonewtonMetersTolerance); - Assert.Equal(TorqueUnit.KilonewtonMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Torque.Parse("1 кН·м", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilonewtonMeters, KilonewtonMetersTolerance); - Assert.Equal(TorqueUnit.KilonewtonMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Torque.Parse("1 kN·mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilonewtonMillimeters, KilonewtonMillimetersTolerance); - Assert.Equal(TorqueUnit.KilonewtonMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Torque.Parse("1 kipf·ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundForceFeet, KilopoundForceFeetTolerance); - Assert.Equal(TorqueUnit.KilopoundForceFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Torque.Parse("1 kipf·in", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilopoundForceInches, KilopoundForceInchesTolerance); - Assert.Equal(TorqueUnit.KilopoundForceInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Torque.Parse("1 MN·cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MeganewtonCentimeters, MeganewtonCentimetersTolerance); - Assert.Equal(TorqueUnit.MeganewtonCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Torque.Parse("1 MN·m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MeganewtonMeters, MeganewtonMetersTolerance); - Assert.Equal(TorqueUnit.MeganewtonMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Torque.Parse("1 МН·м", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MeganewtonMeters, MeganewtonMetersTolerance); - Assert.Equal(TorqueUnit.MeganewtonMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Torque.Parse("1 MN·mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MeganewtonMillimeters, MeganewtonMillimetersTolerance); - Assert.Equal(TorqueUnit.MeganewtonMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Torque.Parse("1 Mlbf·ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegapoundForceFeet, MegapoundForceFeetTolerance); - Assert.Equal(TorqueUnit.MegapoundForceFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Torque.Parse("1 Mlbf·in", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegapoundForceInches, MegapoundForceInchesTolerance); - Assert.Equal(TorqueUnit.MegapoundForceInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Torque.Parse("1 N·cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonCentimeters, NewtonCentimetersTolerance); - Assert.Equal(TorqueUnit.NewtonCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Torque.Parse("1 N·m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonMeters, NewtonMetersTolerance); - Assert.Equal(TorqueUnit.NewtonMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Torque.Parse("1 Н·м", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.NewtonMeters, NewtonMetersTolerance); - Assert.Equal(TorqueUnit.NewtonMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Torque.Parse("1 N·mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NewtonMillimeters, NewtonMillimetersTolerance); - Assert.Equal(TorqueUnit.NewtonMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Torque.Parse("1 pdl·ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundalFeet, PoundalFeetTolerance); - Assert.Equal(TorqueUnit.PoundalFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Torque.Parse("1 lbf·ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundForceFeet, PoundForceFeetTolerance); - Assert.Equal(TorqueUnit.PoundForceFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Torque.Parse("1 lbf·in", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PoundForceInches, PoundForceInchesTolerance); - Assert.Equal(TorqueUnit.PoundForceInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Torque.Parse("1 tf·cm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonneForceCentimeters, TonneForceCentimetersTolerance); - Assert.Equal(TorqueUnit.TonneForceCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Torque.Parse("1 tf·m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonneForceMeters, TonneForceMetersTolerance); - Assert.Equal(TorqueUnit.TonneForceMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Torque.Parse("1 tf·mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.TonneForceMillimeters, TonneForceMillimetersTolerance); - Assert.Equal(TorqueUnit.TonneForceMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Torque.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 gf·cm", TorqueUnit.GramForceCentimeter, 4.2)] + [InlineData("en-US", "4.2 gf·m", TorqueUnit.GramForceMeter, 4.2)] + [InlineData("en-US", "4.2 gf·mm", TorqueUnit.GramForceMillimeter, 4.2)] + [InlineData("en-US", "4.2 kgf·cm", TorqueUnit.KilogramForceCentimeter, 4.2)] + [InlineData("en-US", "4.2 kgf·m", TorqueUnit.KilogramForceMeter, 4.2)] + [InlineData("en-US", "4.2 kgf·mm", TorqueUnit.KilogramForceMillimeter, 4.2)] + [InlineData("en-US", "4.2 kN·cm", TorqueUnit.KilonewtonCentimeter, 4.2)] + [InlineData("en-US", "4.2 kN·m", TorqueUnit.KilonewtonMeter, 4.2)] + [InlineData("en-US", "4.2 kN·mm", TorqueUnit.KilonewtonMillimeter, 4.2)] + [InlineData("en-US", "4.2 kipf·ft", TorqueUnit.KilopoundForceFoot, 4.2)] + [InlineData("en-US", "4.2 kipf·in", TorqueUnit.KilopoundForceInch, 4.2)] + [InlineData("en-US", "4.2 MN·cm", TorqueUnit.MeganewtonCentimeter, 4.2)] + [InlineData("en-US", "4.2 MN·m", TorqueUnit.MeganewtonMeter, 4.2)] + [InlineData("en-US", "4.2 MN·mm", TorqueUnit.MeganewtonMillimeter, 4.2)] + [InlineData("en-US", "4.2 Mlbf·ft", TorqueUnit.MegapoundForceFoot, 4.2)] + [InlineData("en-US", "4.2 Mlbf·in", TorqueUnit.MegapoundForceInch, 4.2)] + [InlineData("en-US", "4.2 N·cm", TorqueUnit.NewtonCentimeter, 4.2)] + [InlineData("en-US", "4.2 N·m", TorqueUnit.NewtonMeter, 4.2)] + [InlineData("en-US", "4.2 N·mm", TorqueUnit.NewtonMillimeter, 4.2)] + [InlineData("en-US", "4.2 pdl·ft", TorqueUnit.PoundalFoot, 4.2)] + [InlineData("en-US", "4.2 lbf·ft", TorqueUnit.PoundForceFoot, 4.2)] + [InlineData("en-US", "4.2 lbf·in", TorqueUnit.PoundForceInch, 4.2)] + [InlineData("en-US", "4.2 tf·cm", TorqueUnit.TonneForceCentimeter, 4.2)] + [InlineData("en-US", "4.2 tf·m", TorqueUnit.TonneForceMeter, 4.2)] + [InlineData("en-US", "4.2 tf·mm", TorqueUnit.TonneForceMillimeter, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(Torque.TryParse("1 gf·cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramForceCentimeters, GramForceCentimetersTolerance); - Assert.Equal(TorqueUnit.GramForceCentimeter, parsed.Unit); - } - - { - Assert.True(Torque.TryParse("1 gf·m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramForceMeters, GramForceMetersTolerance); - Assert.Equal(TorqueUnit.GramForceMeter, parsed.Unit); - } - - { - Assert.True(Torque.TryParse("1 gf·mm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.GramForceMillimeters, GramForceMillimetersTolerance); - Assert.Equal(TorqueUnit.GramForceMillimeter, parsed.Unit); - } - - { - Assert.True(Torque.TryParse("1 kgf·cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramForceCentimeters, KilogramForceCentimetersTolerance); - Assert.Equal(TorqueUnit.KilogramForceCentimeter, parsed.Unit); - } - - { - Assert.True(Torque.TryParse("1 kgf·m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramForceMeters, KilogramForceMetersTolerance); - Assert.Equal(TorqueUnit.KilogramForceMeter, parsed.Unit); - } - - { - Assert.True(Torque.TryParse("1 kgf·mm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilogramForceMillimeters, KilogramForceMillimetersTolerance); - Assert.Equal(TorqueUnit.KilogramForceMillimeter, parsed.Unit); - } - - { - Assert.True(Torque.TryParse("1 kN·cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonCentimeters, KilonewtonCentimetersTolerance); - Assert.Equal(TorqueUnit.KilonewtonCentimeter, parsed.Unit); - } - - { - Assert.True(Torque.TryParse("1 kN·m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonMeters, KilonewtonMetersTolerance); - Assert.Equal(TorqueUnit.KilonewtonMeter, parsed.Unit); - } - - { - Assert.True(Torque.TryParse("1 кН·м", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonMeters, KilonewtonMetersTolerance); - Assert.Equal(TorqueUnit.KilonewtonMeter, parsed.Unit); - } - - { - Assert.True(Torque.TryParse("1 kN·mm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilonewtonMillimeters, KilonewtonMillimetersTolerance); - Assert.Equal(TorqueUnit.KilonewtonMillimeter, parsed.Unit); - } - - { - Assert.True(Torque.TryParse("1 kipf·ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundForceFeet, KilopoundForceFeetTolerance); - Assert.Equal(TorqueUnit.KilopoundForceFoot, parsed.Unit); - } - - { - Assert.True(Torque.TryParse("1 kipf·in", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilopoundForceInches, KilopoundForceInchesTolerance); - Assert.Equal(TorqueUnit.KilopoundForceInch, parsed.Unit); - } - - { - Assert.True(Torque.TryParse("1 MN·cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MeganewtonCentimeters, MeganewtonCentimetersTolerance); - Assert.Equal(TorqueUnit.MeganewtonCentimeter, parsed.Unit); - } - - { - Assert.True(Torque.TryParse("1 MN·m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MeganewtonMeters, MeganewtonMetersTolerance); - Assert.Equal(TorqueUnit.MeganewtonMeter, parsed.Unit); - } - - { - Assert.True(Torque.TryParse("1 МН·м", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MeganewtonMeters, MeganewtonMetersTolerance); - Assert.Equal(TorqueUnit.MeganewtonMeter, parsed.Unit); - } - - { - Assert.True(Torque.TryParse("1 MN·mm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MeganewtonMillimeters, MeganewtonMillimetersTolerance); - Assert.Equal(TorqueUnit.MeganewtonMillimeter, parsed.Unit); - } - - { - Assert.True(Torque.TryParse("1 Mlbf·ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegapoundForceFeet, MegapoundForceFeetTolerance); - Assert.Equal(TorqueUnit.MegapoundForceFoot, parsed.Unit); - } - - { - Assert.True(Torque.TryParse("1 Mlbf·in", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegapoundForceInches, MegapoundForceInchesTolerance); - Assert.Equal(TorqueUnit.MegapoundForceInch, parsed.Unit); - } - - { - Assert.True(Torque.TryParse("1 N·cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonCentimeters, NewtonCentimetersTolerance); - Assert.Equal(TorqueUnit.NewtonCentimeter, parsed.Unit); - } - - { - Assert.True(Torque.TryParse("1 N·m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonMeters, NewtonMetersTolerance); - Assert.Equal(TorqueUnit.NewtonMeter, parsed.Unit); - } - - { - Assert.True(Torque.TryParse("1 Н·м", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonMeters, NewtonMetersTolerance); - Assert.Equal(TorqueUnit.NewtonMeter, parsed.Unit); - } - - { - Assert.True(Torque.TryParse("1 N·mm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NewtonMillimeters, NewtonMillimetersTolerance); - Assert.Equal(TorqueUnit.NewtonMillimeter, parsed.Unit); - } - - { - Assert.True(Torque.TryParse("1 pdl·ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundalFeet, PoundalFeetTolerance); - Assert.Equal(TorqueUnit.PoundalFoot, parsed.Unit); - } - - { - Assert.True(Torque.TryParse("1 lbf·ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundForceFeet, PoundForceFeetTolerance); - Assert.Equal(TorqueUnit.PoundForceFoot, parsed.Unit); - } - - { - Assert.True(Torque.TryParse("1 lbf·in", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PoundForceInches, PoundForceInchesTolerance); - Assert.Equal(TorqueUnit.PoundForceInch, parsed.Unit); - } - - { - Assert.True(Torque.TryParse("1 tf·cm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonneForceCentimeters, TonneForceCentimetersTolerance); - Assert.Equal(TorqueUnit.TonneForceCentimeter, parsed.Unit); - } - - { - Assert.True(Torque.TryParse("1 tf·m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonneForceMeters, TonneForceMetersTolerance); - Assert.Equal(TorqueUnit.TonneForceMeter, parsed.Unit); - } - - { - Assert.True(Torque.TryParse("1 tf·mm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.TonneForceMillimeters, TonneForceMillimetersTolerance); - Assert.Equal(TorqueUnit.TonneForceMillimeter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Torque.TryParse(quantityString, out Torque parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -1159,6 +877,54 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Torque Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", TorqueUnit.GramForceCentimeter, "gf·cm")] + [InlineData("en-US", TorqueUnit.GramForceMeter, "gf·m")] + [InlineData("en-US", TorqueUnit.GramForceMillimeter, "gf·mm")] + [InlineData("en-US", TorqueUnit.KilogramForceCentimeter, "kgf·cm")] + [InlineData("en-US", TorqueUnit.KilogramForceMeter, "kgf·m")] + [InlineData("en-US", TorqueUnit.KilogramForceMillimeter, "kgf·mm")] + [InlineData("en-US", TorqueUnit.KilonewtonCentimeter, "kN·cm")] + [InlineData("en-US", TorqueUnit.KilonewtonMeter, "kN·m")] + [InlineData("en-US", TorqueUnit.KilonewtonMillimeter, "kN·mm")] + [InlineData("en-US", TorqueUnit.KilopoundForceFoot, "kipf·ft")] + [InlineData("en-US", TorqueUnit.KilopoundForceInch, "kipf·in")] + [InlineData("en-US", TorqueUnit.MeganewtonCentimeter, "MN·cm")] + [InlineData("en-US", TorqueUnit.MeganewtonMeter, "MN·m")] + [InlineData("en-US", TorqueUnit.MeganewtonMillimeter, "MN·mm")] + [InlineData("en-US", TorqueUnit.MegapoundForceFoot, "Mlbf·ft")] + [InlineData("en-US", TorqueUnit.MegapoundForceInch, "Mlbf·in")] + [InlineData("en-US", TorqueUnit.NewtonCentimeter, "N·cm")] + [InlineData("en-US", TorqueUnit.NewtonMeter, "N·m")] + [InlineData("en-US", TorqueUnit.NewtonMillimeter, "N·mm")] + [InlineData("en-US", TorqueUnit.PoundalFoot, "pdl·ft")] + [InlineData("en-US", TorqueUnit.PoundForceFoot, "lbf·ft")] + [InlineData("en-US", TorqueUnit.PoundForceInch, "lbf·in")] + [InlineData("en-US", TorqueUnit.TonneForceCentimeter, "tf·cm")] + [InlineData("en-US", TorqueUnit.TonneForceMeter, "tf·m")] + [InlineData("en-US", TorqueUnit.TonneForceMillimeter, "tf·mm")] + [InlineData("ru-RU", TorqueUnit.KilonewtonMeter, "кН·м")] + [InlineData("ru-RU", TorqueUnit.MeganewtonMeter, "МН·м")] + [InlineData("ru-RU", TorqueUnit.NewtonMeter, "Н·м")] + public void GetAbbreviationForCulture(string culture, TorqueUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Torque.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Torque.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Torque.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(TorqueUnit unit) @@ -1189,6 +955,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); }); } @@ -1212,56 +979,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] @@ -1307,8 +1076,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); @@ -1345,23 +1112,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = Torque.FromNewtonMeters(1); - Assert.True(v.Equals(Torque.FromNewtonMeters(1), NewtonMetersTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Torque.Zero, NewtonMetersTolerance, ComparisonType.Relative)); - Assert.True(Torque.FromNewtonMeters(100).Equals(Torque.FromNewtonMeters(120), 0.3, ComparisonType.Relative)); - Assert.False(Torque.FromNewtonMeters(100).Equals(Torque.FromNewtonMeters(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = Torque.FromNewtonMeters(1); - Assert.Throws(() => v.Equals(Torque.FromNewtonMeters(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1376,6 +1126,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(newtonmeter.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = Torque.FromNewtonMeters(1); + var negativeTolerance = Torque.FromNewtonMeters(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1392,6 +1168,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() { @@ -1498,158 +1286,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Torque))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(TorqueUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal(Torque.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal(Torque.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal(new {Torque.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 7c6074e518..63f934ea8c 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TurbidityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TurbidityTestsBase.g.cs @@ -88,15 +88,33 @@ public void Ctor_WithNaNValue_DoNotThrowsArgumentException() [Fact] public void Turbidity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + TurbidityUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Turbidity(1, TurbidityUnit.NTU); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Turbidity.Zero, quantityInfo.Zero); Assert.Equal("Turbidity", quantityInfo.Name); + Assert.Equal(Turbidity.Zero, quantityInfo.Zero); + Assert.Equal(Turbidity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Turbidity.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -110,7 +128,7 @@ public void NTUToTurbidityUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Turbidity.From(1, TurbidityUnit.NTU); - AssertEx.EqualTolerance(1, quantity00.NTU, NTUTolerance); + Assert.Equal(1, quantity00.NTU); Assert.Equal(TurbidityUnit.NTU, quantity00.Unit); } @@ -207,27 +225,24 @@ public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 NTU", TurbidityUnit.NTU, 4.2)] + public void Parse(string culture, string quantityString, TurbidityUnit expectedUnit, decimal expectedValue) { - try - { - var parsed = Turbidity.Parse("1 NTU", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NTU, NTUTolerance); - Assert.Equal(TurbidityUnit.NTU, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = Turbidity.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 NTU", TurbidityUnit.NTU, 4.2)] + public void TryParse(string culture, string quantityString, TurbidityUnit expectedUnit, decimal expectedValue) { - { - Assert.True(Turbidity.TryParse("1 NTU", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NTU, NTUTolerance); - Assert.Equal(TurbidityUnit.NTU, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(Turbidity.TryParse(quantityString, out Turbidity parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -304,6 +319,27 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Turbid Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", TurbidityUnit.NTU, "NTU")] + public void GetAbbreviationForCulture(string culture, TurbidityUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Turbidity.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Turbidity.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Turbidity.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(TurbidityUnit unit) @@ -334,6 +370,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); }); } @@ -357,32 +394,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] @@ -428,7 +467,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); @@ -466,34 +504,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = Turbidity.FromNTU(1); - Assert.True(v.Equals(Turbidity.FromNTU(1), NTUTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Turbidity.Zero, NTUTolerance, ComparisonType.Relative)); - Assert.True(Turbidity.FromNTU(100).Equals(Turbidity.FromNTU(120), 0.3, ComparisonType.Relative)); - Assert.False(Turbidity.FromNTU(100).Equals(Turbidity.FromNTU(120), 0.1, ComparisonType.Relative)); + Turbidity ntu = Turbidity.FromNTU(1); + Assert.False(ntu.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = Turbidity.FromNTU(1); - Assert.Throws(() => v.Equals(Turbidity.FromNTU(1), -1, ComparisonType.Relative)); + Turbidity ntu = Turbidity.FromNTU(1); + Assert.False(ntu.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - Turbidity ntu = Turbidity.FromNTU(1); - Assert.False(ntu.Equals(new object())); + var quantity = Turbidity.FromNTU(firstValue); + var otherQuantity = Turbidity.FromNTU(secondValue); + Turbidity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - Turbidity ntu = Turbidity.FromNTU(1); - Assert.False(ntu.Equals(null)); + var quantity = Turbidity.FromNTU(1); + var negativeTolerance = Turbidity.FromNTU(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -512,6 +559,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() { @@ -570,158 +629,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Turbidity.FromNTU(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Turbidity.FromNTU(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Turbidity.FromNTU(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Turbidity.FromNTU(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Turbidity.FromNTU(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Turbidity.FromNTU(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Turbidity.FromNTU(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Turbidity.FromNTU(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Turbidity.FromNTU(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Turbidity.FromNTU(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Turbidity.FromNTU(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Turbidity.FromNTU(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Turbidity.FromNTU(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Turbidity.FromNTU(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Turbidity.FromNTU(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Turbidity.FromNTU(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Turbidity))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Turbidity.FromNTU(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(TurbidityUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Turbidity.FromNTU(1.0); - Assert.Equal(Turbidity.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Turbidity.FromNTU(1.0); - Assert.Equal(Turbidity.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Turbidity.FromNTU(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Turbidity.FromNTU(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Turbidity.FromNTU(1.0); - Assert.Equal(new {Turbidity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 6006f4dd98..822fba0631 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VitaminATestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VitaminATestsBase.g.cs @@ -88,15 +88,33 @@ public void Ctor_WithNaNValue_DoNotThrowsArgumentException() [Fact] public void VitaminA_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + VitaminAUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new VitaminA(1, VitaminAUnit.InternationalUnit); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(VitaminA.Zero, quantityInfo.Zero); Assert.Equal("VitaminA", quantityInfo.Name); + Assert.Equal(VitaminA.Zero, quantityInfo.Zero); + Assert.Equal(VitaminA.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(VitaminA.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -110,7 +128,7 @@ public void InternationalUnitToVitaminAUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = VitaminA.From(1, VitaminAUnit.InternationalUnit); - AssertEx.EqualTolerance(1, quantity00.InternationalUnits, InternationalUnitsTolerance); + Assert.Equal(1, quantity00.InternationalUnits); Assert.Equal(VitaminAUnit.InternationalUnit, quantity00.Unit); } @@ -207,27 +225,24 @@ public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 IU", VitaminAUnit.InternationalUnit, 4.2)] + public void Parse(string culture, string quantityString, VitaminAUnit expectedUnit, decimal expectedValue) { - try - { - var parsed = VitaminA.Parse("1 IU", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InternationalUnits, InternationalUnitsTolerance); - Assert.Equal(VitaminAUnit.InternationalUnit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = VitaminA.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 IU", VitaminAUnit.InternationalUnit, 4.2)] + public void TryParse(string culture, string quantityString, VitaminAUnit expectedUnit, decimal expectedValue) { - { - Assert.True(VitaminA.TryParse("1 IU", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InternationalUnits, InternationalUnitsTolerance); - Assert.Equal(VitaminAUnit.InternationalUnit, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(VitaminA.TryParse(quantityString, out VitaminA parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -304,6 +319,27 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Vitami Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", VitaminAUnit.InternationalUnit, "IU")] + public void GetAbbreviationForCulture(string culture, VitaminAUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = VitaminA.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(VitaminA.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = VitaminA.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(VitaminAUnit unit) @@ -334,6 +370,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); }); } @@ -357,32 +394,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] @@ -428,7 +467,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); @@ -466,34 +504,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = VitaminA.FromInternationalUnits(1); - Assert.True(v.Equals(VitaminA.FromInternationalUnits(1), InternationalUnitsTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(VitaminA.Zero, InternationalUnitsTolerance, ComparisonType.Relative)); - Assert.True(VitaminA.FromInternationalUnits(100).Equals(VitaminA.FromInternationalUnits(120), 0.3, ComparisonType.Relative)); - Assert.False(VitaminA.FromInternationalUnits(100).Equals(VitaminA.FromInternationalUnits(120), 0.1, ComparisonType.Relative)); + VitaminA internationalunit = VitaminA.FromInternationalUnits(1); + Assert.False(internationalunit.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = VitaminA.FromInternationalUnits(1); - Assert.Throws(() => v.Equals(VitaminA.FromInternationalUnits(1), -1, ComparisonType.Relative)); + VitaminA internationalunit = VitaminA.FromInternationalUnits(1); + Assert.False(internationalunit.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - VitaminA internationalunit = VitaminA.FromInternationalUnits(1); - Assert.False(internationalunit.Equals(new object())); + var quantity = VitaminA.FromInternationalUnits(firstValue); + var otherQuantity = VitaminA.FromInternationalUnits(secondValue); + VitaminA maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - VitaminA internationalunit = VitaminA.FromInternationalUnits(1); - Assert.False(internationalunit.Equals(null)); + var quantity = VitaminA.FromInternationalUnits(1); + var negativeTolerance = VitaminA.FromInternationalUnits(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -512,6 +559,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() { @@ -570,158 +629,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(VitaminA))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(VitaminAUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal(VitaminA.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal(VitaminA.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal(new {VitaminA.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 486cbf8750..d2b642c803 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeConcentrationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeConcentrationTestsBase.g.cs @@ -164,15 +164,33 @@ public void Ctor_WithNaNValue_DoNotThrowsArgumentException() [Fact] public void VolumeConcentration_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + VolumeConcentrationUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new VolumeConcentration(1, VolumeConcentrationUnit.DecimalFraction); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(VolumeConcentration.Zero, quantityInfo.Zero); Assert.Equal("VolumeConcentration", quantityInfo.Name); + Assert.Equal(VolumeConcentration.Zero, quantityInfo.Zero); + Assert.Equal(VolumeConcentration.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(VolumeConcentration.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + [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] @@ -205,83 +223,83 @@ public void DecimalFractionToVolumeConcentrationUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = VolumeConcentration.From(1, VolumeConcentrationUnit.CentiliterPerLiter); - AssertEx.EqualTolerance(1, quantity00.CentilitersPerLiter, CentilitersPerLiterTolerance); + Assert.Equal(1, quantity00.CentilitersPerLiter); Assert.Equal(VolumeConcentrationUnit.CentiliterPerLiter, quantity00.Unit); var quantity01 = VolumeConcentration.From(1, VolumeConcentrationUnit.CentiliterPerMilliliter); - AssertEx.EqualTolerance(1, quantity01.CentilitersPerMilliliter, CentilitersPerMilliliterTolerance); + Assert.Equal(1, quantity01.CentilitersPerMilliliter); Assert.Equal(VolumeConcentrationUnit.CentiliterPerMilliliter, quantity01.Unit); var quantity02 = VolumeConcentration.From(1, VolumeConcentrationUnit.DeciliterPerLiter); - AssertEx.EqualTolerance(1, quantity02.DecilitersPerLiter, DecilitersPerLiterTolerance); + Assert.Equal(1, quantity02.DecilitersPerLiter); Assert.Equal(VolumeConcentrationUnit.DeciliterPerLiter, quantity02.Unit); var quantity03 = VolumeConcentration.From(1, VolumeConcentrationUnit.DeciliterPerMilliliter); - AssertEx.EqualTolerance(1, quantity03.DecilitersPerMilliliter, DecilitersPerMilliliterTolerance); + Assert.Equal(1, quantity03.DecilitersPerMilliliter); Assert.Equal(VolumeConcentrationUnit.DeciliterPerMilliliter, quantity03.Unit); var quantity04 = VolumeConcentration.From(1, VolumeConcentrationUnit.DecimalFraction); - AssertEx.EqualTolerance(1, quantity04.DecimalFractions, DecimalFractionsTolerance); + Assert.Equal(1, quantity04.DecimalFractions); Assert.Equal(VolumeConcentrationUnit.DecimalFraction, quantity04.Unit); var quantity05 = VolumeConcentration.From(1, VolumeConcentrationUnit.LiterPerLiter); - AssertEx.EqualTolerance(1, quantity05.LitersPerLiter, LitersPerLiterTolerance); + Assert.Equal(1, quantity05.LitersPerLiter); Assert.Equal(VolumeConcentrationUnit.LiterPerLiter, quantity05.Unit); var quantity06 = VolumeConcentration.From(1, VolumeConcentrationUnit.LiterPerMilliliter); - AssertEx.EqualTolerance(1, quantity06.LitersPerMilliliter, LitersPerMilliliterTolerance); + Assert.Equal(1, quantity06.LitersPerMilliliter); Assert.Equal(VolumeConcentrationUnit.LiterPerMilliliter, quantity06.Unit); var quantity07 = VolumeConcentration.From(1, VolumeConcentrationUnit.MicroliterPerLiter); - AssertEx.EqualTolerance(1, quantity07.MicrolitersPerLiter, MicrolitersPerLiterTolerance); + Assert.Equal(1, quantity07.MicrolitersPerLiter); Assert.Equal(VolumeConcentrationUnit.MicroliterPerLiter, quantity07.Unit); var quantity08 = VolumeConcentration.From(1, VolumeConcentrationUnit.MicroliterPerMilliliter); - AssertEx.EqualTolerance(1, quantity08.MicrolitersPerMilliliter, MicrolitersPerMilliliterTolerance); + Assert.Equal(1, quantity08.MicrolitersPerMilliliter); Assert.Equal(VolumeConcentrationUnit.MicroliterPerMilliliter, quantity08.Unit); var quantity09 = VolumeConcentration.From(1, VolumeConcentrationUnit.MilliliterPerLiter); - AssertEx.EqualTolerance(1, quantity09.MillilitersPerLiter, MillilitersPerLiterTolerance); + Assert.Equal(1, quantity09.MillilitersPerLiter); Assert.Equal(VolumeConcentrationUnit.MilliliterPerLiter, quantity09.Unit); var quantity10 = VolumeConcentration.From(1, VolumeConcentrationUnit.MilliliterPerMilliliter); - AssertEx.EqualTolerance(1, quantity10.MillilitersPerMilliliter, MillilitersPerMilliliterTolerance); + Assert.Equal(1, quantity10.MillilitersPerMilliliter); Assert.Equal(VolumeConcentrationUnit.MilliliterPerMilliliter, quantity10.Unit); var quantity11 = VolumeConcentration.From(1, VolumeConcentrationUnit.NanoliterPerLiter); - AssertEx.EqualTolerance(1, quantity11.NanolitersPerLiter, NanolitersPerLiterTolerance); + Assert.Equal(1, quantity11.NanolitersPerLiter); Assert.Equal(VolumeConcentrationUnit.NanoliterPerLiter, quantity11.Unit); var quantity12 = VolumeConcentration.From(1, VolumeConcentrationUnit.NanoliterPerMilliliter); - AssertEx.EqualTolerance(1, quantity12.NanolitersPerMilliliter, NanolitersPerMilliliterTolerance); + Assert.Equal(1, quantity12.NanolitersPerMilliliter); Assert.Equal(VolumeConcentrationUnit.NanoliterPerMilliliter, quantity12.Unit); var quantity13 = VolumeConcentration.From(1, VolumeConcentrationUnit.PartPerBillion); - AssertEx.EqualTolerance(1, quantity13.PartsPerBillion, PartsPerBillionTolerance); + Assert.Equal(1, quantity13.PartsPerBillion); Assert.Equal(VolumeConcentrationUnit.PartPerBillion, quantity13.Unit); var quantity14 = VolumeConcentration.From(1, VolumeConcentrationUnit.PartPerMillion); - AssertEx.EqualTolerance(1, quantity14.PartsPerMillion, PartsPerMillionTolerance); + Assert.Equal(1, quantity14.PartsPerMillion); Assert.Equal(VolumeConcentrationUnit.PartPerMillion, quantity14.Unit); var quantity15 = VolumeConcentration.From(1, VolumeConcentrationUnit.PartPerThousand); - AssertEx.EqualTolerance(1, quantity15.PartsPerThousand, PartsPerThousandTolerance); + Assert.Equal(1, quantity15.PartsPerThousand); Assert.Equal(VolumeConcentrationUnit.PartPerThousand, quantity15.Unit); var quantity16 = VolumeConcentration.From(1, VolumeConcentrationUnit.PartPerTrillion); - AssertEx.EqualTolerance(1, quantity16.PartsPerTrillion, PartsPerTrillionTolerance); + Assert.Equal(1, quantity16.PartsPerTrillion); Assert.Equal(VolumeConcentrationUnit.PartPerTrillion, quantity16.Unit); var quantity17 = VolumeConcentration.From(1, VolumeConcentrationUnit.Percent); - AssertEx.EqualTolerance(1, quantity17.Percent, PercentTolerance); + Assert.Equal(1, quantity17.Percent); Assert.Equal(VolumeConcentrationUnit.Percent, quantity17.Unit); var quantity18 = VolumeConcentration.From(1, VolumeConcentrationUnit.PicoliterPerLiter); - AssertEx.EqualTolerance(1, quantity18.PicolitersPerLiter, PicolitersPerLiterTolerance); + Assert.Equal(1, quantity18.PicolitersPerLiter); Assert.Equal(VolumeConcentrationUnit.PicoliterPerLiter, quantity18.Unit); var quantity19 = VolumeConcentration.From(1, VolumeConcentrationUnit.PicoliterPerMilliliter); - AssertEx.EqualTolerance(1, quantity19.PicolitersPerMilliliter, PicolitersPerMilliliterTolerance); + Assert.Equal(1, quantity19.PicolitersPerMilliliter); Assert.Equal(VolumeConcentrationUnit.PicoliterPerMilliliter, quantity19.Unit); } @@ -397,287 +415,64 @@ public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 cl/l", VolumeConcentrationUnit.CentiliterPerLiter, 4.2)] + [InlineData("en-US", "4.2 cl/ml", VolumeConcentrationUnit.CentiliterPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 dl/l", VolumeConcentrationUnit.DeciliterPerLiter, 4.2)] + [InlineData("en-US", "4.2 dl/ml", VolumeConcentrationUnit.DeciliterPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 ", VolumeConcentrationUnit.DecimalFraction, 4.2)] + [InlineData("en-US", "4.2 l/l", VolumeConcentrationUnit.LiterPerLiter, 4.2)] + [InlineData("en-US", "4.2 l/ml", VolumeConcentrationUnit.LiterPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 µl/l", VolumeConcentrationUnit.MicroliterPerLiter, 4.2)] + [InlineData("en-US", "4.2 µl/ml", VolumeConcentrationUnit.MicroliterPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 ml/l", VolumeConcentrationUnit.MilliliterPerLiter, 4.2)] + [InlineData("en-US", "4.2 ml/ml", VolumeConcentrationUnit.MilliliterPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 nl/l", VolumeConcentrationUnit.NanoliterPerLiter, 4.2)] + [InlineData("en-US", "4.2 nl/ml", VolumeConcentrationUnit.NanoliterPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 ppb", VolumeConcentrationUnit.PartPerBillion, 4.2)] + [InlineData("en-US", "4.2 ppm", VolumeConcentrationUnit.PartPerMillion, 4.2)] + [InlineData("en-US", "4.2 ‰", VolumeConcentrationUnit.PartPerThousand, 4.2)] + [InlineData("en-US", "4.2 ppt", VolumeConcentrationUnit.PartPerTrillion, 4.2)] + [InlineData("en-US", "4.2 %", VolumeConcentrationUnit.Percent, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = VolumeConcentration.Parse("1 cl/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentilitersPerLiter, CentilitersPerLiterTolerance); - Assert.Equal(VolumeConcentrationUnit.CentiliterPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeConcentration.Parse("1 cl/ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentilitersPerMilliliter, CentilitersPerMilliliterTolerance); - Assert.Equal(VolumeConcentrationUnit.CentiliterPerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeConcentration.Parse("1 dl/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecilitersPerLiter, DecilitersPerLiterTolerance); - Assert.Equal(VolumeConcentrationUnit.DeciliterPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeConcentration.Parse("1 dl/ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecilitersPerMilliliter, DecilitersPerMilliliterTolerance); - Assert.Equal(VolumeConcentrationUnit.DeciliterPerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeConcentration.Parse("1 ", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecimalFractions, DecimalFractionsTolerance); - Assert.Equal(VolumeConcentrationUnit.DecimalFraction, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeConcentration.Parse("1 l/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.LitersPerLiter, LitersPerLiterTolerance); - Assert.Equal(VolumeConcentrationUnit.LiterPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeConcentration.Parse("1 l/ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.LitersPerMilliliter, LitersPerMilliliterTolerance); - Assert.Equal(VolumeConcentrationUnit.LiterPerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeConcentration.Parse("1 µl/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerLiter, MicrolitersPerLiterTolerance); - Assert.Equal(VolumeConcentrationUnit.MicroliterPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeConcentration.Parse("1 µl/ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerMilliliter, MicrolitersPerMilliliterTolerance); - Assert.Equal(VolumeConcentrationUnit.MicroliterPerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeConcentration.Parse("1 ml/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillilitersPerLiter, MillilitersPerLiterTolerance); - Assert.Equal(VolumeConcentrationUnit.MilliliterPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeConcentration.Parse("1 ml/ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillilitersPerMilliliter, MillilitersPerMilliliterTolerance); - Assert.Equal(VolumeConcentrationUnit.MilliliterPerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeConcentration.Parse("1 nl/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanolitersPerLiter, NanolitersPerLiterTolerance); - Assert.Equal(VolumeConcentrationUnit.NanoliterPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeConcentration.Parse("1 nl/ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanolitersPerMilliliter, NanolitersPerMilliliterTolerance); - Assert.Equal(VolumeConcentrationUnit.NanoliterPerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeConcentration.Parse("1 ppb", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PartsPerBillion, PartsPerBillionTolerance); - Assert.Equal(VolumeConcentrationUnit.PartPerBillion, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeConcentration.Parse("1 ppm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PartsPerMillion, PartsPerMillionTolerance); - Assert.Equal(VolumeConcentrationUnit.PartPerMillion, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeConcentration.Parse("1 ‰", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PartsPerThousand, PartsPerThousandTolerance); - Assert.Equal(VolumeConcentrationUnit.PartPerThousand, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeConcentration.Parse("1 ppt", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PartsPerTrillion, PartsPerTrillionTolerance); - Assert.Equal(VolumeConcentrationUnit.PartPerTrillion, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeConcentration.Parse("1 %", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Percent, PercentTolerance); - Assert.Equal(VolumeConcentrationUnit.Percent, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeConcentration.Parse("1 % (v/v)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Percent, PercentTolerance); - Assert.Equal(VolumeConcentrationUnit.Percent, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeConcentration.Parse("1 pl/l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PicolitersPerLiter, PicolitersPerLiterTolerance); - Assert.Equal(VolumeConcentrationUnit.PicoliterPerLiter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeConcentration.Parse("1 pl/ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.PicolitersPerMilliliter, PicolitersPerMilliliterTolerance); - Assert.Equal(VolumeConcentrationUnit.PicoliterPerMilliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = VolumeConcentration.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 cl/l", VolumeConcentrationUnit.CentiliterPerLiter, 4.2)] + [InlineData("en-US", "4.2 cl/ml", VolumeConcentrationUnit.CentiliterPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 dl/l", VolumeConcentrationUnit.DeciliterPerLiter, 4.2)] + [InlineData("en-US", "4.2 dl/ml", VolumeConcentrationUnit.DeciliterPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 ", VolumeConcentrationUnit.DecimalFraction, 4.2)] + [InlineData("en-US", "4.2 l/l", VolumeConcentrationUnit.LiterPerLiter, 4.2)] + [InlineData("en-US", "4.2 l/ml", VolumeConcentrationUnit.LiterPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 µl/l", VolumeConcentrationUnit.MicroliterPerLiter, 4.2)] + [InlineData("en-US", "4.2 µl/ml", VolumeConcentrationUnit.MicroliterPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 ml/l", VolumeConcentrationUnit.MilliliterPerLiter, 4.2)] + [InlineData("en-US", "4.2 ml/ml", VolumeConcentrationUnit.MilliliterPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 nl/l", VolumeConcentrationUnit.NanoliterPerLiter, 4.2)] + [InlineData("en-US", "4.2 nl/ml", VolumeConcentrationUnit.NanoliterPerMilliliter, 4.2)] + [InlineData("en-US", "4.2 ppb", VolumeConcentrationUnit.PartPerBillion, 4.2)] + [InlineData("en-US", "4.2 ppm", VolumeConcentrationUnit.PartPerMillion, 4.2)] + [InlineData("en-US", "4.2 ‰", VolumeConcentrationUnit.PartPerThousand, 4.2)] + [InlineData("en-US", "4.2 ppt", VolumeConcentrationUnit.PartPerTrillion, 4.2)] + [InlineData("en-US", "4.2 %", VolumeConcentrationUnit.Percent, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(VolumeConcentration.TryParse("1 cl/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentilitersPerLiter, CentilitersPerLiterTolerance); - Assert.Equal(VolumeConcentrationUnit.CentiliterPerLiter, parsed.Unit); - } - - { - Assert.True(VolumeConcentration.TryParse("1 cl/ml", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentilitersPerMilliliter, CentilitersPerMilliliterTolerance); - Assert.Equal(VolumeConcentrationUnit.CentiliterPerMilliliter, parsed.Unit); - } - - { - Assert.True(VolumeConcentration.TryParse("1 dl/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecilitersPerLiter, DecilitersPerLiterTolerance); - Assert.Equal(VolumeConcentrationUnit.DeciliterPerLiter, parsed.Unit); - } - - { - Assert.True(VolumeConcentration.TryParse("1 dl/ml", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecilitersPerMilliliter, DecilitersPerMilliliterTolerance); - Assert.Equal(VolumeConcentrationUnit.DeciliterPerMilliliter, parsed.Unit); - } - - { - Assert.True(VolumeConcentration.TryParse("1 ", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecimalFractions, DecimalFractionsTolerance); - Assert.Equal(VolumeConcentrationUnit.DecimalFraction, parsed.Unit); - } - - { - Assert.True(VolumeConcentration.TryParse("1 l/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.LitersPerLiter, LitersPerLiterTolerance); - Assert.Equal(VolumeConcentrationUnit.LiterPerLiter, parsed.Unit); - } - - { - Assert.True(VolumeConcentration.TryParse("1 l/ml", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.LitersPerMilliliter, LitersPerMilliliterTolerance); - Assert.Equal(VolumeConcentrationUnit.LiterPerMilliliter, parsed.Unit); - } - - { - Assert.True(VolumeConcentration.TryParse("1 µl/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerLiter, MicrolitersPerLiterTolerance); - Assert.Equal(VolumeConcentrationUnit.MicroliterPerLiter, parsed.Unit); - } - - { - Assert.True(VolumeConcentration.TryParse("1 µl/ml", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerMilliliter, MicrolitersPerMilliliterTolerance); - Assert.Equal(VolumeConcentrationUnit.MicroliterPerMilliliter, parsed.Unit); - } - - { - Assert.True(VolumeConcentration.TryParse("1 ml/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillilitersPerLiter, MillilitersPerLiterTolerance); - Assert.Equal(VolumeConcentrationUnit.MilliliterPerLiter, parsed.Unit); - } - - { - Assert.True(VolumeConcentration.TryParse("1 ml/ml", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillilitersPerMilliliter, MillilitersPerMilliliterTolerance); - Assert.Equal(VolumeConcentrationUnit.MilliliterPerMilliliter, parsed.Unit); - } - - { - Assert.True(VolumeConcentration.TryParse("1 nl/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanolitersPerLiter, NanolitersPerLiterTolerance); - Assert.Equal(VolumeConcentrationUnit.NanoliterPerLiter, parsed.Unit); - } - - { - Assert.True(VolumeConcentration.TryParse("1 nl/ml", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanolitersPerMilliliter, NanolitersPerMilliliterTolerance); - Assert.Equal(VolumeConcentrationUnit.NanoliterPerMilliliter, parsed.Unit); - } - - { - Assert.True(VolumeConcentration.TryParse("1 ppb", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PartsPerBillion, PartsPerBillionTolerance); - Assert.Equal(VolumeConcentrationUnit.PartPerBillion, parsed.Unit); - } - - { - Assert.True(VolumeConcentration.TryParse("1 ppm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PartsPerMillion, PartsPerMillionTolerance); - Assert.Equal(VolumeConcentrationUnit.PartPerMillion, parsed.Unit); - } - - { - Assert.True(VolumeConcentration.TryParse("1 ‰", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PartsPerThousand, PartsPerThousandTolerance); - Assert.Equal(VolumeConcentrationUnit.PartPerThousand, parsed.Unit); - } - - { - Assert.True(VolumeConcentration.TryParse("1 ppt", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PartsPerTrillion, PartsPerTrillionTolerance); - Assert.Equal(VolumeConcentrationUnit.PartPerTrillion, parsed.Unit); - } - - { - Assert.True(VolumeConcentration.TryParse("1 %", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Percent, PercentTolerance); - Assert.Equal(VolumeConcentrationUnit.Percent, parsed.Unit); - } - - { - Assert.True(VolumeConcentration.TryParse("1 % (v/v)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Percent, PercentTolerance); - Assert.Equal(VolumeConcentrationUnit.Percent, parsed.Unit); - } - - { - Assert.True(VolumeConcentration.TryParse("1 pl/l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PicolitersPerLiter, PicolitersPerLiterTolerance); - Assert.Equal(VolumeConcentrationUnit.PicoliterPerLiter, parsed.Unit); - } - - { - Assert.True(VolumeConcentration.TryParse("1 pl/ml", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.PicolitersPerMilliliter, PicolitersPerMilliliterTolerance); - Assert.Equal(VolumeConcentrationUnit.PicoliterPerMilliliter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(VolumeConcentration.TryParse(quantityString, out VolumeConcentration parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -914,6 +709,46 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Volume Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", VolumeConcentrationUnit.CentiliterPerLiter, "cl/l")] + [InlineData("en-US", VolumeConcentrationUnit.CentiliterPerMilliliter, "cl/ml")] + [InlineData("en-US", VolumeConcentrationUnit.DeciliterPerLiter, "dl/l")] + [InlineData("en-US", VolumeConcentrationUnit.DeciliterPerMilliliter, "dl/ml")] + [InlineData("en-US", VolumeConcentrationUnit.DecimalFraction, "")] + [InlineData("en-US", VolumeConcentrationUnit.LiterPerLiter, "l/l")] + [InlineData("en-US", VolumeConcentrationUnit.LiterPerMilliliter, "l/ml")] + [InlineData("en-US", VolumeConcentrationUnit.MicroliterPerLiter, "µl/l")] + [InlineData("en-US", VolumeConcentrationUnit.MicroliterPerMilliliter, "µl/ml")] + [InlineData("en-US", VolumeConcentrationUnit.MilliliterPerLiter, "ml/l")] + [InlineData("en-US", VolumeConcentrationUnit.MilliliterPerMilliliter, "ml/ml")] + [InlineData("en-US", VolumeConcentrationUnit.NanoliterPerLiter, "nl/l")] + [InlineData("en-US", VolumeConcentrationUnit.NanoliterPerMilliliter, "nl/ml")] + [InlineData("en-US", VolumeConcentrationUnit.PartPerBillion, "ppb")] + [InlineData("en-US", VolumeConcentrationUnit.PartPerMillion, "ppm")] + [InlineData("en-US", VolumeConcentrationUnit.PartPerThousand, "‰")] + [InlineData("en-US", VolumeConcentrationUnit.PartPerTrillion, "ppt")] + [InlineData("en-US", VolumeConcentrationUnit.Percent, "%")] + [InlineData("en-US", VolumeConcentrationUnit.PicoliterPerLiter, "pl/l")] + [InlineData("en-US", VolumeConcentrationUnit.PicoliterPerMilliliter, "pl/ml")] + public void GetAbbreviationForCulture(string culture, VolumeConcentrationUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = VolumeConcentration.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(VolumeConcentration.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = VolumeConcentration.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(VolumeConcentrationUnit unit) @@ -944,6 +779,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); }); } @@ -967,51 +803,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] @@ -1057,8 +895,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); @@ -1095,23 +931,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = VolumeConcentration.FromDecimalFractions(1); - Assert.True(v.Equals(VolumeConcentration.FromDecimalFractions(1), DecimalFractionsTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(VolumeConcentration.Zero, DecimalFractionsTolerance, ComparisonType.Relative)); - Assert.True(VolumeConcentration.FromDecimalFractions(100).Equals(VolumeConcentration.FromDecimalFractions(120), 0.3, ComparisonType.Relative)); - Assert.False(VolumeConcentration.FromDecimalFractions(100).Equals(VolumeConcentration.FromDecimalFractions(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = VolumeConcentration.FromDecimalFractions(1); - Assert.Throws(() => v.Equals(VolumeConcentration.FromDecimalFractions(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -1126,6 +945,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(decimalfraction.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = VolumeConcentration.FromDecimalFractions(1); + var negativeTolerance = VolumeConcentration.FromDecimalFractions(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -1142,6 +987,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() { @@ -1238,158 +1095,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(VolumeConcentration))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(VolumeConcentrationUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal(VolumeConcentration.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal(VolumeConcentration.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal(new {VolumeConcentration.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 3d846e5a0c..1c1edca130 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowPerAreaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowPerAreaTestsBase.g.cs @@ -100,7 +100,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new VolumeFlowPerArea(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -113,15 +113,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void VolumeFlowPerArea_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + VolumeFlowPerAreaUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new VolumeFlowPerArea(1, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(VolumeFlowPerArea.Zero, quantityInfo.Zero); Assert.Equal("VolumeFlowPerArea", quantityInfo.Name); + Assert.Equal(VolumeFlowPerArea.Zero, quantityInfo.Zero); + Assert.Equal(VolumeFlowPerArea.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(VolumeFlowPerArea.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void VolumeFlowPerAreaInfo_CreateWithCustomUnitInfos() + { + VolumeFlowPerAreaUnit[] expectedUnits = [VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -136,11 +154,11 @@ public void CubicMeterPerSecondPerSquareMeterToVolumeFlowPerAreaUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = VolumeFlowPerArea.From(1, VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot); - AssertEx.EqualTolerance(1, quantity00.CubicFeetPerMinutePerSquareFoot, CubicFeetPerMinutePerSquareFootTolerance); + Assert.Equal(1, quantity00.CubicFeetPerMinutePerSquareFoot); Assert.Equal(VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot, quantity00.Unit); var quantity01 = VolumeFlowPerArea.From(1, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter); - AssertEx.EqualTolerance(1, quantity01.CubicMetersPerSecondPerSquareMeter, CubicMetersPerSecondPerSquareMeterTolerance); + Assert.Equal(1, quantity01.CubicMetersPerSecondPerSquareMeter); Assert.Equal(VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, quantity01.Unit); } @@ -277,40 +295,26 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [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, decimal expectedValue) { - try - { - var parsed = VolumeFlowPerArea.Parse("1 CFM/ft²", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicFeetPerMinutePerSquareFoot, CubicFeetPerMinutePerSquareFootTolerance); - Assert.Equal(VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlowPerArea.Parse("1 m³/(s·m²)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicMetersPerSecondPerSquareMeter, CubicMetersPerSecondPerSquareMeterTolerance); - Assert.Equal(VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = VolumeFlowPerArea.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [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, decimal expectedValue) { - { - Assert.True(VolumeFlowPerArea.TryParse("1 CFM/ft²", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicFeetPerMinutePerSquareFoot, CubicFeetPerMinutePerSquareFootTolerance); - Assert.Equal(VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot, parsed.Unit); - } - - { - Assert.True(VolumeFlowPerArea.TryParse("1 m³/(s·m²)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicMetersPerSecondPerSquareMeter, CubicMetersPerSecondPerSquareMeterTolerance); - Assert.Equal(VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(VolumeFlowPerArea.TryParse(quantityString, out VolumeFlowPerArea parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -395,6 +399,28 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Volume Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot, "CFM/ft²")] + [InlineData("en-US", VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, "m³/(s·m²)")] + public void GetAbbreviationForCulture(string culture, VolumeFlowPerAreaUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = VolumeFlowPerArea.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(VolumeFlowPerArea.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = VolumeFlowPerArea.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(VolumeFlowPerAreaUnit unit) @@ -425,6 +451,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); }); } @@ -448,33 +475,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] @@ -520,8 +549,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); @@ -559,34 +586,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1); - Assert.True(v.Equals(VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1), CubicMetersPerSecondPerSquareMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(VolumeFlowPerArea.Zero, CubicMetersPerSecondPerSquareMeterTolerance, ComparisonType.Relative)); - Assert.True(VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(100).Equals(VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(100).Equals(VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(120), 0.1, ComparisonType.Relative)); + VolumeFlowPerArea cubicmeterpersecondpersquaremeter = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1); + Assert.False(cubicmeterpersecondpersquaremeter.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1); - Assert.Throws(() => v.Equals(VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1), -1, ComparisonType.Relative)); + VolumeFlowPerArea cubicmeterpersecondpersquaremeter = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1); + Assert.False(cubicmeterpersecondpersquaremeter.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - VolumeFlowPerArea cubicmeterpersecondpersquaremeter = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1); - Assert.False(cubicmeterpersecondpersquaremeter.Equals(new object())); + var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(firstValue); + var otherQuantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(secondValue); + VolumeFlowPerArea maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - VolumeFlowPerArea cubicmeterpersecondpersquaremeter = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1); - Assert.False(cubicmeterpersecondpersquaremeter.Equals(null)); + var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1); + var negativeTolerance = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -605,6 +641,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() { @@ -665,158 +713,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(VolumeFlowPerArea))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(VolumeFlowPerAreaUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal(VolumeFlowPerArea.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal(VolumeFlowPerArea.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal(new {VolumeFlowPerArea.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 525ec31eef..bc8c53d802 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowTestsBase.g.cs @@ -392,7 +392,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new VolumeFlow(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -405,15 +405,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void VolumeFlow_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + VolumeFlowUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new VolumeFlow(1, VolumeFlowUnit.CubicMeterPerSecond); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(VolumeFlow.Zero, quantityInfo.Zero); Assert.Equal("VolumeFlow", quantityInfo.Name); + Assert.Equal(VolumeFlow.Zero, quantityInfo.Zero); + Assert.Equal(VolumeFlow.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(VolumeFlow.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void VolumeFlowInfo_CreateWithCustomUnitInfos() + { + VolumeFlowUnit[] expectedUnits = [VolumeFlowUnit.CubicMeterPerSecond]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -501,303 +519,303 @@ public void CubicMeterPerSecondToVolumeFlowUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = VolumeFlow.From(1, VolumeFlowUnit.AcreFootPerDay); - AssertEx.EqualTolerance(1, quantity00.AcreFeetPerDay, AcreFeetPerDayTolerance); + Assert.Equal(1, quantity00.AcreFeetPerDay); Assert.Equal(VolumeFlowUnit.AcreFootPerDay, quantity00.Unit); var quantity01 = VolumeFlow.From(1, VolumeFlowUnit.AcreFootPerHour); - AssertEx.EqualTolerance(1, quantity01.AcreFeetPerHour, AcreFeetPerHourTolerance); + Assert.Equal(1, quantity01.AcreFeetPerHour); Assert.Equal(VolumeFlowUnit.AcreFootPerHour, quantity01.Unit); var quantity02 = VolumeFlow.From(1, VolumeFlowUnit.AcreFootPerMinute); - AssertEx.EqualTolerance(1, quantity02.AcreFeetPerMinute, AcreFeetPerMinuteTolerance); + Assert.Equal(1, quantity02.AcreFeetPerMinute); Assert.Equal(VolumeFlowUnit.AcreFootPerMinute, quantity02.Unit); var quantity03 = VolumeFlow.From(1, VolumeFlowUnit.AcreFootPerSecond); - AssertEx.EqualTolerance(1, quantity03.AcreFeetPerSecond, AcreFeetPerSecondTolerance); + Assert.Equal(1, quantity03.AcreFeetPerSecond); Assert.Equal(VolumeFlowUnit.AcreFootPerSecond, quantity03.Unit); var quantity04 = VolumeFlow.From(1, VolumeFlowUnit.CentiliterPerDay); - AssertEx.EqualTolerance(1, quantity04.CentilitersPerDay, CentilitersPerDayTolerance); + Assert.Equal(1, quantity04.CentilitersPerDay); Assert.Equal(VolumeFlowUnit.CentiliterPerDay, quantity04.Unit); var quantity05 = VolumeFlow.From(1, VolumeFlowUnit.CentiliterPerHour); - AssertEx.EqualTolerance(1, quantity05.CentilitersPerHour, CentilitersPerHourTolerance); + Assert.Equal(1, quantity05.CentilitersPerHour); Assert.Equal(VolumeFlowUnit.CentiliterPerHour, quantity05.Unit); var quantity06 = VolumeFlow.From(1, VolumeFlowUnit.CentiliterPerMinute); - AssertEx.EqualTolerance(1, quantity06.CentilitersPerMinute, CentilitersPerMinuteTolerance); + Assert.Equal(1, quantity06.CentilitersPerMinute); Assert.Equal(VolumeFlowUnit.CentiliterPerMinute, quantity06.Unit); var quantity07 = VolumeFlow.From(1, VolumeFlowUnit.CentiliterPerSecond); - AssertEx.EqualTolerance(1, quantity07.CentilitersPerSecond, CentilitersPerSecondTolerance); + Assert.Equal(1, quantity07.CentilitersPerSecond); Assert.Equal(VolumeFlowUnit.CentiliterPerSecond, quantity07.Unit); var quantity08 = VolumeFlow.From(1, VolumeFlowUnit.CubicCentimeterPerMinute); - AssertEx.EqualTolerance(1, quantity08.CubicCentimetersPerMinute, CubicCentimetersPerMinuteTolerance); + Assert.Equal(1, quantity08.CubicCentimetersPerMinute); Assert.Equal(VolumeFlowUnit.CubicCentimeterPerMinute, quantity08.Unit); var quantity09 = VolumeFlow.From(1, VolumeFlowUnit.CubicDecimeterPerMinute); - AssertEx.EqualTolerance(1, quantity09.CubicDecimetersPerMinute, CubicDecimetersPerMinuteTolerance); + Assert.Equal(1, quantity09.CubicDecimetersPerMinute); Assert.Equal(VolumeFlowUnit.CubicDecimeterPerMinute, quantity09.Unit); var quantity10 = VolumeFlow.From(1, VolumeFlowUnit.CubicFootPerHour); - AssertEx.EqualTolerance(1, quantity10.CubicFeetPerHour, CubicFeetPerHourTolerance); + Assert.Equal(1, quantity10.CubicFeetPerHour); Assert.Equal(VolumeFlowUnit.CubicFootPerHour, quantity10.Unit); var quantity11 = VolumeFlow.From(1, VolumeFlowUnit.CubicFootPerMinute); - AssertEx.EqualTolerance(1, quantity11.CubicFeetPerMinute, CubicFeetPerMinuteTolerance); + Assert.Equal(1, quantity11.CubicFeetPerMinute); Assert.Equal(VolumeFlowUnit.CubicFootPerMinute, quantity11.Unit); var quantity12 = VolumeFlow.From(1, VolumeFlowUnit.CubicFootPerSecond); - AssertEx.EqualTolerance(1, quantity12.CubicFeetPerSecond, CubicFeetPerSecondTolerance); + Assert.Equal(1, quantity12.CubicFeetPerSecond); Assert.Equal(VolumeFlowUnit.CubicFootPerSecond, quantity12.Unit); var quantity13 = VolumeFlow.From(1, VolumeFlowUnit.CubicMeterPerDay); - AssertEx.EqualTolerance(1, quantity13.CubicMetersPerDay, CubicMetersPerDayTolerance); + Assert.Equal(1, quantity13.CubicMetersPerDay); Assert.Equal(VolumeFlowUnit.CubicMeterPerDay, quantity13.Unit); var quantity14 = VolumeFlow.From(1, VolumeFlowUnit.CubicMeterPerHour); - AssertEx.EqualTolerance(1, quantity14.CubicMetersPerHour, CubicMetersPerHourTolerance); + Assert.Equal(1, quantity14.CubicMetersPerHour); Assert.Equal(VolumeFlowUnit.CubicMeterPerHour, quantity14.Unit); var quantity15 = VolumeFlow.From(1, VolumeFlowUnit.CubicMeterPerMinute); - AssertEx.EqualTolerance(1, quantity15.CubicMetersPerMinute, CubicMetersPerMinuteTolerance); + Assert.Equal(1, quantity15.CubicMetersPerMinute); Assert.Equal(VolumeFlowUnit.CubicMeterPerMinute, quantity15.Unit); var quantity16 = VolumeFlow.From(1, VolumeFlowUnit.CubicMeterPerSecond); - AssertEx.EqualTolerance(1, quantity16.CubicMetersPerSecond, CubicMetersPerSecondTolerance); + Assert.Equal(1, quantity16.CubicMetersPerSecond); Assert.Equal(VolumeFlowUnit.CubicMeterPerSecond, quantity16.Unit); var quantity17 = VolumeFlow.From(1, VolumeFlowUnit.CubicMillimeterPerSecond); - AssertEx.EqualTolerance(1, quantity17.CubicMillimetersPerSecond, CubicMillimetersPerSecondTolerance); + Assert.Equal(1, quantity17.CubicMillimetersPerSecond); Assert.Equal(VolumeFlowUnit.CubicMillimeterPerSecond, quantity17.Unit); var quantity18 = VolumeFlow.From(1, VolumeFlowUnit.CubicYardPerDay); - AssertEx.EqualTolerance(1, quantity18.CubicYardsPerDay, CubicYardsPerDayTolerance); + Assert.Equal(1, quantity18.CubicYardsPerDay); Assert.Equal(VolumeFlowUnit.CubicYardPerDay, quantity18.Unit); var quantity19 = VolumeFlow.From(1, VolumeFlowUnit.CubicYardPerHour); - AssertEx.EqualTolerance(1, quantity19.CubicYardsPerHour, CubicYardsPerHourTolerance); + Assert.Equal(1, quantity19.CubicYardsPerHour); Assert.Equal(VolumeFlowUnit.CubicYardPerHour, quantity19.Unit); var quantity20 = VolumeFlow.From(1, VolumeFlowUnit.CubicYardPerMinute); - AssertEx.EqualTolerance(1, quantity20.CubicYardsPerMinute, CubicYardsPerMinuteTolerance); + Assert.Equal(1, quantity20.CubicYardsPerMinute); Assert.Equal(VolumeFlowUnit.CubicYardPerMinute, quantity20.Unit); var quantity21 = VolumeFlow.From(1, VolumeFlowUnit.CubicYardPerSecond); - AssertEx.EqualTolerance(1, quantity21.CubicYardsPerSecond, CubicYardsPerSecondTolerance); + Assert.Equal(1, quantity21.CubicYardsPerSecond); Assert.Equal(VolumeFlowUnit.CubicYardPerSecond, quantity21.Unit); var quantity22 = VolumeFlow.From(1, VolumeFlowUnit.DecaliterPerDay); - AssertEx.EqualTolerance(1, quantity22.DecalitersPerDay, DecalitersPerDayTolerance); + Assert.Equal(1, quantity22.DecalitersPerDay); Assert.Equal(VolumeFlowUnit.DecaliterPerDay, quantity22.Unit); var quantity23 = VolumeFlow.From(1, VolumeFlowUnit.DecaliterPerHour); - AssertEx.EqualTolerance(1, quantity23.DecalitersPerHour, DecalitersPerHourTolerance); + Assert.Equal(1, quantity23.DecalitersPerHour); Assert.Equal(VolumeFlowUnit.DecaliterPerHour, quantity23.Unit); var quantity24 = VolumeFlow.From(1, VolumeFlowUnit.DecaliterPerMinute); - AssertEx.EqualTolerance(1, quantity24.DecalitersPerMinute, DecalitersPerMinuteTolerance); + Assert.Equal(1, quantity24.DecalitersPerMinute); Assert.Equal(VolumeFlowUnit.DecaliterPerMinute, quantity24.Unit); var quantity25 = VolumeFlow.From(1, VolumeFlowUnit.DecaliterPerSecond); - AssertEx.EqualTolerance(1, quantity25.DecalitersPerSecond, DecalitersPerSecondTolerance); + Assert.Equal(1, quantity25.DecalitersPerSecond); Assert.Equal(VolumeFlowUnit.DecaliterPerSecond, quantity25.Unit); var quantity26 = VolumeFlow.From(1, VolumeFlowUnit.DeciliterPerDay); - AssertEx.EqualTolerance(1, quantity26.DecilitersPerDay, DecilitersPerDayTolerance); + Assert.Equal(1, quantity26.DecilitersPerDay); Assert.Equal(VolumeFlowUnit.DeciliterPerDay, quantity26.Unit); var quantity27 = VolumeFlow.From(1, VolumeFlowUnit.DeciliterPerHour); - AssertEx.EqualTolerance(1, quantity27.DecilitersPerHour, DecilitersPerHourTolerance); + Assert.Equal(1, quantity27.DecilitersPerHour); Assert.Equal(VolumeFlowUnit.DeciliterPerHour, quantity27.Unit); var quantity28 = VolumeFlow.From(1, VolumeFlowUnit.DeciliterPerMinute); - AssertEx.EqualTolerance(1, quantity28.DecilitersPerMinute, DecilitersPerMinuteTolerance); + Assert.Equal(1, quantity28.DecilitersPerMinute); Assert.Equal(VolumeFlowUnit.DeciliterPerMinute, quantity28.Unit); var quantity29 = VolumeFlow.From(1, VolumeFlowUnit.DeciliterPerSecond); - AssertEx.EqualTolerance(1, quantity29.DecilitersPerSecond, DecilitersPerSecondTolerance); + Assert.Equal(1, quantity29.DecilitersPerSecond); Assert.Equal(VolumeFlowUnit.DeciliterPerSecond, quantity29.Unit); var quantity30 = VolumeFlow.From(1, VolumeFlowUnit.HectoliterPerDay); - AssertEx.EqualTolerance(1, quantity30.HectolitersPerDay, HectolitersPerDayTolerance); + Assert.Equal(1, quantity30.HectolitersPerDay); Assert.Equal(VolumeFlowUnit.HectoliterPerDay, quantity30.Unit); var quantity31 = VolumeFlow.From(1, VolumeFlowUnit.HectoliterPerHour); - AssertEx.EqualTolerance(1, quantity31.HectolitersPerHour, HectolitersPerHourTolerance); + Assert.Equal(1, quantity31.HectolitersPerHour); Assert.Equal(VolumeFlowUnit.HectoliterPerHour, quantity31.Unit); var quantity32 = VolumeFlow.From(1, VolumeFlowUnit.HectoliterPerMinute); - AssertEx.EqualTolerance(1, quantity32.HectolitersPerMinute, HectolitersPerMinuteTolerance); + Assert.Equal(1, quantity32.HectolitersPerMinute); Assert.Equal(VolumeFlowUnit.HectoliterPerMinute, quantity32.Unit); var quantity33 = VolumeFlow.From(1, VolumeFlowUnit.HectoliterPerSecond); - AssertEx.EqualTolerance(1, quantity33.HectolitersPerSecond, HectolitersPerSecondTolerance); + Assert.Equal(1, quantity33.HectolitersPerSecond); Assert.Equal(VolumeFlowUnit.HectoliterPerSecond, quantity33.Unit); var quantity34 = VolumeFlow.From(1, VolumeFlowUnit.KiloliterPerDay); - AssertEx.EqualTolerance(1, quantity34.KilolitersPerDay, KilolitersPerDayTolerance); + Assert.Equal(1, quantity34.KilolitersPerDay); Assert.Equal(VolumeFlowUnit.KiloliterPerDay, quantity34.Unit); var quantity35 = VolumeFlow.From(1, VolumeFlowUnit.KiloliterPerHour); - AssertEx.EqualTolerance(1, quantity35.KilolitersPerHour, KilolitersPerHourTolerance); + Assert.Equal(1, quantity35.KilolitersPerHour); Assert.Equal(VolumeFlowUnit.KiloliterPerHour, quantity35.Unit); var quantity36 = VolumeFlow.From(1, VolumeFlowUnit.KiloliterPerMinute); - AssertEx.EqualTolerance(1, quantity36.KilolitersPerMinute, KilolitersPerMinuteTolerance); + Assert.Equal(1, quantity36.KilolitersPerMinute); Assert.Equal(VolumeFlowUnit.KiloliterPerMinute, quantity36.Unit); var quantity37 = VolumeFlow.From(1, VolumeFlowUnit.KiloliterPerSecond); - AssertEx.EqualTolerance(1, quantity37.KilolitersPerSecond, KilolitersPerSecondTolerance); + Assert.Equal(1, quantity37.KilolitersPerSecond); Assert.Equal(VolumeFlowUnit.KiloliterPerSecond, quantity37.Unit); var quantity38 = VolumeFlow.From(1, VolumeFlowUnit.KilousGallonPerMinute); - AssertEx.EqualTolerance(1, quantity38.KilousGallonsPerMinute, KilousGallonsPerMinuteTolerance); + Assert.Equal(1, quantity38.KilousGallonsPerMinute); Assert.Equal(VolumeFlowUnit.KilousGallonPerMinute, quantity38.Unit); var quantity39 = VolumeFlow.From(1, VolumeFlowUnit.LiterPerDay); - AssertEx.EqualTolerance(1, quantity39.LitersPerDay, LitersPerDayTolerance); + Assert.Equal(1, quantity39.LitersPerDay); Assert.Equal(VolumeFlowUnit.LiterPerDay, quantity39.Unit); var quantity40 = VolumeFlow.From(1, VolumeFlowUnit.LiterPerHour); - AssertEx.EqualTolerance(1, quantity40.LitersPerHour, LitersPerHourTolerance); + Assert.Equal(1, quantity40.LitersPerHour); Assert.Equal(VolumeFlowUnit.LiterPerHour, quantity40.Unit); var quantity41 = VolumeFlow.From(1, VolumeFlowUnit.LiterPerMinute); - AssertEx.EqualTolerance(1, quantity41.LitersPerMinute, LitersPerMinuteTolerance); + Assert.Equal(1, quantity41.LitersPerMinute); Assert.Equal(VolumeFlowUnit.LiterPerMinute, quantity41.Unit); var quantity42 = VolumeFlow.From(1, VolumeFlowUnit.LiterPerSecond); - AssertEx.EqualTolerance(1, quantity42.LitersPerSecond, LitersPerSecondTolerance); + Assert.Equal(1, quantity42.LitersPerSecond); Assert.Equal(VolumeFlowUnit.LiterPerSecond, quantity42.Unit); var quantity43 = VolumeFlow.From(1, VolumeFlowUnit.MegaliterPerDay); - AssertEx.EqualTolerance(1, quantity43.MegalitersPerDay, MegalitersPerDayTolerance); + Assert.Equal(1, quantity43.MegalitersPerDay); Assert.Equal(VolumeFlowUnit.MegaliterPerDay, quantity43.Unit); var quantity44 = VolumeFlow.From(1, VolumeFlowUnit.MegaliterPerHour); - AssertEx.EqualTolerance(1, quantity44.MegalitersPerHour, MegalitersPerHourTolerance); + Assert.Equal(1, quantity44.MegalitersPerHour); Assert.Equal(VolumeFlowUnit.MegaliterPerHour, quantity44.Unit); var quantity45 = VolumeFlow.From(1, VolumeFlowUnit.MegaliterPerMinute); - AssertEx.EqualTolerance(1, quantity45.MegalitersPerMinute, MegalitersPerMinuteTolerance); + Assert.Equal(1, quantity45.MegalitersPerMinute); Assert.Equal(VolumeFlowUnit.MegaliterPerMinute, quantity45.Unit); var quantity46 = VolumeFlow.From(1, VolumeFlowUnit.MegaliterPerSecond); - AssertEx.EqualTolerance(1, quantity46.MegalitersPerSecond, MegalitersPerSecondTolerance); + Assert.Equal(1, quantity46.MegalitersPerSecond); Assert.Equal(VolumeFlowUnit.MegaliterPerSecond, quantity46.Unit); var quantity47 = VolumeFlow.From(1, VolumeFlowUnit.MegaukGallonPerDay); - AssertEx.EqualTolerance(1, quantity47.MegaukGallonsPerDay, MegaukGallonsPerDayTolerance); + Assert.Equal(1, quantity47.MegaukGallonsPerDay); Assert.Equal(VolumeFlowUnit.MegaukGallonPerDay, quantity47.Unit); var quantity48 = VolumeFlow.From(1, VolumeFlowUnit.MegaukGallonPerSecond); - AssertEx.EqualTolerance(1, quantity48.MegaukGallonsPerSecond, MegaukGallonsPerSecondTolerance); + Assert.Equal(1, quantity48.MegaukGallonsPerSecond); Assert.Equal(VolumeFlowUnit.MegaukGallonPerSecond, quantity48.Unit); var quantity49 = VolumeFlow.From(1, VolumeFlowUnit.MegausGallonPerDay); - AssertEx.EqualTolerance(1, quantity49.MegausGallonsPerDay, MegausGallonsPerDayTolerance); + Assert.Equal(1, quantity49.MegausGallonsPerDay); Assert.Equal(VolumeFlowUnit.MegausGallonPerDay, quantity49.Unit); var quantity50 = VolumeFlow.From(1, VolumeFlowUnit.MicroliterPerDay); - AssertEx.EqualTolerance(1, quantity50.MicrolitersPerDay, MicrolitersPerDayTolerance); + Assert.Equal(1, quantity50.MicrolitersPerDay); Assert.Equal(VolumeFlowUnit.MicroliterPerDay, quantity50.Unit); var quantity51 = VolumeFlow.From(1, VolumeFlowUnit.MicroliterPerHour); - AssertEx.EqualTolerance(1, quantity51.MicrolitersPerHour, MicrolitersPerHourTolerance); + Assert.Equal(1, quantity51.MicrolitersPerHour); Assert.Equal(VolumeFlowUnit.MicroliterPerHour, quantity51.Unit); var quantity52 = VolumeFlow.From(1, VolumeFlowUnit.MicroliterPerMinute); - AssertEx.EqualTolerance(1, quantity52.MicrolitersPerMinute, MicrolitersPerMinuteTolerance); + Assert.Equal(1, quantity52.MicrolitersPerMinute); Assert.Equal(VolumeFlowUnit.MicroliterPerMinute, quantity52.Unit); var quantity53 = VolumeFlow.From(1, VolumeFlowUnit.MicroliterPerSecond); - AssertEx.EqualTolerance(1, quantity53.MicrolitersPerSecond, MicrolitersPerSecondTolerance); + Assert.Equal(1, quantity53.MicrolitersPerSecond); Assert.Equal(VolumeFlowUnit.MicroliterPerSecond, quantity53.Unit); var quantity54 = VolumeFlow.From(1, VolumeFlowUnit.MilliliterPerDay); - AssertEx.EqualTolerance(1, quantity54.MillilitersPerDay, MillilitersPerDayTolerance); + Assert.Equal(1, quantity54.MillilitersPerDay); Assert.Equal(VolumeFlowUnit.MilliliterPerDay, quantity54.Unit); var quantity55 = VolumeFlow.From(1, VolumeFlowUnit.MilliliterPerHour); - AssertEx.EqualTolerance(1, quantity55.MillilitersPerHour, MillilitersPerHourTolerance); + Assert.Equal(1, quantity55.MillilitersPerHour); Assert.Equal(VolumeFlowUnit.MilliliterPerHour, quantity55.Unit); var quantity56 = VolumeFlow.From(1, VolumeFlowUnit.MilliliterPerMinute); - AssertEx.EqualTolerance(1, quantity56.MillilitersPerMinute, MillilitersPerMinuteTolerance); + Assert.Equal(1, quantity56.MillilitersPerMinute); Assert.Equal(VolumeFlowUnit.MilliliterPerMinute, quantity56.Unit); var quantity57 = VolumeFlow.From(1, VolumeFlowUnit.MilliliterPerSecond); - AssertEx.EqualTolerance(1, quantity57.MillilitersPerSecond, MillilitersPerSecondTolerance); + Assert.Equal(1, quantity57.MillilitersPerSecond); Assert.Equal(VolumeFlowUnit.MilliliterPerSecond, quantity57.Unit); var quantity58 = VolumeFlow.From(1, VolumeFlowUnit.MillionUsGallonPerDay); - AssertEx.EqualTolerance(1, quantity58.MillionUsGallonsPerDay, MillionUsGallonsPerDayTolerance); + Assert.Equal(1, quantity58.MillionUsGallonsPerDay); Assert.Equal(VolumeFlowUnit.MillionUsGallonPerDay, quantity58.Unit); var quantity59 = VolumeFlow.From(1, VolumeFlowUnit.NanoliterPerDay); - AssertEx.EqualTolerance(1, quantity59.NanolitersPerDay, NanolitersPerDayTolerance); + Assert.Equal(1, quantity59.NanolitersPerDay); Assert.Equal(VolumeFlowUnit.NanoliterPerDay, quantity59.Unit); var quantity60 = VolumeFlow.From(1, VolumeFlowUnit.NanoliterPerHour); - AssertEx.EqualTolerance(1, quantity60.NanolitersPerHour, NanolitersPerHourTolerance); + Assert.Equal(1, quantity60.NanolitersPerHour); Assert.Equal(VolumeFlowUnit.NanoliterPerHour, quantity60.Unit); var quantity61 = VolumeFlow.From(1, VolumeFlowUnit.NanoliterPerMinute); - AssertEx.EqualTolerance(1, quantity61.NanolitersPerMinute, NanolitersPerMinuteTolerance); + Assert.Equal(1, quantity61.NanolitersPerMinute); Assert.Equal(VolumeFlowUnit.NanoliterPerMinute, quantity61.Unit); var quantity62 = VolumeFlow.From(1, VolumeFlowUnit.NanoliterPerSecond); - AssertEx.EqualTolerance(1, quantity62.NanolitersPerSecond, NanolitersPerSecondTolerance); + Assert.Equal(1, quantity62.NanolitersPerSecond); Assert.Equal(VolumeFlowUnit.NanoliterPerSecond, quantity62.Unit); var quantity63 = VolumeFlow.From(1, VolumeFlowUnit.OilBarrelPerDay); - AssertEx.EqualTolerance(1, quantity63.OilBarrelsPerDay, OilBarrelsPerDayTolerance); + Assert.Equal(1, quantity63.OilBarrelsPerDay); Assert.Equal(VolumeFlowUnit.OilBarrelPerDay, quantity63.Unit); var quantity64 = VolumeFlow.From(1, VolumeFlowUnit.OilBarrelPerHour); - AssertEx.EqualTolerance(1, quantity64.OilBarrelsPerHour, OilBarrelsPerHourTolerance); + Assert.Equal(1, quantity64.OilBarrelsPerHour); Assert.Equal(VolumeFlowUnit.OilBarrelPerHour, quantity64.Unit); var quantity65 = VolumeFlow.From(1, VolumeFlowUnit.OilBarrelPerMinute); - AssertEx.EqualTolerance(1, quantity65.OilBarrelsPerMinute, OilBarrelsPerMinuteTolerance); + Assert.Equal(1, quantity65.OilBarrelsPerMinute); Assert.Equal(VolumeFlowUnit.OilBarrelPerMinute, quantity65.Unit); var quantity66 = VolumeFlow.From(1, VolumeFlowUnit.OilBarrelPerSecond); - AssertEx.EqualTolerance(1, quantity66.OilBarrelsPerSecond, OilBarrelsPerSecondTolerance); + Assert.Equal(1, quantity66.OilBarrelsPerSecond); Assert.Equal(VolumeFlowUnit.OilBarrelPerSecond, quantity66.Unit); var quantity67 = VolumeFlow.From(1, VolumeFlowUnit.UkGallonPerDay); - AssertEx.EqualTolerance(1, quantity67.UkGallonsPerDay, UkGallonsPerDayTolerance); + Assert.Equal(1, quantity67.UkGallonsPerDay); Assert.Equal(VolumeFlowUnit.UkGallonPerDay, quantity67.Unit); var quantity68 = VolumeFlow.From(1, VolumeFlowUnit.UkGallonPerHour); - AssertEx.EqualTolerance(1, quantity68.UkGallonsPerHour, UkGallonsPerHourTolerance); + Assert.Equal(1, quantity68.UkGallonsPerHour); Assert.Equal(VolumeFlowUnit.UkGallonPerHour, quantity68.Unit); var quantity69 = VolumeFlow.From(1, VolumeFlowUnit.UkGallonPerMinute); - AssertEx.EqualTolerance(1, quantity69.UkGallonsPerMinute, UkGallonsPerMinuteTolerance); + Assert.Equal(1, quantity69.UkGallonsPerMinute); Assert.Equal(VolumeFlowUnit.UkGallonPerMinute, quantity69.Unit); var quantity70 = VolumeFlow.From(1, VolumeFlowUnit.UkGallonPerSecond); - AssertEx.EqualTolerance(1, quantity70.UkGallonsPerSecond, UkGallonsPerSecondTolerance); + Assert.Equal(1, quantity70.UkGallonsPerSecond); Assert.Equal(VolumeFlowUnit.UkGallonPerSecond, quantity70.Unit); var quantity71 = VolumeFlow.From(1, VolumeFlowUnit.UsGallonPerDay); - AssertEx.EqualTolerance(1, quantity71.UsGallonsPerDay, UsGallonsPerDayTolerance); + Assert.Equal(1, quantity71.UsGallonsPerDay); Assert.Equal(VolumeFlowUnit.UsGallonPerDay, quantity71.Unit); var quantity72 = VolumeFlow.From(1, VolumeFlowUnit.UsGallonPerHour); - AssertEx.EqualTolerance(1, quantity72.UsGallonsPerHour, UsGallonsPerHourTolerance); + Assert.Equal(1, quantity72.UsGallonsPerHour); Assert.Equal(VolumeFlowUnit.UsGallonPerHour, quantity72.Unit); var quantity73 = VolumeFlow.From(1, VolumeFlowUnit.UsGallonPerMinute); - AssertEx.EqualTolerance(1, quantity73.UsGallonsPerMinute, UsGallonsPerMinuteTolerance); + Assert.Equal(1, quantity73.UsGallonsPerMinute); Assert.Equal(VolumeFlowUnit.UsGallonPerMinute, quantity73.Unit); var quantity74 = VolumeFlow.From(1, VolumeFlowUnit.UsGallonPerSecond); - AssertEx.EqualTolerance(1, quantity74.UsGallonsPerSecond, UsGallonsPerSecondTolerance); + Assert.Equal(1, quantity74.UsGallonsPerSecond); Assert.Equal(VolumeFlowUnit.UsGallonPerSecond, quantity74.Unit); } @@ -908,2179 +926,461 @@ public virtual void BaseUnit_HasSIBase() Assert.True(baseUnitInfo.BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } - [Fact] - public virtual void As_UnitSystem_SI_ReturnsQuantityInSIUnits() - { - var quantity = new VolumeFlow(value: 1, unit: VolumeFlow.BaseUnit); - var expectedValue = quantity.As(VolumeFlow.Info.GetDefaultUnit(UnitSystem.SI)); - - var convertedValue = quantity.As(UnitSystem.SI); - - Assert.Equal(expectedValue, convertedValue); - } - - [Fact] - public void As_UnitSystem_ThrowsArgumentNullExceptionIfNull() - { - var quantity = new VolumeFlow(value: 1, unit: VolumeFlow.BaseUnit); - UnitSystem nullUnitSystem = null!; - Assert.Throws(() => quantity.As(nullUnitSystem)); - } - - [Fact] - public void As_UnitSystem_ThrowsArgumentExceptionIfNotSupported() - { - var quantity = new VolumeFlow(value: 1, unit: VolumeFlow.BaseUnit); - var unsupportedUnitSystem = new UnitSystem(UnsupportedBaseUnits); - Assert.Throws(() => quantity.As(unsupportedUnitSystem)); - } - - [Fact] - public virtual void ToUnit_UnitSystem_SI_ReturnsQuantityInSIUnits() - { - var quantity = new VolumeFlow(value: 1, unit: VolumeFlow.BaseUnit); - var expectedUnit = VolumeFlow.Info.GetDefaultUnit(UnitSystem.SI); - var expectedValue = quantity.As(expectedUnit); - - Assert.Multiple(() => - { - VolumeFlow quantityToConvert = quantity; - - VolumeFlow convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); - - Assert.Equal(expectedUnit, convertedQuantity.Unit); - Assert.Equal(expectedValue, convertedQuantity.Value); - }, () => - { - IQuantity quantityToConvert = quantity; - - IQuantity convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); - - Assert.Equal(expectedUnit, convertedQuantity.Unit); - Assert.Equal(expectedValue, convertedQuantity.Value); - }, () => - { - IQuantity quantityToConvert = quantity; - - IQuantity convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); - - Assert.Equal(expectedUnit, convertedQuantity.Unit); - Assert.Equal(expectedValue, convertedQuantity.Value); - }); - } - - [Fact] - public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() - { - UnitSystem nullUnitSystem = null!; - Assert.Multiple(() => - { - var quantity = new VolumeFlow(value: 1, unit: VolumeFlow.BaseUnit); - Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); - }, () => - { - IQuantity quantity = new VolumeFlow(value: 1, unit: VolumeFlow.BaseUnit); - Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); - }, () => - { - IQuantity quantity = new VolumeFlow(value: 1, unit: VolumeFlow.BaseUnit); - Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); - }); - } - - [Fact] - public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() - { - var unsupportedUnitSystem = new UnitSystem(UnsupportedBaseUnits); - Assert.Multiple(() => - { - var quantity = new VolumeFlow(value: 1, unit: VolumeFlow.BaseUnit); - Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); - }, () => - { - IQuantity quantity = new VolumeFlow(value: 1, unit: VolumeFlow.BaseUnit); - Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); - }, () => - { - IQuantity quantity = new VolumeFlow(value: 1, unit: VolumeFlow.BaseUnit); - Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); - }); - } - - [Fact] - public void Parse() - { - try - { - var parsed = VolumeFlow.Parse("1 af/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.AcreFeetPerDay, AcreFeetPerDayTolerance); - Assert.Equal(VolumeFlowUnit.AcreFootPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 af/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.AcreFeetPerHour, AcreFeetPerHourTolerance); - Assert.Equal(VolumeFlowUnit.AcreFootPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 af/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.AcreFeetPerMinute, AcreFeetPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.AcreFootPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 af/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.AcreFeetPerSecond, AcreFeetPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.AcreFootPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 cl/day", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentilitersPerDay, CentilitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 cl/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentilitersPerDay, CentilitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 cLPD", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentilitersPerDay, CentilitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 cl/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentilitersPerHour, CentilitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 cLPH", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentilitersPerHour, CentilitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 сл/ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CentilitersPerHour, CentilitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 cl/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentilitersPerMinute, CentilitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 cLPM", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentilitersPerMinute, CentilitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 сл/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CentilitersPerMinute, CentilitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 cl/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentilitersPerSecond, CentilitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 cLPS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentilitersPerSecond, CentilitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 сл/c", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CentilitersPerSecond, CentilitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 cm³/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicCentimetersPerMinute, CubicCentimetersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CubicCentimeterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 см³/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CubicCentimetersPerMinute, CubicCentimetersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CubicCentimeterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 dm³/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicDecimetersPerMinute, CubicDecimetersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CubicDecimeterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 дм³/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CubicDecimetersPerMinute, CubicDecimetersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CubicDecimeterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 ft³/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicFeetPerHour, CubicFeetPerHourTolerance); - Assert.Equal(VolumeFlowUnit.CubicFootPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 cf/hr", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicFeetPerHour, CubicFeetPerHourTolerance); - Assert.Equal(VolumeFlowUnit.CubicFootPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 ft³/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicFeetPerMinute, CubicFeetPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CubicFootPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 CFM", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicFeetPerMinute, CubicFeetPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CubicFootPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 ft³/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicFeetPerSecond, CubicFeetPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.CubicFootPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 m³/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicMetersPerDay, CubicMetersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.CubicMeterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 m³/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicMetersPerHour, CubicMetersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.CubicMeterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 м³/ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CubicMetersPerHour, CubicMetersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.CubicMeterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 m³/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicMetersPerMinute, CubicMetersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CubicMeterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 м³/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CubicMetersPerMinute, CubicMetersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CubicMeterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 m³/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicMetersPerSecond, CubicMetersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.CubicMeterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 м³/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CubicMetersPerSecond, CubicMetersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.CubicMeterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 mm³/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicMillimetersPerSecond, CubicMillimetersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.CubicMillimeterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 мм³/с", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CubicMillimetersPerSecond, CubicMillimetersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.CubicMillimeterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 cy/day", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicYardsPerDay, CubicYardsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.CubicYardPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 yd³/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicYardsPerHour, CubicYardsPerHourTolerance); - Assert.Equal(VolumeFlowUnit.CubicYardPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 yd³/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicYardsPerMinute, CubicYardsPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CubicYardPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 yd³/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicYardsPerSecond, CubicYardsPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.CubicYardPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 dal/day", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecalitersPerDay, DecalitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.DecaliterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 dal/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecalitersPerDay, DecalitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.DecaliterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 daLPD", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecalitersPerDay, DecalitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.DecaliterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 dal/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecalitersPerHour, DecalitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.DecaliterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 daLPH", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecalitersPerHour, DecalitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.DecaliterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 дал/ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.DecalitersPerHour, DecalitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.DecaliterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 dal/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecalitersPerMinute, DecalitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.DecaliterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 daLPM", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecalitersPerMinute, DecalitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.DecaliterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 дал/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.DecalitersPerMinute, DecalitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.DecaliterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 dal/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecalitersPerSecond, DecalitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.DecaliterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 daLPS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecalitersPerSecond, DecalitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.DecaliterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 дал/c", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.DecalitersPerSecond, DecalitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.DecaliterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 dl/day", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecilitersPerDay, DecilitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 dl/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecilitersPerDay, DecilitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 dLPD", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecilitersPerDay, DecilitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 dl/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecilitersPerHour, DecilitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 dLPH", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecilitersPerHour, DecilitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 дл/ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.DecilitersPerHour, DecilitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 dl/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecilitersPerMinute, DecilitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 dLPM", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecilitersPerMinute, DecilitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 дл/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.DecilitersPerMinute, DecilitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 dl/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecilitersPerSecond, DecilitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 dLPS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecilitersPerSecond, DecilitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 дл/c", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.DecilitersPerSecond, DecilitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 hl/day", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.HectolitersPerDay, HectolitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.HectoliterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 hl/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.HectolitersPerDay, HectolitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.HectoliterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 hLPD", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.HectolitersPerDay, HectolitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.HectoliterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 hl/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.HectolitersPerHour, HectolitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.HectoliterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 hLPH", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.HectolitersPerHour, HectolitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.HectoliterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 гл/ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.HectolitersPerHour, HectolitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.HectoliterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 hl/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.HectolitersPerMinute, HectolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.HectoliterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 hLPM", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.HectolitersPerMinute, HectolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.HectoliterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 гл/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.HectolitersPerMinute, HectolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.HectoliterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 hl/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.HectolitersPerSecond, HectolitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.HectoliterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 hLPS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.HectolitersPerSecond, HectolitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.HectoliterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 гл/c", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.HectolitersPerSecond, HectolitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.HectoliterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 kl/day", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilolitersPerDay, KilolitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 kl/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilolitersPerDay, KilolitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 kLPD", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilolitersPerDay, KilolitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 kl/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilolitersPerHour, KilolitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 kLPH", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilolitersPerHour, KilolitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 кл/ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilolitersPerHour, KilolitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 kl/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilolitersPerMinute, KilolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 kLPM", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilolitersPerMinute, KilolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 кл/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilolitersPerMinute, KilolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 kl/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilolitersPerSecond, KilolitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 kLPS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilolitersPerSecond, KilolitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 кл/c", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilolitersPerSecond, KilolitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 kgal (U.S.)/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilousGallonsPerMinute, KilousGallonsPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.KilousGallonPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 KGPM", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilousGallonsPerMinute, KilousGallonsPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.KilousGallonPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 l/day", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.LitersPerDay, LitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 l/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.LitersPerDay, LitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 LPD", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.LitersPerDay, LitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 l/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.LitersPerHour, LitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 LPH", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.LitersPerHour, LitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 л/ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.LitersPerHour, LitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 l/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.LitersPerMinute, LitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 LPM", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.LitersPerMinute, LitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 л/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.LitersPerMinute, LitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 l/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.LitersPerSecond, LitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 LPS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.LitersPerSecond, LitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 л/c", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.LitersPerSecond, LitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 Ml/day", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegalitersPerDay, MegalitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.MegaliterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 Ml/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegalitersPerDay, MegalitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.MegaliterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 MLPD", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegalitersPerDay, MegalitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.MegaliterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 Ml/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegalitersPerHour, MegalitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.MegaliterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 MLPH", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegalitersPerHour, MegalitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.MegaliterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 Мл/ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MegalitersPerHour, MegalitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.MegaliterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 Ml/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegalitersPerMinute, MegalitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.MegaliterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 MLPM", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegalitersPerMinute, MegalitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.MegaliterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 Мл/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MegalitersPerMinute, MegalitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.MegaliterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 Ml/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegalitersPerSecond, MegalitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.MegaliterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 MLPS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegalitersPerSecond, MegalitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.MegaliterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 Мл/c", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MegalitersPerSecond, MegalitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.MegaliterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 Mgal (U. K.)/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegaukGallonsPerDay, MegaukGallonsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.MegaukGallonPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 Mgal (imp.)/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegaukGallonsPerSecond, MegaukGallonsPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.MegaukGallonPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 Mgpd", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegausGallonsPerDay, MegausGallonsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.MegausGallonPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 Mgal/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegausGallonsPerDay, MegausGallonsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.MegausGallonPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 µl/day", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerDay, MicrolitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 µl/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerDay, MicrolitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 µLPD", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerDay, MicrolitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 µl/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerHour, MicrolitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 µLPH", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerHour, MicrolitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 мкл/ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerHour, MicrolitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 µl/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerMinute, MicrolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 µLPM", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerMinute, MicrolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 мкл/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerMinute, MicrolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 µl/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerSecond, MicrolitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 µLPS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerSecond, MicrolitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 мкл/c", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerSecond, MicrolitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 ml/day", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillilitersPerDay, MillilitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.MilliliterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 ml/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillilitersPerDay, MillilitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.MilliliterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 mLPD", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillilitersPerDay, MillilitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.MilliliterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 ml/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillilitersPerHour, MillilitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.MilliliterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 mLPH", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillilitersPerHour, MillilitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.MilliliterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 мл/ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MillilitersPerHour, MillilitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.MilliliterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 ml/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillilitersPerMinute, MillilitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.MilliliterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 mLPM", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillilitersPerMinute, MillilitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.MilliliterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 мл/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MillilitersPerMinute, MillilitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.MilliliterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 ml/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillilitersPerSecond, MillilitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.MilliliterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 mLPS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillilitersPerSecond, MillilitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.MilliliterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 мл/c", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MillilitersPerSecond, MillilitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.MilliliterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 MGD", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillionUsGallonsPerDay, MillionUsGallonsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.MillionUsGallonPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 nl/day", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanolitersPerDay, NanolitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 nl/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanolitersPerDay, NanolitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 nLPD", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanolitersPerDay, NanolitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 nl/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanolitersPerHour, NanolitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 nLPH", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanolitersPerHour, NanolitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 нл/ч", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.NanolitersPerHour, NanolitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 nl/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanolitersPerMinute, NanolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 nLPM", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanolitersPerMinute, NanolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 нл/мин", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.NanolitersPerMinute, NanolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 nl/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanolitersPerSecond, NanolitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 nLPS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.NanolitersPerSecond, NanolitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 нл/c", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.NanolitersPerSecond, NanolitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 bbl/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.OilBarrelsPerDay, OilBarrelsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.OilBarrelPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 BOPD", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.OilBarrelsPerDay, OilBarrelsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.OilBarrelPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 bbl/hr", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.OilBarrelsPerHour, OilBarrelsPerHourTolerance); - Assert.Equal(VolumeFlowUnit.OilBarrelPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 bph", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.OilBarrelsPerHour, OilBarrelsPerHourTolerance); - Assert.Equal(VolumeFlowUnit.OilBarrelPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 bbl/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.OilBarrelsPerMinute, OilBarrelsPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.OilBarrelPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 bpm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.OilBarrelsPerMinute, OilBarrelsPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.OilBarrelPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 bbl/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.OilBarrelsPerSecond, OilBarrelsPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.OilBarrelPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 gal (U. K.)/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.UkGallonsPerDay, UkGallonsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.UkGallonPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 gal (imp.)/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.UkGallonsPerHour, UkGallonsPerHourTolerance); - Assert.Equal(VolumeFlowUnit.UkGallonPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 gal (imp.)/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.UkGallonsPerMinute, UkGallonsPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.UkGallonPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 gal (imp.)/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.UkGallonsPerSecond, UkGallonsPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.UkGallonPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 gpd", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.UsGallonsPerDay, UsGallonsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.UsGallonPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 gal/d", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.UsGallonsPerDay, UsGallonsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.UsGallonPerDay, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 gal (U.S.)/h", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.UsGallonsPerHour, UsGallonsPerHourTolerance); - Assert.Equal(VolumeFlowUnit.UsGallonPerHour, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 gal (U.S.)/min", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.UsGallonsPerMinute, UsGallonsPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.UsGallonPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 GPM", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.UsGallonsPerMinute, UsGallonsPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.UsGallonPerMinute, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumeFlow.Parse("1 gal (U.S.)/s", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.UsGallonsPerSecond, UsGallonsPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.UsGallonPerSecond, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - } - - [Fact] - public void TryParse() - { - { - Assert.True(VolumeFlow.TryParse("1 af/d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.AcreFeetPerDay, AcreFeetPerDayTolerance); - Assert.Equal(VolumeFlowUnit.AcreFootPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 af/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.AcreFeetPerHour, AcreFeetPerHourTolerance); - Assert.Equal(VolumeFlowUnit.AcreFootPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 af/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.AcreFeetPerMinute, AcreFeetPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.AcreFootPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 af/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.AcreFeetPerSecond, AcreFeetPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.AcreFootPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 cl/day", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentilitersPerDay, CentilitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 cl/d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentilitersPerDay, CentilitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 cLPD", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentilitersPerDay, CentilitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 cl/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentilitersPerHour, CentilitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 cLPH", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentilitersPerHour, CentilitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 сл/ч", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentilitersPerHour, CentilitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 cl/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentilitersPerMinute, CentilitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 cLPM", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentilitersPerMinute, CentilitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 сл/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentilitersPerMinute, CentilitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 cl/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentilitersPerSecond, CentilitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 cLPS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentilitersPerSecond, CentilitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 сл/c", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentilitersPerSecond, CentilitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.CentiliterPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 cm³/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicCentimetersPerMinute, CubicCentimetersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CubicCentimeterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 см³/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicCentimetersPerMinute, CubicCentimetersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CubicCentimeterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 dm³/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicDecimetersPerMinute, CubicDecimetersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CubicDecimeterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 дм³/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicDecimetersPerMinute, CubicDecimetersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CubicDecimeterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 ft³/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicFeetPerHour, CubicFeetPerHourTolerance); - Assert.Equal(VolumeFlowUnit.CubicFootPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 cf/hr", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicFeetPerHour, CubicFeetPerHourTolerance); - Assert.Equal(VolumeFlowUnit.CubicFootPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 ft³/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicFeetPerMinute, CubicFeetPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CubicFootPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 CFM", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicFeetPerMinute, CubicFeetPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CubicFootPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 ft³/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicFeetPerSecond, CubicFeetPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.CubicFootPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 m³/d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicMetersPerDay, CubicMetersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.CubicMeterPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 m³/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicMetersPerHour, CubicMetersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.CubicMeterPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 м³/ч", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicMetersPerHour, CubicMetersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.CubicMeterPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 m³/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicMetersPerMinute, CubicMetersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CubicMeterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 м³/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicMetersPerMinute, CubicMetersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CubicMeterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 m³/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicMetersPerSecond, CubicMetersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.CubicMeterPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 м³/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicMetersPerSecond, CubicMetersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.CubicMeterPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 mm³/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicMillimetersPerSecond, CubicMillimetersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.CubicMillimeterPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 мм³/с", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicMillimetersPerSecond, CubicMillimetersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.CubicMillimeterPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 cy/day", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicYardsPerDay, CubicYardsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.CubicYardPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 yd³/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicYardsPerHour, CubicYardsPerHourTolerance); - Assert.Equal(VolumeFlowUnit.CubicYardPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 yd³/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicYardsPerMinute, CubicYardsPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.CubicYardPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 yd³/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicYardsPerSecond, CubicYardsPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.CubicYardPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 dal/day", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecalitersPerDay, DecalitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.DecaliterPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 dal/d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecalitersPerDay, DecalitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.DecaliterPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 daLPD", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecalitersPerDay, DecalitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.DecaliterPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 dal/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecalitersPerHour, DecalitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.DecaliterPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 daLPH", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecalitersPerHour, DecalitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.DecaliterPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 дал/ч", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecalitersPerHour, DecalitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.DecaliterPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 dal/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecalitersPerMinute, DecalitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.DecaliterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 daLPM", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecalitersPerMinute, DecalitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.DecaliterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 дал/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecalitersPerMinute, DecalitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.DecaliterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 dal/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecalitersPerSecond, DecalitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.DecaliterPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 daLPS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecalitersPerSecond, DecalitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.DecaliterPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 дал/c", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecalitersPerSecond, DecalitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.DecaliterPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 dl/day", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecilitersPerDay, DecilitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 dl/d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecilitersPerDay, DecilitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 dLPD", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecilitersPerDay, DecilitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 dl/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecilitersPerHour, DecilitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 dLPH", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecilitersPerHour, DecilitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 дл/ч", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecilitersPerHour, DecilitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 dl/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecilitersPerMinute, DecilitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 dLPM", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecilitersPerMinute, DecilitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 дл/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecilitersPerMinute, DecilitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 dl/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecilitersPerSecond, DecilitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 dLPS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecilitersPerSecond, DecilitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 дл/c", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecilitersPerSecond, DecilitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.DeciliterPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 hl/day", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HectolitersPerDay, HectolitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.HectoliterPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 hl/d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HectolitersPerDay, HectolitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.HectoliterPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 hLPD", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HectolitersPerDay, HectolitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.HectoliterPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 hl/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HectolitersPerHour, HectolitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.HectoliterPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 hLPH", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HectolitersPerHour, HectolitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.HectoliterPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 гл/ч", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HectolitersPerHour, HectolitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.HectoliterPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 hl/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HectolitersPerMinute, HectolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.HectoliterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 hLPM", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HectolitersPerMinute, HectolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.HectoliterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 гл/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HectolitersPerMinute, HectolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.HectoliterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 hl/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HectolitersPerSecond, HectolitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.HectoliterPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 hLPS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HectolitersPerSecond, HectolitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.HectoliterPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 гл/c", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HectolitersPerSecond, HectolitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.HectoliterPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 kl/day", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilolitersPerDay, KilolitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 kl/d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilolitersPerDay, KilolitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 kLPD", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilolitersPerDay, KilolitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 kl/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilolitersPerHour, KilolitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 kLPH", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilolitersPerHour, KilolitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 кл/ч", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilolitersPerHour, KilolitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 kl/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilolitersPerMinute, KilolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 kLPM", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilolitersPerMinute, KilolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 кл/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilolitersPerMinute, KilolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 kl/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilolitersPerSecond, KilolitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 kLPS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilolitersPerSecond, KilolitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 кл/c", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilolitersPerSecond, KilolitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.KiloliterPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 kgal (U.S.)/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilousGallonsPerMinute, KilousGallonsPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.KilousGallonPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 KGPM", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilousGallonsPerMinute, KilousGallonsPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.KilousGallonPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 l/day", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.LitersPerDay, LitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 l/d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.LitersPerDay, LitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 LPD", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.LitersPerDay, LitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 l/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.LitersPerHour, LitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 LPH", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.LitersPerHour, LitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 л/ч", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.LitersPerHour, LitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 l/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.LitersPerMinute, LitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 LPM", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.LitersPerMinute, LitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 л/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.LitersPerMinute, LitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 l/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.LitersPerSecond, LitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 LPS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.LitersPerSecond, LitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 л/c", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.LitersPerSecond, LitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.LiterPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 Mgal (U. K.)/d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegaukGallonsPerDay, MegaukGallonsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.MegaukGallonPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 Mgal (imp.)/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegaukGallonsPerSecond, MegaukGallonsPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.MegaukGallonPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 Mgpd", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegausGallonsPerDay, MegausGallonsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.MegausGallonPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 Mgal/d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegausGallonsPerDay, MegausGallonsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.MegausGallonPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 µl/day", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerDay, MicrolitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 µl/d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerDay, MicrolitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 µLPD", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerDay, MicrolitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 µl/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerHour, MicrolitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 µLPH", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerHour, MicrolitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 мкл/ч", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerHour, MicrolitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 µl/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerMinute, MicrolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 µLPM", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerMinute, MicrolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 мкл/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerMinute, MicrolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 µl/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerSecond, MicrolitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 µLPS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerSecond, MicrolitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 мкл/c", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MicrolitersPerSecond, MicrolitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.MicroliterPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 MGD", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillionUsGallonsPerDay, MillionUsGallonsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.MillionUsGallonPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 nl/day", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanolitersPerDay, NanolitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 nl/d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanolitersPerDay, NanolitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 nLPD", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanolitersPerDay, NanolitersPerDayTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerDay, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 nl/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanolitersPerHour, NanolitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 nLPH", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanolitersPerHour, NanolitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 нл/ч", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanolitersPerHour, NanolitersPerHourTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerHour, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 nl/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanolitersPerMinute, NanolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 nLPM", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanolitersPerMinute, NanolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 нл/мин", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanolitersPerMinute, NanolitersPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerMinute, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 nl/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanolitersPerSecond, NanolitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerSecond, parsed.Unit); - } - - { - Assert.True(VolumeFlow.TryParse("1 nLPS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanolitersPerSecond, NanolitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerSecond, parsed.Unit); - } + [Fact] + public virtual void As_UnitSystem_SI_ReturnsQuantityInSIUnits() + { + var quantity = new VolumeFlow(value: 1, unit: VolumeFlow.BaseUnit); + var expectedValue = quantity.As(VolumeFlow.Info.GetDefaultUnit(UnitSystem.SI)); - { - Assert.True(VolumeFlow.TryParse("1 нл/c", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.NanolitersPerSecond, NanolitersPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.NanoliterPerSecond, parsed.Unit); - } + var convertedValue = quantity.As(UnitSystem.SI); - { - Assert.True(VolumeFlow.TryParse("1 bbl/d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.OilBarrelsPerDay, OilBarrelsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.OilBarrelPerDay, parsed.Unit); - } + Assert.Equal(expectedValue, convertedValue); + } - { - Assert.True(VolumeFlow.TryParse("1 BOPD", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.OilBarrelsPerDay, OilBarrelsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.OilBarrelPerDay, parsed.Unit); - } + [Fact] + public void As_UnitSystem_ThrowsArgumentNullExceptionIfNull() + { + var quantity = new VolumeFlow(value: 1, unit: VolumeFlow.BaseUnit); + UnitSystem nullUnitSystem = null!; + Assert.Throws(() => quantity.As(nullUnitSystem)); + } - { - Assert.True(VolumeFlow.TryParse("1 bbl/hr", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.OilBarrelsPerHour, OilBarrelsPerHourTolerance); - Assert.Equal(VolumeFlowUnit.OilBarrelPerHour, parsed.Unit); - } + [Fact] + public void As_UnitSystem_ThrowsArgumentExceptionIfNotSupported() + { + var quantity = new VolumeFlow(value: 1, unit: VolumeFlow.BaseUnit); + var unsupportedUnitSystem = new UnitSystem(UnsupportedBaseUnits); + Assert.Throws(() => quantity.As(unsupportedUnitSystem)); + } - { - Assert.True(VolumeFlow.TryParse("1 bph", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.OilBarrelsPerHour, OilBarrelsPerHourTolerance); - Assert.Equal(VolumeFlowUnit.OilBarrelPerHour, parsed.Unit); - } + [Fact] + public virtual void ToUnit_UnitSystem_SI_ReturnsQuantityInSIUnits() + { + var quantity = new VolumeFlow(value: 1, unit: VolumeFlow.BaseUnit); + var expectedUnit = VolumeFlow.Info.GetDefaultUnit(UnitSystem.SI); + var expectedValue = quantity.As(expectedUnit); + Assert.Multiple(() => { - Assert.True(VolumeFlow.TryParse("1 bbl/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.OilBarrelsPerMinute, OilBarrelsPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.OilBarrelPerMinute, parsed.Unit); - } + VolumeFlow quantityToConvert = quantity; - { - Assert.True(VolumeFlow.TryParse("1 bpm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.OilBarrelsPerMinute, OilBarrelsPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.OilBarrelPerMinute, parsed.Unit); - } + VolumeFlow convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); + Assert.Equal(expectedUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }, () => { - Assert.True(VolumeFlow.TryParse("1 bbl/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.OilBarrelsPerSecond, OilBarrelsPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.OilBarrelPerSecond, parsed.Unit); - } + IQuantity quantityToConvert = quantity; - { - Assert.True(VolumeFlow.TryParse("1 gal (U. K.)/d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UkGallonsPerDay, UkGallonsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.UkGallonPerDay, parsed.Unit); - } + IQuantity convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); + Assert.Equal(expectedUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }, () => { - Assert.True(VolumeFlow.TryParse("1 gal (imp.)/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UkGallonsPerHour, UkGallonsPerHourTolerance); - Assert.Equal(VolumeFlowUnit.UkGallonPerHour, parsed.Unit); - } + IQuantity quantityToConvert = quantity; - { - Assert.True(VolumeFlow.TryParse("1 gal (imp.)/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UkGallonsPerMinute, UkGallonsPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.UkGallonPerMinute, parsed.Unit); - } + IQuantity convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); - { - Assert.True(VolumeFlow.TryParse("1 gal (imp.)/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UkGallonsPerSecond, UkGallonsPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.UkGallonPerSecond, parsed.Unit); - } + Assert.Equal(expectedUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }); + } + [Fact] + public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() + { + UnitSystem nullUnitSystem = null!; + Assert.Multiple(() => { - Assert.True(VolumeFlow.TryParse("1 gpd", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UsGallonsPerDay, UsGallonsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.UsGallonPerDay, parsed.Unit); - } - + var quantity = new VolumeFlow(value: 1, unit: VolumeFlow.BaseUnit); + Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); + }, () => { - Assert.True(VolumeFlow.TryParse("1 gal/d", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UsGallonsPerDay, UsGallonsPerDayTolerance); - Assert.Equal(VolumeFlowUnit.UsGallonPerDay, parsed.Unit); - } - + IQuantity quantity = new VolumeFlow(value: 1, unit: VolumeFlow.BaseUnit); + Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); + }, () => { - Assert.True(VolumeFlow.TryParse("1 gal (U.S.)/h", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UsGallonsPerHour, UsGallonsPerHourTolerance); - Assert.Equal(VolumeFlowUnit.UsGallonPerHour, parsed.Unit); - } + IQuantity quantity = new VolumeFlow(value: 1, unit: VolumeFlow.BaseUnit); + Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); + }); + } + [Fact] + public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() + { + var unsupportedUnitSystem = new UnitSystem(UnsupportedBaseUnits); + Assert.Multiple(() => { - Assert.True(VolumeFlow.TryParse("1 gal (U.S.)/min", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UsGallonsPerMinute, UsGallonsPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.UsGallonPerMinute, parsed.Unit); - } - + var quantity = new VolumeFlow(value: 1, unit: VolumeFlow.BaseUnit); + Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); + }, () => { - Assert.True(VolumeFlow.TryParse("1 GPM", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UsGallonsPerMinute, UsGallonsPerMinuteTolerance); - Assert.Equal(VolumeFlowUnit.UsGallonPerMinute, parsed.Unit); - } - + IQuantity quantity = new VolumeFlow(value: 1, unit: VolumeFlow.BaseUnit); + Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); + }, () => { - Assert.True(VolumeFlow.TryParse("1 gal (U.S.)/s", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UsGallonsPerSecond, UsGallonsPerSecondTolerance); - Assert.Equal(VolumeFlowUnit.UsGallonPerSecond, parsed.Unit); - } + IQuantity quantity = new VolumeFlow(value: 1, unit: VolumeFlow.BaseUnit); + Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); + }); + } + + [Theory] + [InlineData("en-US", "4.2 af/d", VolumeFlowUnit.AcreFootPerDay, 4.2)] + [InlineData("en-US", "4.2 af/h", VolumeFlowUnit.AcreFootPerHour, 4.2)] + [InlineData("en-US", "4.2 af/m", VolumeFlowUnit.AcreFootPerMinute, 4.2)] + [InlineData("en-US", "4.2 af/s", VolumeFlowUnit.AcreFootPerSecond, 4.2)] + [InlineData("en-US", "4.2 cl/day", VolumeFlowUnit.CentiliterPerDay, 4.2)] + [InlineData("en-US", "4.2 cl/d", VolumeFlowUnit.CentiliterPerDay, 4.2)] + [InlineData("en-US", "4.2 cLPD", VolumeFlowUnit.CentiliterPerDay, 4.2)] + [InlineData("en-US", "4.2 cl/h", VolumeFlowUnit.CentiliterPerHour, 4.2)] + [InlineData("en-US", "4.2 cLPH", VolumeFlowUnit.CentiliterPerHour, 4.2)] + [InlineData("en-US", "4.2 cl/min", VolumeFlowUnit.CentiliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 cLPM", VolumeFlowUnit.CentiliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 cl/s", VolumeFlowUnit.CentiliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 cLPS", VolumeFlowUnit.CentiliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 cm³/min", VolumeFlowUnit.CubicCentimeterPerMinute, 4.2)] + [InlineData("en-US", "4.2 dm³/min", VolumeFlowUnit.CubicDecimeterPerMinute, 4.2)] + [InlineData("en-US", "4.2 ft³/h", VolumeFlowUnit.CubicFootPerHour, 4.2)] + [InlineData("en-US", "4.2 cf/hr", VolumeFlowUnit.CubicFootPerHour, 4.2)] + [InlineData("en-US", "4.2 ft³/min", VolumeFlowUnit.CubicFootPerMinute, 4.2)] + [InlineData("en-US", "4.2 CFM", VolumeFlowUnit.CubicFootPerMinute, 4.2)] + [InlineData("en-US", "4.2 ft³/s", VolumeFlowUnit.CubicFootPerSecond, 4.2)] + [InlineData("en-US", "4.2 m³/d", VolumeFlowUnit.CubicMeterPerDay, 4.2)] + [InlineData("en-US", "4.2 m³/h", VolumeFlowUnit.CubicMeterPerHour, 4.2)] + [InlineData("en-US", "4.2 m³/min", VolumeFlowUnit.CubicMeterPerMinute, 4.2)] + [InlineData("en-US", "4.2 m³/s", VolumeFlowUnit.CubicMeterPerSecond, 4.2)] + [InlineData("en-US", "4.2 mm³/s", VolumeFlowUnit.CubicMillimeterPerSecond, 4.2)] + [InlineData("en-US", "4.2 cy/day", VolumeFlowUnit.CubicYardPerDay, 4.2)] + [InlineData("en-US", "4.2 yd³/h", VolumeFlowUnit.CubicYardPerHour, 4.2)] + [InlineData("en-US", "4.2 yd³/min", VolumeFlowUnit.CubicYardPerMinute, 4.2)] + [InlineData("en-US", "4.2 yd³/s", VolumeFlowUnit.CubicYardPerSecond, 4.2)] + [InlineData("en-US", "4.2 dal/day", VolumeFlowUnit.DecaliterPerDay, 4.2)] + [InlineData("en-US", "4.2 dal/d", VolumeFlowUnit.DecaliterPerDay, 4.2)] + [InlineData("en-US", "4.2 daLPD", VolumeFlowUnit.DecaliterPerDay, 4.2)] + [InlineData("en-US", "4.2 dal/h", VolumeFlowUnit.DecaliterPerHour, 4.2)] + [InlineData("en-US", "4.2 daLPH", VolumeFlowUnit.DecaliterPerHour, 4.2)] + [InlineData("en-US", "4.2 dal/min", VolumeFlowUnit.DecaliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 daLPM", VolumeFlowUnit.DecaliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 dal/s", VolumeFlowUnit.DecaliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 daLPS", VolumeFlowUnit.DecaliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 dl/day", VolumeFlowUnit.DeciliterPerDay, 4.2)] + [InlineData("en-US", "4.2 dl/d", VolumeFlowUnit.DeciliterPerDay, 4.2)] + [InlineData("en-US", "4.2 dLPD", VolumeFlowUnit.DeciliterPerDay, 4.2)] + [InlineData("en-US", "4.2 dl/h", VolumeFlowUnit.DeciliterPerHour, 4.2)] + [InlineData("en-US", "4.2 dLPH", VolumeFlowUnit.DeciliterPerHour, 4.2)] + [InlineData("en-US", "4.2 dl/min", VolumeFlowUnit.DeciliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 dLPM", VolumeFlowUnit.DeciliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 dl/s", VolumeFlowUnit.DeciliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 dLPS", VolumeFlowUnit.DeciliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 hl/day", VolumeFlowUnit.HectoliterPerDay, 4.2)] + [InlineData("en-US", "4.2 hl/d", VolumeFlowUnit.HectoliterPerDay, 4.2)] + [InlineData("en-US", "4.2 hLPD", VolumeFlowUnit.HectoliterPerDay, 4.2)] + [InlineData("en-US", "4.2 hl/h", VolumeFlowUnit.HectoliterPerHour, 4.2)] + [InlineData("en-US", "4.2 hLPH", VolumeFlowUnit.HectoliterPerHour, 4.2)] + [InlineData("en-US", "4.2 hl/min", VolumeFlowUnit.HectoliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 hLPM", VolumeFlowUnit.HectoliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 hl/s", VolumeFlowUnit.HectoliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 hLPS", VolumeFlowUnit.HectoliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 kl/day", VolumeFlowUnit.KiloliterPerDay, 4.2)] + [InlineData("en-US", "4.2 kl/d", VolumeFlowUnit.KiloliterPerDay, 4.2)] + [InlineData("en-US", "4.2 kLPD", VolumeFlowUnit.KiloliterPerDay, 4.2)] + [InlineData("en-US", "4.2 kl/h", VolumeFlowUnit.KiloliterPerHour, 4.2)] + [InlineData("en-US", "4.2 kLPH", VolumeFlowUnit.KiloliterPerHour, 4.2)] + [InlineData("en-US", "4.2 kl/min", VolumeFlowUnit.KiloliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 kLPM", VolumeFlowUnit.KiloliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 kl/s", VolumeFlowUnit.KiloliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 kLPS", VolumeFlowUnit.KiloliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 kgal (U.S.)/min", VolumeFlowUnit.KilousGallonPerMinute, 4.2)] + [InlineData("en-US", "4.2 KGPM", VolumeFlowUnit.KilousGallonPerMinute, 4.2)] + [InlineData("en-US", "4.2 l/day", VolumeFlowUnit.LiterPerDay, 4.2)] + [InlineData("en-US", "4.2 l/d", VolumeFlowUnit.LiterPerDay, 4.2)] + [InlineData("en-US", "4.2 LPD", VolumeFlowUnit.LiterPerDay, 4.2)] + [InlineData("en-US", "4.2 l/h", VolumeFlowUnit.LiterPerHour, 4.2)] + [InlineData("en-US", "4.2 LPH", VolumeFlowUnit.LiterPerHour, 4.2)] + [InlineData("en-US", "4.2 l/min", VolumeFlowUnit.LiterPerMinute, 4.2)] + [InlineData("en-US", "4.2 LPM", VolumeFlowUnit.LiterPerMinute, 4.2)] + [InlineData("en-US", "4.2 l/s", VolumeFlowUnit.LiterPerSecond, 4.2)] + [InlineData("en-US", "4.2 LPS", VolumeFlowUnit.LiterPerSecond, 4.2)] + [InlineData("en-US", "4.2 Ml/day", VolumeFlowUnit.MegaliterPerDay, 4.2)] + [InlineData("en-US", "4.2 Ml/d", VolumeFlowUnit.MegaliterPerDay, 4.2)] + [InlineData("en-US", "4.2 MLPD", VolumeFlowUnit.MegaliterPerDay, 4.2)] + [InlineData("en-US", "4.2 Ml/h", VolumeFlowUnit.MegaliterPerHour, 4.2)] + [InlineData("en-US", "4.2 MLPH", VolumeFlowUnit.MegaliterPerHour, 4.2)] + [InlineData("en-US", "4.2 Ml/min", VolumeFlowUnit.MegaliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 MLPM", VolumeFlowUnit.MegaliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 Ml/s", VolumeFlowUnit.MegaliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 MLPS", VolumeFlowUnit.MegaliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 Mgal (U. K.)/d", VolumeFlowUnit.MegaukGallonPerDay, 4.2)] + [InlineData("en-US", "4.2 Mgal (imp.)/s", VolumeFlowUnit.MegaukGallonPerSecond, 4.2)] + [InlineData("en-US", "4.2 Mgpd", VolumeFlowUnit.MegausGallonPerDay, 4.2)] + [InlineData("en-US", "4.2 Mgal/d", VolumeFlowUnit.MegausGallonPerDay, 4.2)] + [InlineData("en-US", "4.2 µl/day", VolumeFlowUnit.MicroliterPerDay, 4.2)] + [InlineData("en-US", "4.2 µl/d", VolumeFlowUnit.MicroliterPerDay, 4.2)] + [InlineData("en-US", "4.2 µLPD", VolumeFlowUnit.MicroliterPerDay, 4.2)] + [InlineData("en-US", "4.2 µl/h", VolumeFlowUnit.MicroliterPerHour, 4.2)] + [InlineData("en-US", "4.2 µLPH", VolumeFlowUnit.MicroliterPerHour, 4.2)] + [InlineData("en-US", "4.2 µl/min", VolumeFlowUnit.MicroliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 µLPM", VolumeFlowUnit.MicroliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 µl/s", VolumeFlowUnit.MicroliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 µLPS", VolumeFlowUnit.MicroliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 ml/day", VolumeFlowUnit.MilliliterPerDay, 4.2)] + [InlineData("en-US", "4.2 ml/d", VolumeFlowUnit.MilliliterPerDay, 4.2)] + [InlineData("en-US", "4.2 mLPD", VolumeFlowUnit.MilliliterPerDay, 4.2)] + [InlineData("en-US", "4.2 ml/h", VolumeFlowUnit.MilliliterPerHour, 4.2)] + [InlineData("en-US", "4.2 mLPH", VolumeFlowUnit.MilliliterPerHour, 4.2)] + [InlineData("en-US", "4.2 ml/min", VolumeFlowUnit.MilliliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 mLPM", VolumeFlowUnit.MilliliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 ml/s", VolumeFlowUnit.MilliliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 mLPS", VolumeFlowUnit.MilliliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 MGD", VolumeFlowUnit.MillionUsGallonPerDay, 4.2)] + [InlineData("en-US", "4.2 nl/day", VolumeFlowUnit.NanoliterPerDay, 4.2)] + [InlineData("en-US", "4.2 nl/d", VolumeFlowUnit.NanoliterPerDay, 4.2)] + [InlineData("en-US", "4.2 nLPD", VolumeFlowUnit.NanoliterPerDay, 4.2)] + [InlineData("en-US", "4.2 nl/h", VolumeFlowUnit.NanoliterPerHour, 4.2)] + [InlineData("en-US", "4.2 nLPH", VolumeFlowUnit.NanoliterPerHour, 4.2)] + [InlineData("en-US", "4.2 nl/min", VolumeFlowUnit.NanoliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 nLPM", VolumeFlowUnit.NanoliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 nl/s", VolumeFlowUnit.NanoliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 nLPS", VolumeFlowUnit.NanoliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 bbl/d", VolumeFlowUnit.OilBarrelPerDay, 4.2)] + [InlineData("en-US", "4.2 BOPD", VolumeFlowUnit.OilBarrelPerDay, 4.2)] + [InlineData("en-US", "4.2 bbl/hr", VolumeFlowUnit.OilBarrelPerHour, 4.2)] + [InlineData("en-US", "4.2 bph", VolumeFlowUnit.OilBarrelPerHour, 4.2)] + [InlineData("en-US", "4.2 bbl/min", VolumeFlowUnit.OilBarrelPerMinute, 4.2)] + [InlineData("en-US", "4.2 bpm", VolumeFlowUnit.OilBarrelPerMinute, 4.2)] + [InlineData("en-US", "4.2 bbl/s", VolumeFlowUnit.OilBarrelPerSecond, 4.2)] + [InlineData("en-US", "4.2 gal (U. K.)/d", VolumeFlowUnit.UkGallonPerDay, 4.2)] + [InlineData("en-US", "4.2 gal (imp.)/h", VolumeFlowUnit.UkGallonPerHour, 4.2)] + [InlineData("en-US", "4.2 gal (imp.)/min", VolumeFlowUnit.UkGallonPerMinute, 4.2)] + [InlineData("en-US", "4.2 gal (imp.)/s", VolumeFlowUnit.UkGallonPerSecond, 4.2)] + [InlineData("en-US", "4.2 gpd", VolumeFlowUnit.UsGallonPerDay, 4.2)] + [InlineData("en-US", "4.2 gal/d", VolumeFlowUnit.UsGallonPerDay, 4.2)] + [InlineData("en-US", "4.2 gal (U.S.)/h", VolumeFlowUnit.UsGallonPerHour, 4.2)] + [InlineData("en-US", "4.2 gal (U.S.)/min", VolumeFlowUnit.UsGallonPerMinute, 4.2)] + [InlineData("en-US", "4.2 GPM", VolumeFlowUnit.UsGallonPerMinute, 4.2)] + [InlineData("en-US", "4.2 gal (U.S.)/s", VolumeFlowUnit.UsGallonPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 сл/ч", VolumeFlowUnit.CentiliterPerHour, 4.2)] + [InlineData("ru-RU", "4,2 сл/мин", VolumeFlowUnit.CentiliterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 сл/c", VolumeFlowUnit.CentiliterPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 см³/мин", VolumeFlowUnit.CubicCentimeterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 дм³/мин", VolumeFlowUnit.CubicDecimeterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 м³/ч", VolumeFlowUnit.CubicMeterPerHour, 4.2)] + [InlineData("ru-RU", "4,2 м³/мин", VolumeFlowUnit.CubicMeterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 м³/с", VolumeFlowUnit.CubicMeterPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 мм³/с", VolumeFlowUnit.CubicMillimeterPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 дал/ч", VolumeFlowUnit.DecaliterPerHour, 4.2)] + [InlineData("ru-RU", "4,2 дал/мин", VolumeFlowUnit.DecaliterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 дал/c", VolumeFlowUnit.DecaliterPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 дл/ч", VolumeFlowUnit.DeciliterPerHour, 4.2)] + [InlineData("ru-RU", "4,2 дл/мин", VolumeFlowUnit.DeciliterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 дл/c", VolumeFlowUnit.DeciliterPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 гл/ч", VolumeFlowUnit.HectoliterPerHour, 4.2)] + [InlineData("ru-RU", "4,2 гл/мин", VolumeFlowUnit.HectoliterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 гл/c", VolumeFlowUnit.HectoliterPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 кл/ч", VolumeFlowUnit.KiloliterPerHour, 4.2)] + [InlineData("ru-RU", "4,2 кл/мин", VolumeFlowUnit.KiloliterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 кл/c", VolumeFlowUnit.KiloliterPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 л/ч", VolumeFlowUnit.LiterPerHour, 4.2)] + [InlineData("ru-RU", "4,2 л/мин", VolumeFlowUnit.LiterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 л/c", VolumeFlowUnit.LiterPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 Мл/ч", VolumeFlowUnit.MegaliterPerHour, 4.2)] + [InlineData("ru-RU", "4,2 Мл/мин", VolumeFlowUnit.MegaliterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 Мл/c", VolumeFlowUnit.MegaliterPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 мкл/ч", VolumeFlowUnit.MicroliterPerHour, 4.2)] + [InlineData("ru-RU", "4,2 мкл/мин", VolumeFlowUnit.MicroliterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 мкл/c", VolumeFlowUnit.MicroliterPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 мл/ч", VolumeFlowUnit.MilliliterPerHour, 4.2)] + [InlineData("ru-RU", "4,2 мл/мин", VolumeFlowUnit.MilliliterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 мл/c", VolumeFlowUnit.MilliliterPerSecond, 4.2)] + [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, decimal expectedValue) + { + using var _ = new CultureScope(culture); + var parsed = VolumeFlow.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); + } + [Theory] + [InlineData("en-US", "4.2 af/d", VolumeFlowUnit.AcreFootPerDay, 4.2)] + [InlineData("en-US", "4.2 af/h", VolumeFlowUnit.AcreFootPerHour, 4.2)] + [InlineData("en-US", "4.2 af/m", VolumeFlowUnit.AcreFootPerMinute, 4.2)] + [InlineData("en-US", "4.2 af/s", VolumeFlowUnit.AcreFootPerSecond, 4.2)] + [InlineData("en-US", "4.2 cl/day", VolumeFlowUnit.CentiliterPerDay, 4.2)] + [InlineData("en-US", "4.2 cl/d", VolumeFlowUnit.CentiliterPerDay, 4.2)] + [InlineData("en-US", "4.2 cLPD", VolumeFlowUnit.CentiliterPerDay, 4.2)] + [InlineData("en-US", "4.2 cl/h", VolumeFlowUnit.CentiliterPerHour, 4.2)] + [InlineData("en-US", "4.2 cLPH", VolumeFlowUnit.CentiliterPerHour, 4.2)] + [InlineData("en-US", "4.2 cl/min", VolumeFlowUnit.CentiliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 cLPM", VolumeFlowUnit.CentiliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 cl/s", VolumeFlowUnit.CentiliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 cLPS", VolumeFlowUnit.CentiliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 cm³/min", VolumeFlowUnit.CubicCentimeterPerMinute, 4.2)] + [InlineData("en-US", "4.2 dm³/min", VolumeFlowUnit.CubicDecimeterPerMinute, 4.2)] + [InlineData("en-US", "4.2 ft³/h", VolumeFlowUnit.CubicFootPerHour, 4.2)] + [InlineData("en-US", "4.2 cf/hr", VolumeFlowUnit.CubicFootPerHour, 4.2)] + [InlineData("en-US", "4.2 ft³/min", VolumeFlowUnit.CubicFootPerMinute, 4.2)] + [InlineData("en-US", "4.2 CFM", VolumeFlowUnit.CubicFootPerMinute, 4.2)] + [InlineData("en-US", "4.2 ft³/s", VolumeFlowUnit.CubicFootPerSecond, 4.2)] + [InlineData("en-US", "4.2 m³/d", VolumeFlowUnit.CubicMeterPerDay, 4.2)] + [InlineData("en-US", "4.2 m³/h", VolumeFlowUnit.CubicMeterPerHour, 4.2)] + [InlineData("en-US", "4.2 m³/min", VolumeFlowUnit.CubicMeterPerMinute, 4.2)] + [InlineData("en-US", "4.2 m³/s", VolumeFlowUnit.CubicMeterPerSecond, 4.2)] + [InlineData("en-US", "4.2 mm³/s", VolumeFlowUnit.CubicMillimeterPerSecond, 4.2)] + [InlineData("en-US", "4.2 cy/day", VolumeFlowUnit.CubicYardPerDay, 4.2)] + [InlineData("en-US", "4.2 yd³/h", VolumeFlowUnit.CubicYardPerHour, 4.2)] + [InlineData("en-US", "4.2 yd³/min", VolumeFlowUnit.CubicYardPerMinute, 4.2)] + [InlineData("en-US", "4.2 yd³/s", VolumeFlowUnit.CubicYardPerSecond, 4.2)] + [InlineData("en-US", "4.2 dal/day", VolumeFlowUnit.DecaliterPerDay, 4.2)] + [InlineData("en-US", "4.2 dal/d", VolumeFlowUnit.DecaliterPerDay, 4.2)] + [InlineData("en-US", "4.2 daLPD", VolumeFlowUnit.DecaliterPerDay, 4.2)] + [InlineData("en-US", "4.2 dal/h", VolumeFlowUnit.DecaliterPerHour, 4.2)] + [InlineData("en-US", "4.2 daLPH", VolumeFlowUnit.DecaliterPerHour, 4.2)] + [InlineData("en-US", "4.2 dal/min", VolumeFlowUnit.DecaliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 daLPM", VolumeFlowUnit.DecaliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 dal/s", VolumeFlowUnit.DecaliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 daLPS", VolumeFlowUnit.DecaliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 dl/day", VolumeFlowUnit.DeciliterPerDay, 4.2)] + [InlineData("en-US", "4.2 dl/d", VolumeFlowUnit.DeciliterPerDay, 4.2)] + [InlineData("en-US", "4.2 dLPD", VolumeFlowUnit.DeciliterPerDay, 4.2)] + [InlineData("en-US", "4.2 dl/h", VolumeFlowUnit.DeciliterPerHour, 4.2)] + [InlineData("en-US", "4.2 dLPH", VolumeFlowUnit.DeciliterPerHour, 4.2)] + [InlineData("en-US", "4.2 dl/min", VolumeFlowUnit.DeciliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 dLPM", VolumeFlowUnit.DeciliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 dl/s", VolumeFlowUnit.DeciliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 dLPS", VolumeFlowUnit.DeciliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 hl/day", VolumeFlowUnit.HectoliterPerDay, 4.2)] + [InlineData("en-US", "4.2 hl/d", VolumeFlowUnit.HectoliterPerDay, 4.2)] + [InlineData("en-US", "4.2 hLPD", VolumeFlowUnit.HectoliterPerDay, 4.2)] + [InlineData("en-US", "4.2 hl/h", VolumeFlowUnit.HectoliterPerHour, 4.2)] + [InlineData("en-US", "4.2 hLPH", VolumeFlowUnit.HectoliterPerHour, 4.2)] + [InlineData("en-US", "4.2 hl/min", VolumeFlowUnit.HectoliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 hLPM", VolumeFlowUnit.HectoliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 hl/s", VolumeFlowUnit.HectoliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 hLPS", VolumeFlowUnit.HectoliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 kl/day", VolumeFlowUnit.KiloliterPerDay, 4.2)] + [InlineData("en-US", "4.2 kl/d", VolumeFlowUnit.KiloliterPerDay, 4.2)] + [InlineData("en-US", "4.2 kLPD", VolumeFlowUnit.KiloliterPerDay, 4.2)] + [InlineData("en-US", "4.2 kl/h", VolumeFlowUnit.KiloliterPerHour, 4.2)] + [InlineData("en-US", "4.2 kLPH", VolumeFlowUnit.KiloliterPerHour, 4.2)] + [InlineData("en-US", "4.2 kl/min", VolumeFlowUnit.KiloliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 kLPM", VolumeFlowUnit.KiloliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 kl/s", VolumeFlowUnit.KiloliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 kLPS", VolumeFlowUnit.KiloliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 kgal (U.S.)/min", VolumeFlowUnit.KilousGallonPerMinute, 4.2)] + [InlineData("en-US", "4.2 KGPM", VolumeFlowUnit.KilousGallonPerMinute, 4.2)] + [InlineData("en-US", "4.2 l/day", VolumeFlowUnit.LiterPerDay, 4.2)] + [InlineData("en-US", "4.2 l/d", VolumeFlowUnit.LiterPerDay, 4.2)] + [InlineData("en-US", "4.2 LPD", VolumeFlowUnit.LiterPerDay, 4.2)] + [InlineData("en-US", "4.2 l/h", VolumeFlowUnit.LiterPerHour, 4.2)] + [InlineData("en-US", "4.2 LPH", VolumeFlowUnit.LiterPerHour, 4.2)] + [InlineData("en-US", "4.2 l/min", VolumeFlowUnit.LiterPerMinute, 4.2)] + [InlineData("en-US", "4.2 LPM", VolumeFlowUnit.LiterPerMinute, 4.2)] + [InlineData("en-US", "4.2 l/s", VolumeFlowUnit.LiterPerSecond, 4.2)] + [InlineData("en-US", "4.2 LPS", VolumeFlowUnit.LiterPerSecond, 4.2)] + [InlineData("en-US", "4.2 Ml/day", VolumeFlowUnit.MegaliterPerDay, 4.2)] + [InlineData("en-US", "4.2 Ml/d", VolumeFlowUnit.MegaliterPerDay, 4.2)] + [InlineData("en-US", "4.2 MLPD", VolumeFlowUnit.MegaliterPerDay, 4.2)] + [InlineData("en-US", "4.2 Ml/h", VolumeFlowUnit.MegaliterPerHour, 4.2)] + [InlineData("en-US", "4.2 MLPH", VolumeFlowUnit.MegaliterPerHour, 4.2)] + [InlineData("en-US", "4.2 Ml/min", VolumeFlowUnit.MegaliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 MLPM", VolumeFlowUnit.MegaliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 Ml/s", VolumeFlowUnit.MegaliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 MLPS", VolumeFlowUnit.MegaliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 Mgal (U. K.)/d", VolumeFlowUnit.MegaukGallonPerDay, 4.2)] + [InlineData("en-US", "4.2 Mgal (imp.)/s", VolumeFlowUnit.MegaukGallonPerSecond, 4.2)] + [InlineData("en-US", "4.2 Mgpd", VolumeFlowUnit.MegausGallonPerDay, 4.2)] + [InlineData("en-US", "4.2 Mgal/d", VolumeFlowUnit.MegausGallonPerDay, 4.2)] + [InlineData("en-US", "4.2 µl/day", VolumeFlowUnit.MicroliterPerDay, 4.2)] + [InlineData("en-US", "4.2 µl/d", VolumeFlowUnit.MicroliterPerDay, 4.2)] + [InlineData("en-US", "4.2 µLPD", VolumeFlowUnit.MicroliterPerDay, 4.2)] + [InlineData("en-US", "4.2 µl/h", VolumeFlowUnit.MicroliterPerHour, 4.2)] + [InlineData("en-US", "4.2 µLPH", VolumeFlowUnit.MicroliterPerHour, 4.2)] + [InlineData("en-US", "4.2 µl/min", VolumeFlowUnit.MicroliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 µLPM", VolumeFlowUnit.MicroliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 µl/s", VolumeFlowUnit.MicroliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 µLPS", VolumeFlowUnit.MicroliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 ml/day", VolumeFlowUnit.MilliliterPerDay, 4.2)] + [InlineData("en-US", "4.2 ml/d", VolumeFlowUnit.MilliliterPerDay, 4.2)] + [InlineData("en-US", "4.2 mLPD", VolumeFlowUnit.MilliliterPerDay, 4.2)] + [InlineData("en-US", "4.2 ml/h", VolumeFlowUnit.MilliliterPerHour, 4.2)] + [InlineData("en-US", "4.2 mLPH", VolumeFlowUnit.MilliliterPerHour, 4.2)] + [InlineData("en-US", "4.2 ml/min", VolumeFlowUnit.MilliliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 mLPM", VolumeFlowUnit.MilliliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 ml/s", VolumeFlowUnit.MilliliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 mLPS", VolumeFlowUnit.MilliliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 MGD", VolumeFlowUnit.MillionUsGallonPerDay, 4.2)] + [InlineData("en-US", "4.2 nl/day", VolumeFlowUnit.NanoliterPerDay, 4.2)] + [InlineData("en-US", "4.2 nl/d", VolumeFlowUnit.NanoliterPerDay, 4.2)] + [InlineData("en-US", "4.2 nLPD", VolumeFlowUnit.NanoliterPerDay, 4.2)] + [InlineData("en-US", "4.2 nl/h", VolumeFlowUnit.NanoliterPerHour, 4.2)] + [InlineData("en-US", "4.2 nLPH", VolumeFlowUnit.NanoliterPerHour, 4.2)] + [InlineData("en-US", "4.2 nl/min", VolumeFlowUnit.NanoliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 nLPM", VolumeFlowUnit.NanoliterPerMinute, 4.2)] + [InlineData("en-US", "4.2 nl/s", VolumeFlowUnit.NanoliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 nLPS", VolumeFlowUnit.NanoliterPerSecond, 4.2)] + [InlineData("en-US", "4.2 bbl/d", VolumeFlowUnit.OilBarrelPerDay, 4.2)] + [InlineData("en-US", "4.2 BOPD", VolumeFlowUnit.OilBarrelPerDay, 4.2)] + [InlineData("en-US", "4.2 bbl/hr", VolumeFlowUnit.OilBarrelPerHour, 4.2)] + [InlineData("en-US", "4.2 bph", VolumeFlowUnit.OilBarrelPerHour, 4.2)] + [InlineData("en-US", "4.2 bbl/min", VolumeFlowUnit.OilBarrelPerMinute, 4.2)] + [InlineData("en-US", "4.2 bpm", VolumeFlowUnit.OilBarrelPerMinute, 4.2)] + [InlineData("en-US", "4.2 bbl/s", VolumeFlowUnit.OilBarrelPerSecond, 4.2)] + [InlineData("en-US", "4.2 gal (U. K.)/d", VolumeFlowUnit.UkGallonPerDay, 4.2)] + [InlineData("en-US", "4.2 gal (imp.)/h", VolumeFlowUnit.UkGallonPerHour, 4.2)] + [InlineData("en-US", "4.2 gal (imp.)/min", VolumeFlowUnit.UkGallonPerMinute, 4.2)] + [InlineData("en-US", "4.2 gal (imp.)/s", VolumeFlowUnit.UkGallonPerSecond, 4.2)] + [InlineData("en-US", "4.2 gpd", VolumeFlowUnit.UsGallonPerDay, 4.2)] + [InlineData("en-US", "4.2 gal/d", VolumeFlowUnit.UsGallonPerDay, 4.2)] + [InlineData("en-US", "4.2 gal (U.S.)/h", VolumeFlowUnit.UsGallonPerHour, 4.2)] + [InlineData("en-US", "4.2 gal (U.S.)/min", VolumeFlowUnit.UsGallonPerMinute, 4.2)] + [InlineData("en-US", "4.2 GPM", VolumeFlowUnit.UsGallonPerMinute, 4.2)] + [InlineData("en-US", "4.2 gal (U.S.)/s", VolumeFlowUnit.UsGallonPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 сл/ч", VolumeFlowUnit.CentiliterPerHour, 4.2)] + [InlineData("ru-RU", "4,2 сл/мин", VolumeFlowUnit.CentiliterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 сл/c", VolumeFlowUnit.CentiliterPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 см³/мин", VolumeFlowUnit.CubicCentimeterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 дм³/мин", VolumeFlowUnit.CubicDecimeterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 м³/ч", VolumeFlowUnit.CubicMeterPerHour, 4.2)] + [InlineData("ru-RU", "4,2 м³/мин", VolumeFlowUnit.CubicMeterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 м³/с", VolumeFlowUnit.CubicMeterPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 мм³/с", VolumeFlowUnit.CubicMillimeterPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 дал/ч", VolumeFlowUnit.DecaliterPerHour, 4.2)] + [InlineData("ru-RU", "4,2 дал/мин", VolumeFlowUnit.DecaliterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 дал/c", VolumeFlowUnit.DecaliterPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 дл/ч", VolumeFlowUnit.DeciliterPerHour, 4.2)] + [InlineData("ru-RU", "4,2 дл/мин", VolumeFlowUnit.DeciliterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 дл/c", VolumeFlowUnit.DeciliterPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 гл/ч", VolumeFlowUnit.HectoliterPerHour, 4.2)] + [InlineData("ru-RU", "4,2 гл/мин", VolumeFlowUnit.HectoliterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 гл/c", VolumeFlowUnit.HectoliterPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 кл/ч", VolumeFlowUnit.KiloliterPerHour, 4.2)] + [InlineData("ru-RU", "4,2 кл/мин", VolumeFlowUnit.KiloliterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 кл/c", VolumeFlowUnit.KiloliterPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 л/ч", VolumeFlowUnit.LiterPerHour, 4.2)] + [InlineData("ru-RU", "4,2 л/мин", VolumeFlowUnit.LiterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 л/c", VolumeFlowUnit.LiterPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 Мл/ч", VolumeFlowUnit.MegaliterPerHour, 4.2)] + [InlineData("ru-RU", "4,2 Мл/мин", VolumeFlowUnit.MegaliterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 Мл/c", VolumeFlowUnit.MegaliterPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 мкл/ч", VolumeFlowUnit.MicroliterPerHour, 4.2)] + [InlineData("ru-RU", "4,2 мкл/мин", VolumeFlowUnit.MicroliterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 мкл/c", VolumeFlowUnit.MicroliterPerSecond, 4.2)] + [InlineData("ru-RU", "4,2 мл/ч", VolumeFlowUnit.MilliliterPerHour, 4.2)] + [InlineData("ru-RU", "4,2 мл/мин", VolumeFlowUnit.MilliliterPerMinute, 4.2)] + [InlineData("ru-RU", "4,2 мл/c", VolumeFlowUnit.MilliliterPerSecond, 4.2)] + [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, decimal expectedValue) + { + using var _ = new CultureScope(culture); + Assert.True(VolumeFlow.TryParse(quantityString, out VolumeFlow parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -4365,6 +2665,137 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Volume Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", VolumeFlowUnit.AcreFootPerDay, "af/d")] + [InlineData("en-US", VolumeFlowUnit.AcreFootPerHour, "af/h")] + [InlineData("en-US", VolumeFlowUnit.AcreFootPerMinute, "af/m")] + [InlineData("en-US", VolumeFlowUnit.AcreFootPerSecond, "af/s")] + [InlineData("en-US", VolumeFlowUnit.CentiliterPerDay, "cl/day")] + [InlineData("en-US", VolumeFlowUnit.CentiliterPerHour, "cl/h")] + [InlineData("en-US", VolumeFlowUnit.CentiliterPerMinute, "cl/min")] + [InlineData("en-US", VolumeFlowUnit.CentiliterPerSecond, "cl/s")] + [InlineData("en-US", VolumeFlowUnit.CubicCentimeterPerMinute, "cm³/min")] + [InlineData("en-US", VolumeFlowUnit.CubicDecimeterPerMinute, "dm³/min")] + [InlineData("en-US", VolumeFlowUnit.CubicFootPerHour, "ft³/h")] + [InlineData("en-US", VolumeFlowUnit.CubicFootPerMinute, "ft³/min")] + [InlineData("en-US", VolumeFlowUnit.CubicFootPerSecond, "ft³/s")] + [InlineData("en-US", VolumeFlowUnit.CubicMeterPerDay, "m³/d")] + [InlineData("en-US", VolumeFlowUnit.CubicMeterPerHour, "m³/h")] + [InlineData("en-US", VolumeFlowUnit.CubicMeterPerMinute, "m³/min")] + [InlineData("en-US", VolumeFlowUnit.CubicMeterPerSecond, "m³/s")] + [InlineData("en-US", VolumeFlowUnit.CubicMillimeterPerSecond, "mm³/s")] + [InlineData("en-US", VolumeFlowUnit.CubicYardPerDay, "cy/day")] + [InlineData("en-US", VolumeFlowUnit.CubicYardPerHour, "yd³/h")] + [InlineData("en-US", VolumeFlowUnit.CubicYardPerMinute, "yd³/min")] + [InlineData("en-US", VolumeFlowUnit.CubicYardPerSecond, "yd³/s")] + [InlineData("en-US", VolumeFlowUnit.DecaliterPerDay, "dal/day")] + [InlineData("en-US", VolumeFlowUnit.DecaliterPerHour, "dal/h")] + [InlineData("en-US", VolumeFlowUnit.DecaliterPerMinute, "dal/min")] + [InlineData("en-US", VolumeFlowUnit.DecaliterPerSecond, "dal/s")] + [InlineData("en-US", VolumeFlowUnit.DeciliterPerDay, "dl/day")] + [InlineData("en-US", VolumeFlowUnit.DeciliterPerHour, "dl/h")] + [InlineData("en-US", VolumeFlowUnit.DeciliterPerMinute, "dl/min")] + [InlineData("en-US", VolumeFlowUnit.DeciliterPerSecond, "dl/s")] + [InlineData("en-US", VolumeFlowUnit.HectoliterPerDay, "hl/day")] + [InlineData("en-US", VolumeFlowUnit.HectoliterPerHour, "hl/h")] + [InlineData("en-US", VolumeFlowUnit.HectoliterPerMinute, "hl/min")] + [InlineData("en-US", VolumeFlowUnit.HectoliterPerSecond, "hl/s")] + [InlineData("en-US", VolumeFlowUnit.KiloliterPerDay, "kl/day")] + [InlineData("en-US", VolumeFlowUnit.KiloliterPerHour, "kl/h")] + [InlineData("en-US", VolumeFlowUnit.KiloliterPerMinute, "kl/min")] + [InlineData("en-US", VolumeFlowUnit.KiloliterPerSecond, "kl/s")] + [InlineData("en-US", VolumeFlowUnit.KilousGallonPerMinute, "kgal (U.S.)/min")] + [InlineData("en-US", VolumeFlowUnit.LiterPerDay, "l/day")] + [InlineData("en-US", VolumeFlowUnit.LiterPerHour, "l/h")] + [InlineData("en-US", VolumeFlowUnit.LiterPerMinute, "l/min")] + [InlineData("en-US", VolumeFlowUnit.LiterPerSecond, "l/s")] + [InlineData("en-US", VolumeFlowUnit.MegaliterPerDay, "Ml/day")] + [InlineData("en-US", VolumeFlowUnit.MegaliterPerHour, "Ml/h")] + [InlineData("en-US", VolumeFlowUnit.MegaliterPerMinute, "Ml/min")] + [InlineData("en-US", VolumeFlowUnit.MegaliterPerSecond, "Ml/s")] + [InlineData("en-US", VolumeFlowUnit.MegaukGallonPerDay, "Mgal (U. K.)/d")] + [InlineData("en-US", VolumeFlowUnit.MegaukGallonPerSecond, "Mgal (imp.)/s")] + [InlineData("en-US", VolumeFlowUnit.MegausGallonPerDay, "Mgpd")] + [InlineData("en-US", VolumeFlowUnit.MicroliterPerDay, "µl/day")] + [InlineData("en-US", VolumeFlowUnit.MicroliterPerHour, "µl/h")] + [InlineData("en-US", VolumeFlowUnit.MicroliterPerMinute, "µl/min")] + [InlineData("en-US", VolumeFlowUnit.MicroliterPerSecond, "µl/s")] + [InlineData("en-US", VolumeFlowUnit.MilliliterPerDay, "ml/day")] + [InlineData("en-US", VolumeFlowUnit.MilliliterPerHour, "ml/h")] + [InlineData("en-US", VolumeFlowUnit.MilliliterPerMinute, "ml/min")] + [InlineData("en-US", VolumeFlowUnit.MilliliterPerSecond, "ml/s")] + [InlineData("en-US", VolumeFlowUnit.MillionUsGallonPerDay, "MGD")] + [InlineData("en-US", VolumeFlowUnit.NanoliterPerDay, "nl/day")] + [InlineData("en-US", VolumeFlowUnit.NanoliterPerHour, "nl/h")] + [InlineData("en-US", VolumeFlowUnit.NanoliterPerMinute, "nl/min")] + [InlineData("en-US", VolumeFlowUnit.NanoliterPerSecond, "nl/s")] + [InlineData("en-US", VolumeFlowUnit.OilBarrelPerDay, "bbl/d")] + [InlineData("en-US", VolumeFlowUnit.OilBarrelPerHour, "bbl/hr")] + [InlineData("en-US", VolumeFlowUnit.OilBarrelPerMinute, "bbl/min")] + [InlineData("en-US", VolumeFlowUnit.OilBarrelPerSecond, "bbl/s")] + [InlineData("en-US", VolumeFlowUnit.UkGallonPerDay, "gal (U. K.)/d")] + [InlineData("en-US", VolumeFlowUnit.UkGallonPerHour, "gal (imp.)/h")] + [InlineData("en-US", VolumeFlowUnit.UkGallonPerMinute, "gal (imp.)/min")] + [InlineData("en-US", VolumeFlowUnit.UkGallonPerSecond, "gal (imp.)/s")] + [InlineData("en-US", VolumeFlowUnit.UsGallonPerDay, "gpd")] + [InlineData("en-US", VolumeFlowUnit.UsGallonPerHour, "gal (U.S.)/h")] + [InlineData("en-US", VolumeFlowUnit.UsGallonPerMinute, "gal (U.S.)/min")] + [InlineData("en-US", VolumeFlowUnit.UsGallonPerSecond, "gal (U.S.)/s")] + [InlineData("ru-RU", VolumeFlowUnit.CentiliterPerHour, "сл/ч")] + [InlineData("ru-RU", VolumeFlowUnit.CentiliterPerMinute, "сл/мин")] + [InlineData("ru-RU", VolumeFlowUnit.CentiliterPerSecond, "сл/c")] + [InlineData("ru-RU", VolumeFlowUnit.CubicCentimeterPerMinute, "см³/мин")] + [InlineData("ru-RU", VolumeFlowUnit.CubicDecimeterPerMinute, "дм³/мин")] + [InlineData("ru-RU", VolumeFlowUnit.CubicMeterPerHour, "м³/ч")] + [InlineData("ru-RU", VolumeFlowUnit.CubicMeterPerMinute, "м³/мин")] + [InlineData("ru-RU", VolumeFlowUnit.CubicMeterPerSecond, "м³/с")] + [InlineData("ru-RU", VolumeFlowUnit.CubicMillimeterPerSecond, "мм³/с")] + [InlineData("ru-RU", VolumeFlowUnit.DecaliterPerHour, "дал/ч")] + [InlineData("ru-RU", VolumeFlowUnit.DecaliterPerMinute, "дал/мин")] + [InlineData("ru-RU", VolumeFlowUnit.DecaliterPerSecond, "дал/c")] + [InlineData("ru-RU", VolumeFlowUnit.DeciliterPerHour, "дл/ч")] + [InlineData("ru-RU", VolumeFlowUnit.DeciliterPerMinute, "дл/мин")] + [InlineData("ru-RU", VolumeFlowUnit.DeciliterPerSecond, "дл/c")] + [InlineData("ru-RU", VolumeFlowUnit.HectoliterPerHour, "гл/ч")] + [InlineData("ru-RU", VolumeFlowUnit.HectoliterPerMinute, "гл/мин")] + [InlineData("ru-RU", VolumeFlowUnit.HectoliterPerSecond, "гл/c")] + [InlineData("ru-RU", VolumeFlowUnit.KiloliterPerHour, "кл/ч")] + [InlineData("ru-RU", VolumeFlowUnit.KiloliterPerMinute, "кл/мин")] + [InlineData("ru-RU", VolumeFlowUnit.KiloliterPerSecond, "кл/c")] + [InlineData("ru-RU", VolumeFlowUnit.LiterPerHour, "л/ч")] + [InlineData("ru-RU", VolumeFlowUnit.LiterPerMinute, "л/мин")] + [InlineData("ru-RU", VolumeFlowUnit.LiterPerSecond, "л/c")] + [InlineData("ru-RU", VolumeFlowUnit.MegaliterPerHour, "Мл/ч")] + [InlineData("ru-RU", VolumeFlowUnit.MegaliterPerMinute, "Мл/мин")] + [InlineData("ru-RU", VolumeFlowUnit.MegaliterPerSecond, "Мл/c")] + [InlineData("ru-RU", VolumeFlowUnit.MicroliterPerHour, "мкл/ч")] + [InlineData("ru-RU", VolumeFlowUnit.MicroliterPerMinute, "мкл/мин")] + [InlineData("ru-RU", VolumeFlowUnit.MicroliterPerSecond, "мкл/c")] + [InlineData("ru-RU", VolumeFlowUnit.MilliliterPerHour, "мл/ч")] + [InlineData("ru-RU", VolumeFlowUnit.MilliliterPerMinute, "мл/мин")] + [InlineData("ru-RU", VolumeFlowUnit.MilliliterPerSecond, "мл/c")] + [InlineData("ru-RU", VolumeFlowUnit.NanoliterPerHour, "нл/ч")] + [InlineData("ru-RU", VolumeFlowUnit.NanoliterPerMinute, "нл/мин")] + [InlineData("ru-RU", VolumeFlowUnit.NanoliterPerSecond, "нл/c")] + public void GetAbbreviationForCulture(string culture, VolumeFlowUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = VolumeFlow.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(VolumeFlow.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = VolumeFlow.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(VolumeFlowUnit unit) @@ -4395,6 +2826,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); }); } @@ -4418,106 +2850,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] @@ -4563,8 +2997,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); @@ -4601,23 +3033,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = VolumeFlow.FromCubicMetersPerSecond(1); - Assert.True(v.Equals(VolumeFlow.FromCubicMetersPerSecond(1), CubicMetersPerSecondTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(VolumeFlow.Zero, CubicMetersPerSecondTolerance, ComparisonType.Relative)); - Assert.True(VolumeFlow.FromCubicMetersPerSecond(100).Equals(VolumeFlow.FromCubicMetersPerSecond(120), 0.3, ComparisonType.Relative)); - Assert.False(VolumeFlow.FromCubicMetersPerSecond(100).Equals(VolumeFlow.FromCubicMetersPerSecond(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = VolumeFlow.FromCubicMetersPerSecond(1); - Assert.Throws(() => v.Equals(VolumeFlow.FromCubicMetersPerSecond(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -4632,6 +3047,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(cubicmeterpersecond.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = VolumeFlow.FromCubicMetersPerSecond(1); + var negativeTolerance = VolumeFlow.FromCubicMetersPerSecond(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -4648,6 +3089,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() { @@ -4854,158 +3307,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(VolumeFlow))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(VolumeFlowUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal(VolumeFlow.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal(VolumeFlow.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal(new {VolumeFlow.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 f6a65135fa..6ed8654b79 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumePerLengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumePerLengthTestsBase.g.cs @@ -128,7 +128,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new VolumePerLength(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -141,15 +141,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void VolumePerLength_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + VolumePerLengthUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new VolumePerLength(1, VolumePerLengthUnit.CubicMeterPerMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(VolumePerLength.Zero, quantityInfo.Zero); Assert.Equal("VolumePerLength", quantityInfo.Name); + Assert.Equal(VolumePerLength.Zero, quantityInfo.Zero); + Assert.Equal(VolumePerLength.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(VolumePerLength.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -171,39 +189,39 @@ public void CubicMeterPerMeterToVolumePerLengthUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = VolumePerLength.From(1, VolumePerLengthUnit.CubicMeterPerMeter); - AssertEx.EqualTolerance(1, quantity00.CubicMetersPerMeter, CubicMetersPerMeterTolerance); + Assert.Equal(1, quantity00.CubicMetersPerMeter); Assert.Equal(VolumePerLengthUnit.CubicMeterPerMeter, quantity00.Unit); var quantity01 = VolumePerLength.From(1, VolumePerLengthUnit.CubicYardPerFoot); - AssertEx.EqualTolerance(1, quantity01.CubicYardsPerFoot, CubicYardsPerFootTolerance); + Assert.Equal(1, quantity01.CubicYardsPerFoot); Assert.Equal(VolumePerLengthUnit.CubicYardPerFoot, quantity01.Unit); var quantity02 = VolumePerLength.From(1, VolumePerLengthUnit.CubicYardPerUsSurveyFoot); - AssertEx.EqualTolerance(1, quantity02.CubicYardsPerUsSurveyFoot, CubicYardsPerUsSurveyFootTolerance); + Assert.Equal(1, quantity02.CubicYardsPerUsSurveyFoot); Assert.Equal(VolumePerLengthUnit.CubicYardPerUsSurveyFoot, quantity02.Unit); var quantity03 = VolumePerLength.From(1, VolumePerLengthUnit.ImperialGallonPerMile); - AssertEx.EqualTolerance(1, quantity03.ImperialGallonsPerMile, ImperialGallonsPerMileTolerance); + Assert.Equal(1, quantity03.ImperialGallonsPerMile); Assert.Equal(VolumePerLengthUnit.ImperialGallonPerMile, quantity03.Unit); var quantity04 = VolumePerLength.From(1, VolumePerLengthUnit.LiterPerKilometer); - AssertEx.EqualTolerance(1, quantity04.LitersPerKilometer, LitersPerKilometerTolerance); + Assert.Equal(1, quantity04.LitersPerKilometer); Assert.Equal(VolumePerLengthUnit.LiterPerKilometer, quantity04.Unit); var quantity05 = VolumePerLength.From(1, VolumePerLengthUnit.LiterPerMeter); - AssertEx.EqualTolerance(1, quantity05.LitersPerMeter, LitersPerMeterTolerance); + Assert.Equal(1, quantity05.LitersPerMeter); Assert.Equal(VolumePerLengthUnit.LiterPerMeter, quantity05.Unit); var quantity06 = VolumePerLength.From(1, VolumePerLengthUnit.LiterPerMillimeter); - AssertEx.EqualTolerance(1, quantity06.LitersPerMillimeter, LitersPerMillimeterTolerance); + Assert.Equal(1, quantity06.LitersPerMillimeter); Assert.Equal(VolumePerLengthUnit.LiterPerMillimeter, quantity06.Unit); var quantity07 = VolumePerLength.From(1, VolumePerLengthUnit.OilBarrelPerFoot); - AssertEx.EqualTolerance(1, quantity07.OilBarrelsPerFoot, OilBarrelsPerFootTolerance); + Assert.Equal(1, quantity07.OilBarrelsPerFoot); Assert.Equal(VolumePerLengthUnit.OilBarrelPerFoot, quantity07.Unit); var quantity08 = VolumePerLength.From(1, VolumePerLengthUnit.UsGallonPerMile); - AssertEx.EqualTolerance(1, quantity08.UsGallonsPerMile, UsGallonsPerMileTolerance); + Assert.Equal(1, quantity08.UsGallonsPerMile); Assert.Equal(VolumePerLengthUnit.UsGallonPerMile, quantity08.Unit); } @@ -347,131 +365,40 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 m³/m", VolumePerLengthUnit.CubicMeterPerMeter, 4.2)] + [InlineData("en-US", "4.2 yd³/ft", VolumePerLengthUnit.CubicYardPerFoot, 4.2)] + [InlineData("en-US", "4.2 yd³/ftUS", VolumePerLengthUnit.CubicYardPerUsSurveyFoot, 4.2)] + [InlineData("en-US", "4.2 gal (imp.)/mi", VolumePerLengthUnit.ImperialGallonPerMile, 4.2)] + [InlineData("en-US", "4.2 l/km", VolumePerLengthUnit.LiterPerKilometer, 4.2)] + [InlineData("en-US", "4.2 l/m", VolumePerLengthUnit.LiterPerMeter, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = VolumePerLength.Parse("1 m³/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicMetersPerMeter, CubicMetersPerMeterTolerance); - Assert.Equal(VolumePerLengthUnit.CubicMeterPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumePerLength.Parse("1 yd³/ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicYardsPerFoot, CubicYardsPerFootTolerance); - Assert.Equal(VolumePerLengthUnit.CubicYardPerFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumePerLength.Parse("1 yd³/ftUS", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicYardsPerUsSurveyFoot, CubicYardsPerUsSurveyFootTolerance); - Assert.Equal(VolumePerLengthUnit.CubicYardPerUsSurveyFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumePerLength.Parse("1 gal (imp.)/mi", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ImperialGallonsPerMile, ImperialGallonsPerMileTolerance); - Assert.Equal(VolumePerLengthUnit.ImperialGallonPerMile, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumePerLength.Parse("1 l/km", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.LitersPerKilometer, LitersPerKilometerTolerance); - Assert.Equal(VolumePerLengthUnit.LiterPerKilometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumePerLength.Parse("1 l/m", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.LitersPerMeter, LitersPerMeterTolerance); - Assert.Equal(VolumePerLengthUnit.LiterPerMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumePerLength.Parse("1 l/mm", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.LitersPerMillimeter, LitersPerMillimeterTolerance); - Assert.Equal(VolumePerLengthUnit.LiterPerMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumePerLength.Parse("1 bbl/ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.OilBarrelsPerFoot, OilBarrelsPerFootTolerance); - Assert.Equal(VolumePerLengthUnit.OilBarrelPerFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumePerLength.Parse("1 gal (U.S.)/mi", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.UsGallonsPerMile, UsGallonsPerMileTolerance); - Assert.Equal(VolumePerLengthUnit.UsGallonPerMile, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = VolumePerLength.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 m³/m", VolumePerLengthUnit.CubicMeterPerMeter, 4.2)] + [InlineData("en-US", "4.2 yd³/ft", VolumePerLengthUnit.CubicYardPerFoot, 4.2)] + [InlineData("en-US", "4.2 yd³/ftUS", VolumePerLengthUnit.CubicYardPerUsSurveyFoot, 4.2)] + [InlineData("en-US", "4.2 gal (imp.)/mi", VolumePerLengthUnit.ImperialGallonPerMile, 4.2)] + [InlineData("en-US", "4.2 l/km", VolumePerLengthUnit.LiterPerKilometer, 4.2)] + [InlineData("en-US", "4.2 l/m", VolumePerLengthUnit.LiterPerMeter, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(VolumePerLength.TryParse("1 m³/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicMetersPerMeter, CubicMetersPerMeterTolerance); - Assert.Equal(VolumePerLengthUnit.CubicMeterPerMeter, parsed.Unit); - } - - { - Assert.True(VolumePerLength.TryParse("1 yd³/ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicYardsPerFoot, CubicYardsPerFootTolerance); - Assert.Equal(VolumePerLengthUnit.CubicYardPerFoot, parsed.Unit); - } - - { - Assert.True(VolumePerLength.TryParse("1 yd³/ftUS", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicYardsPerUsSurveyFoot, CubicYardsPerUsSurveyFootTolerance); - Assert.Equal(VolumePerLengthUnit.CubicYardPerUsSurveyFoot, parsed.Unit); - } - - { - Assert.True(VolumePerLength.TryParse("1 gal (imp.)/mi", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ImperialGallonsPerMile, ImperialGallonsPerMileTolerance); - Assert.Equal(VolumePerLengthUnit.ImperialGallonPerMile, parsed.Unit); - } - - { - Assert.True(VolumePerLength.TryParse("1 l/km", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.LitersPerKilometer, LitersPerKilometerTolerance); - Assert.Equal(VolumePerLengthUnit.LiterPerKilometer, parsed.Unit); - } - - { - Assert.True(VolumePerLength.TryParse("1 l/m", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.LitersPerMeter, LitersPerMeterTolerance); - Assert.Equal(VolumePerLengthUnit.LiterPerMeter, parsed.Unit); - } - - { - Assert.True(VolumePerLength.TryParse("1 l/mm", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.LitersPerMillimeter, LitersPerMillimeterTolerance); - Assert.Equal(VolumePerLengthUnit.LiterPerMillimeter, parsed.Unit); - } - - { - Assert.True(VolumePerLength.TryParse("1 bbl/ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.OilBarrelsPerFoot, OilBarrelsPerFootTolerance); - Assert.Equal(VolumePerLengthUnit.OilBarrelPerFoot, parsed.Unit); - } - - { - Assert.True(VolumePerLength.TryParse("1 gal (U.S.)/mi", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UsGallonsPerMile, UsGallonsPerMileTolerance); - Assert.Equal(VolumePerLengthUnit.UsGallonPerMile, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(VolumePerLength.TryParse(quantityString, out VolumePerLength parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -612,6 +539,35 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Volume Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", VolumePerLengthUnit.CubicMeterPerMeter, "m³/m")] + [InlineData("en-US", VolumePerLengthUnit.CubicYardPerFoot, "yd³/ft")] + [InlineData("en-US", VolumePerLengthUnit.CubicYardPerUsSurveyFoot, "yd³/ftUS")] + [InlineData("en-US", VolumePerLengthUnit.ImperialGallonPerMile, "gal (imp.)/mi")] + [InlineData("en-US", VolumePerLengthUnit.LiterPerKilometer, "l/km")] + [InlineData("en-US", VolumePerLengthUnit.LiterPerMeter, "l/m")] + [InlineData("en-US", VolumePerLengthUnit.LiterPerMillimeter, "l/mm")] + [InlineData("en-US", VolumePerLengthUnit.OilBarrelPerFoot, "bbl/ft")] + [InlineData("en-US", VolumePerLengthUnit.UsGallonPerMile, "gal (U.S.)/mi")] + public void GetAbbreviationForCulture(string culture, VolumePerLengthUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = VolumePerLength.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(VolumePerLength.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = VolumePerLength.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(VolumePerLengthUnit unit) @@ -642,6 +598,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); }); } @@ -665,40 +622,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] @@ -744,8 +703,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); @@ -783,34 +740,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = VolumePerLength.FromCubicMetersPerMeter(1); - Assert.True(v.Equals(VolumePerLength.FromCubicMetersPerMeter(1), CubicMetersPerMeterTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(VolumePerLength.Zero, CubicMetersPerMeterTolerance, ComparisonType.Relative)); - Assert.True(VolumePerLength.FromCubicMetersPerMeter(100).Equals(VolumePerLength.FromCubicMetersPerMeter(120), 0.3, ComparisonType.Relative)); - Assert.False(VolumePerLength.FromCubicMetersPerMeter(100).Equals(VolumePerLength.FromCubicMetersPerMeter(120), 0.1, ComparisonType.Relative)); + VolumePerLength cubicmeterpermeter = VolumePerLength.FromCubicMetersPerMeter(1); + Assert.False(cubicmeterpermeter.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = VolumePerLength.FromCubicMetersPerMeter(1); - Assert.Throws(() => v.Equals(VolumePerLength.FromCubicMetersPerMeter(1), -1, ComparisonType.Relative)); + VolumePerLength cubicmeterpermeter = VolumePerLength.FromCubicMetersPerMeter(1); + Assert.False(cubicmeterpermeter.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - VolumePerLength cubicmeterpermeter = VolumePerLength.FromCubicMetersPerMeter(1); - Assert.False(cubicmeterpermeter.Equals(new object())); + var quantity = VolumePerLength.FromCubicMetersPerMeter(firstValue); + var otherQuantity = VolumePerLength.FromCubicMetersPerMeter(secondValue); + VolumePerLength maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - VolumePerLength cubicmeterpermeter = VolumePerLength.FromCubicMetersPerMeter(1); - Assert.False(cubicmeterpermeter.Equals(null)); + var quantity = VolumePerLength.FromCubicMetersPerMeter(1); + var negativeTolerance = VolumePerLength.FromCubicMetersPerMeter(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -829,6 +795,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() { @@ -903,158 +881,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(VolumePerLength))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(VolumePerLengthUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal(VolumePerLength.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal(VolumePerLength.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal(new {VolumePerLength.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 849af02b43..3a7c66f84b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeTestsBase.g.cs @@ -308,7 +308,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new Volume(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -321,15 +321,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void Volume_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + VolumeUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new Volume(1, VolumeUnit.CubicMeter); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(Volume.Zero, quantityInfo.Zero); Assert.Equal("Volume", quantityInfo.Name); + Assert.Equal(Volume.Zero, quantityInfo.Zero); + Assert.Equal(Volume.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(Volume.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void VolumeInfo_CreateWithCustomUnitInfos() + { + VolumeUnit[] expectedUnits = [VolumeUnit.CubicMeter]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -396,219 +414,219 @@ public void CubicMeterToVolumeUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = Volume.From(1, VolumeUnit.AcreFoot); - AssertEx.EqualTolerance(1, quantity00.AcreFeet, AcreFeetTolerance); + Assert.Equal(1, quantity00.AcreFeet); Assert.Equal(VolumeUnit.AcreFoot, quantity00.Unit); var quantity01 = Volume.From(1, VolumeUnit.AuTablespoon); - AssertEx.EqualTolerance(1, quantity01.AuTablespoons, AuTablespoonsTolerance); + Assert.Equal(1, quantity01.AuTablespoons); Assert.Equal(VolumeUnit.AuTablespoon, quantity01.Unit); var quantity02 = Volume.From(1, VolumeUnit.BoardFoot); - AssertEx.EqualTolerance(1, quantity02.BoardFeet, BoardFeetTolerance); + Assert.Equal(1, quantity02.BoardFeet); Assert.Equal(VolumeUnit.BoardFoot, quantity02.Unit); var quantity03 = Volume.From(1, VolumeUnit.Centiliter); - AssertEx.EqualTolerance(1, quantity03.Centiliters, CentilitersTolerance); + Assert.Equal(1, quantity03.Centiliters); Assert.Equal(VolumeUnit.Centiliter, quantity03.Unit); var quantity04 = Volume.From(1, VolumeUnit.CubicCentimeter); - AssertEx.EqualTolerance(1, quantity04.CubicCentimeters, CubicCentimetersTolerance); + Assert.Equal(1, quantity04.CubicCentimeters); Assert.Equal(VolumeUnit.CubicCentimeter, quantity04.Unit); var quantity05 = Volume.From(1, VolumeUnit.CubicDecimeter); - AssertEx.EqualTolerance(1, quantity05.CubicDecimeters, CubicDecimetersTolerance); + Assert.Equal(1, quantity05.CubicDecimeters); Assert.Equal(VolumeUnit.CubicDecimeter, quantity05.Unit); var quantity06 = Volume.From(1, VolumeUnit.CubicFoot); - AssertEx.EqualTolerance(1, quantity06.CubicFeet, CubicFeetTolerance); + Assert.Equal(1, quantity06.CubicFeet); Assert.Equal(VolumeUnit.CubicFoot, quantity06.Unit); var quantity07 = Volume.From(1, VolumeUnit.CubicHectometer); - AssertEx.EqualTolerance(1, quantity07.CubicHectometers, CubicHectometersTolerance); + Assert.Equal(1, quantity07.CubicHectometers); Assert.Equal(VolumeUnit.CubicHectometer, quantity07.Unit); var quantity08 = Volume.From(1, VolumeUnit.CubicInch); - AssertEx.EqualTolerance(1, quantity08.CubicInches, CubicInchesTolerance); + Assert.Equal(1, quantity08.CubicInches); Assert.Equal(VolumeUnit.CubicInch, quantity08.Unit); var quantity09 = Volume.From(1, VolumeUnit.CubicKilometer); - AssertEx.EqualTolerance(1, quantity09.CubicKilometers, CubicKilometersTolerance); + Assert.Equal(1, quantity09.CubicKilometers); Assert.Equal(VolumeUnit.CubicKilometer, quantity09.Unit); var quantity10 = Volume.From(1, VolumeUnit.CubicMeter); - AssertEx.EqualTolerance(1, quantity10.CubicMeters, CubicMetersTolerance); + Assert.Equal(1, quantity10.CubicMeters); Assert.Equal(VolumeUnit.CubicMeter, quantity10.Unit); var quantity11 = Volume.From(1, VolumeUnit.CubicMicrometer); - AssertEx.EqualTolerance(1, quantity11.CubicMicrometers, CubicMicrometersTolerance); + Assert.Equal(1, quantity11.CubicMicrometers); Assert.Equal(VolumeUnit.CubicMicrometer, quantity11.Unit); var quantity12 = Volume.From(1, VolumeUnit.CubicMile); - AssertEx.EqualTolerance(1, quantity12.CubicMiles, CubicMilesTolerance); + Assert.Equal(1, quantity12.CubicMiles); Assert.Equal(VolumeUnit.CubicMile, quantity12.Unit); var quantity13 = Volume.From(1, VolumeUnit.CubicMillimeter); - AssertEx.EqualTolerance(1, quantity13.CubicMillimeters, CubicMillimetersTolerance); + Assert.Equal(1, quantity13.CubicMillimeters); Assert.Equal(VolumeUnit.CubicMillimeter, quantity13.Unit); var quantity14 = Volume.From(1, VolumeUnit.CubicYard); - AssertEx.EqualTolerance(1, quantity14.CubicYards, CubicYardsTolerance); + Assert.Equal(1, quantity14.CubicYards); Assert.Equal(VolumeUnit.CubicYard, quantity14.Unit); var quantity15 = Volume.From(1, VolumeUnit.Decaliter); - AssertEx.EqualTolerance(1, quantity15.Decaliters, DecalitersTolerance); + Assert.Equal(1, quantity15.Decaliters); Assert.Equal(VolumeUnit.Decaliter, quantity15.Unit); var quantity16 = Volume.From(1, VolumeUnit.DecausGallon); - AssertEx.EqualTolerance(1, quantity16.DecausGallons, DecausGallonsTolerance); + Assert.Equal(1, quantity16.DecausGallons); Assert.Equal(VolumeUnit.DecausGallon, quantity16.Unit); var quantity17 = Volume.From(1, VolumeUnit.Deciliter); - AssertEx.EqualTolerance(1, quantity17.Deciliters, DecilitersTolerance); + Assert.Equal(1, quantity17.Deciliters); Assert.Equal(VolumeUnit.Deciliter, quantity17.Unit); var quantity18 = Volume.From(1, VolumeUnit.DeciusGallon); - AssertEx.EqualTolerance(1, quantity18.DeciusGallons, DeciusGallonsTolerance); + Assert.Equal(1, quantity18.DeciusGallons); Assert.Equal(VolumeUnit.DeciusGallon, quantity18.Unit); var quantity19 = Volume.From(1, VolumeUnit.HectocubicFoot); - AssertEx.EqualTolerance(1, quantity19.HectocubicFeet, HectocubicFeetTolerance); + Assert.Equal(1, quantity19.HectocubicFeet); Assert.Equal(VolumeUnit.HectocubicFoot, quantity19.Unit); var quantity20 = Volume.From(1, VolumeUnit.HectocubicMeter); - AssertEx.EqualTolerance(1, quantity20.HectocubicMeters, HectocubicMetersTolerance); + Assert.Equal(1, quantity20.HectocubicMeters); Assert.Equal(VolumeUnit.HectocubicMeter, quantity20.Unit); var quantity21 = Volume.From(1, VolumeUnit.Hectoliter); - AssertEx.EqualTolerance(1, quantity21.Hectoliters, HectolitersTolerance); + Assert.Equal(1, quantity21.Hectoliters); Assert.Equal(VolumeUnit.Hectoliter, quantity21.Unit); var quantity22 = Volume.From(1, VolumeUnit.HectousGallon); - AssertEx.EqualTolerance(1, quantity22.HectousGallons, HectousGallonsTolerance); + Assert.Equal(1, quantity22.HectousGallons); Assert.Equal(VolumeUnit.HectousGallon, quantity22.Unit); var quantity23 = Volume.From(1, VolumeUnit.ImperialBeerBarrel); - AssertEx.EqualTolerance(1, quantity23.ImperialBeerBarrels, ImperialBeerBarrelsTolerance); + Assert.Equal(1, quantity23.ImperialBeerBarrels); Assert.Equal(VolumeUnit.ImperialBeerBarrel, quantity23.Unit); var quantity24 = Volume.From(1, VolumeUnit.ImperialGallon); - AssertEx.EqualTolerance(1, quantity24.ImperialGallons, ImperialGallonsTolerance); + Assert.Equal(1, quantity24.ImperialGallons); Assert.Equal(VolumeUnit.ImperialGallon, quantity24.Unit); var quantity25 = Volume.From(1, VolumeUnit.ImperialOunce); - AssertEx.EqualTolerance(1, quantity25.ImperialOunces, ImperialOuncesTolerance); + Assert.Equal(1, quantity25.ImperialOunces); Assert.Equal(VolumeUnit.ImperialOunce, quantity25.Unit); var quantity26 = Volume.From(1, VolumeUnit.ImperialPint); - AssertEx.EqualTolerance(1, quantity26.ImperialPints, ImperialPintsTolerance); + Assert.Equal(1, quantity26.ImperialPints); Assert.Equal(VolumeUnit.ImperialPint, quantity26.Unit); var quantity27 = Volume.From(1, VolumeUnit.ImperialQuart); - AssertEx.EqualTolerance(1, quantity27.ImperialQuarts, ImperialQuartsTolerance); + Assert.Equal(1, quantity27.ImperialQuarts); Assert.Equal(VolumeUnit.ImperialQuart, quantity27.Unit); var quantity28 = Volume.From(1, VolumeUnit.KilocubicFoot); - AssertEx.EqualTolerance(1, quantity28.KilocubicFeet, KilocubicFeetTolerance); + Assert.Equal(1, quantity28.KilocubicFeet); Assert.Equal(VolumeUnit.KilocubicFoot, quantity28.Unit); var quantity29 = Volume.From(1, VolumeUnit.KilocubicMeter); - AssertEx.EqualTolerance(1, quantity29.KilocubicMeters, KilocubicMetersTolerance); + Assert.Equal(1, quantity29.KilocubicMeters); Assert.Equal(VolumeUnit.KilocubicMeter, quantity29.Unit); var quantity30 = Volume.From(1, VolumeUnit.KiloimperialGallon); - AssertEx.EqualTolerance(1, quantity30.KiloimperialGallons, KiloimperialGallonsTolerance); + Assert.Equal(1, quantity30.KiloimperialGallons); Assert.Equal(VolumeUnit.KiloimperialGallon, quantity30.Unit); var quantity31 = Volume.From(1, VolumeUnit.Kiloliter); - AssertEx.EqualTolerance(1, quantity31.Kiloliters, KilolitersTolerance); + Assert.Equal(1, quantity31.Kiloliters); Assert.Equal(VolumeUnit.Kiloliter, quantity31.Unit); var quantity32 = Volume.From(1, VolumeUnit.KilousGallon); - AssertEx.EqualTolerance(1, quantity32.KilousGallons, KilousGallonsTolerance); + Assert.Equal(1, quantity32.KilousGallons); Assert.Equal(VolumeUnit.KilousGallon, quantity32.Unit); var quantity33 = Volume.From(1, VolumeUnit.Liter); - AssertEx.EqualTolerance(1, quantity33.Liters, LitersTolerance); + Assert.Equal(1, quantity33.Liters); Assert.Equal(VolumeUnit.Liter, quantity33.Unit); var quantity34 = Volume.From(1, VolumeUnit.MegacubicFoot); - AssertEx.EqualTolerance(1, quantity34.MegacubicFeet, MegacubicFeetTolerance); + Assert.Equal(1, quantity34.MegacubicFeet); Assert.Equal(VolumeUnit.MegacubicFoot, quantity34.Unit); var quantity35 = Volume.From(1, VolumeUnit.MegaimperialGallon); - AssertEx.EqualTolerance(1, quantity35.MegaimperialGallons, MegaimperialGallonsTolerance); + Assert.Equal(1, quantity35.MegaimperialGallons); Assert.Equal(VolumeUnit.MegaimperialGallon, quantity35.Unit); var quantity36 = Volume.From(1, VolumeUnit.Megaliter); - AssertEx.EqualTolerance(1, quantity36.Megaliters, MegalitersTolerance); + Assert.Equal(1, quantity36.Megaliters); Assert.Equal(VolumeUnit.Megaliter, quantity36.Unit); var quantity37 = Volume.From(1, VolumeUnit.MegausGallon); - AssertEx.EqualTolerance(1, quantity37.MegausGallons, MegausGallonsTolerance); + Assert.Equal(1, quantity37.MegausGallons); Assert.Equal(VolumeUnit.MegausGallon, quantity37.Unit); var quantity38 = Volume.From(1, VolumeUnit.MetricCup); - AssertEx.EqualTolerance(1, quantity38.MetricCups, MetricCupsTolerance); + Assert.Equal(1, quantity38.MetricCups); Assert.Equal(VolumeUnit.MetricCup, quantity38.Unit); var quantity39 = Volume.From(1, VolumeUnit.MetricTeaspoon); - AssertEx.EqualTolerance(1, quantity39.MetricTeaspoons, MetricTeaspoonsTolerance); + Assert.Equal(1, quantity39.MetricTeaspoons); Assert.Equal(VolumeUnit.MetricTeaspoon, quantity39.Unit); var quantity40 = Volume.From(1, VolumeUnit.Microliter); - AssertEx.EqualTolerance(1, quantity40.Microliters, MicrolitersTolerance); + Assert.Equal(1, quantity40.Microliters); Assert.Equal(VolumeUnit.Microliter, quantity40.Unit); var quantity41 = Volume.From(1, VolumeUnit.Milliliter); - AssertEx.EqualTolerance(1, quantity41.Milliliters, MillilitersTolerance); + Assert.Equal(1, quantity41.Milliliters); Assert.Equal(VolumeUnit.Milliliter, quantity41.Unit); var quantity42 = Volume.From(1, VolumeUnit.Nanoliter); - AssertEx.EqualTolerance(1, quantity42.Nanoliters, NanolitersTolerance); + Assert.Equal(1, quantity42.Nanoliters); Assert.Equal(VolumeUnit.Nanoliter, quantity42.Unit); var quantity43 = Volume.From(1, VolumeUnit.OilBarrel); - AssertEx.EqualTolerance(1, quantity43.OilBarrels, OilBarrelsTolerance); + Assert.Equal(1, quantity43.OilBarrels); Assert.Equal(VolumeUnit.OilBarrel, quantity43.Unit); var quantity44 = Volume.From(1, VolumeUnit.UkTablespoon); - AssertEx.EqualTolerance(1, quantity44.UkTablespoons, UkTablespoonsTolerance); + Assert.Equal(1, quantity44.UkTablespoons); Assert.Equal(VolumeUnit.UkTablespoon, quantity44.Unit); var quantity45 = Volume.From(1, VolumeUnit.UsBeerBarrel); - AssertEx.EqualTolerance(1, quantity45.UsBeerBarrels, UsBeerBarrelsTolerance); + Assert.Equal(1, quantity45.UsBeerBarrels); Assert.Equal(VolumeUnit.UsBeerBarrel, quantity45.Unit); var quantity46 = Volume.From(1, VolumeUnit.UsCustomaryCup); - AssertEx.EqualTolerance(1, quantity46.UsCustomaryCups, UsCustomaryCupsTolerance); + Assert.Equal(1, quantity46.UsCustomaryCups); Assert.Equal(VolumeUnit.UsCustomaryCup, quantity46.Unit); var quantity47 = Volume.From(1, VolumeUnit.UsGallon); - AssertEx.EqualTolerance(1, quantity47.UsGallons, UsGallonsTolerance); + Assert.Equal(1, quantity47.UsGallons); Assert.Equal(VolumeUnit.UsGallon, quantity47.Unit); var quantity48 = Volume.From(1, VolumeUnit.UsLegalCup); - AssertEx.EqualTolerance(1, quantity48.UsLegalCups, UsLegalCupsTolerance); + Assert.Equal(1, quantity48.UsLegalCups); Assert.Equal(VolumeUnit.UsLegalCup, quantity48.Unit); var quantity49 = Volume.From(1, VolumeUnit.UsOunce); - AssertEx.EqualTolerance(1, quantity49.UsOunces, UsOuncesTolerance); + Assert.Equal(1, quantity49.UsOunces); Assert.Equal(VolumeUnit.UsOunce, quantity49.Unit); var quantity50 = Volume.From(1, VolumeUnit.UsPint); - AssertEx.EqualTolerance(1, quantity50.UsPints, UsPintsTolerance); + Assert.Equal(1, quantity50.UsPints); Assert.Equal(VolumeUnit.UsPint, quantity50.Unit); var quantity51 = Volume.From(1, VolumeUnit.UsQuart); - AssertEx.EqualTolerance(1, quantity51.UsQuarts, UsQuartsTolerance); + Assert.Equal(1, quantity51.UsQuarts); Assert.Equal(VolumeUnit.UsQuart, quantity51.Unit); var quantity52 = Volume.From(1, VolumeUnit.UsTablespoon); - AssertEx.EqualTolerance(1, quantity52.UsTablespoons, UsTablespoonsTolerance); + Assert.Equal(1, quantity52.UsTablespoons); Assert.Equal(VolumeUnit.UsTablespoon, quantity52.Unit); var quantity53 = Volume.From(1, VolumeUnit.UsTeaspoon); - AssertEx.EqualTolerance(1, quantity53.UsTeaspoons, UsTeaspoonsTolerance); + Assert.Equal(1, quantity53.UsTeaspoons); Assert.Equal(VolumeUnit.UsTeaspoon, quantity53.Unit); } @@ -706,1450 +724,335 @@ public virtual void As_UnitSystem_SI_ReturnsQuantityInSIUnits() var convertedValue = quantity.As(UnitSystem.SI); - Assert.Equal(expectedValue, convertedValue); - } - - [Fact] - public void As_UnitSystem_ThrowsArgumentNullExceptionIfNull() - { - var quantity = new Volume(value: 1, unit: Volume.BaseUnit); - UnitSystem nullUnitSystem = null!; - Assert.Throws(() => quantity.As(nullUnitSystem)); - } - - [Fact] - public void As_UnitSystem_ThrowsArgumentExceptionIfNotSupported() - { - var quantity = new Volume(value: 1, unit: Volume.BaseUnit); - var unsupportedUnitSystem = new UnitSystem(UnsupportedBaseUnits); - Assert.Throws(() => quantity.As(unsupportedUnitSystem)); - } - - [Fact] - public virtual void ToUnit_UnitSystem_SI_ReturnsQuantityInSIUnits() - { - var quantity = new Volume(value: 1, unit: Volume.BaseUnit); - var expectedUnit = Volume.Info.GetDefaultUnit(UnitSystem.SI); - var expectedValue = quantity.As(expectedUnit); - - Assert.Multiple(() => - { - Volume quantityToConvert = quantity; - - Volume convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); - - Assert.Equal(expectedUnit, convertedQuantity.Unit); - Assert.Equal(expectedValue, convertedQuantity.Value); - }, () => - { - IQuantity quantityToConvert = quantity; - - IQuantity convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); - - Assert.Equal(expectedUnit, convertedQuantity.Unit); - Assert.Equal(expectedValue, convertedQuantity.Value); - }, () => - { - IQuantity quantityToConvert = quantity; - - IQuantity convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); - - Assert.Equal(expectedUnit, convertedQuantity.Unit); - Assert.Equal(expectedValue, convertedQuantity.Value); - }); - } - - [Fact] - public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() - { - UnitSystem nullUnitSystem = null!; - Assert.Multiple(() => - { - var quantity = new Volume(value: 1, unit: Volume.BaseUnit); - Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); - }, () => - { - IQuantity quantity = new Volume(value: 1, unit: Volume.BaseUnit); - Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); - }, () => - { - IQuantity quantity = new Volume(value: 1, unit: Volume.BaseUnit); - Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); - }); - } - - [Fact] - public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() - { - var unsupportedUnitSystem = new UnitSystem(UnsupportedBaseUnits); - Assert.Multiple(() => - { - var quantity = new Volume(value: 1, unit: Volume.BaseUnit); - Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); - }, () => - { - IQuantity quantity = new Volume(value: 1, unit: Volume.BaseUnit); - Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); - }, () => - { - IQuantity quantity = new Volume(value: 1, unit: Volume.BaseUnit); - Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); - }); - } - - [Fact] - public void Parse() - { - try - { - var parsed = Volume.Parse("1 ac-ft", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.AcreFeet, AcreFeetTolerance); - Assert.Equal(VolumeUnit.AcreFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 acre-foot", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.AcreFeet, AcreFeetTolerance); - Assert.Equal(VolumeUnit.AcreFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 acre-feet", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.AcreFeet, AcreFeetTolerance); - Assert.Equal(VolumeUnit.AcreFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 tablespoon (A.U.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.AuTablespoons, AuTablespoonsTolerance); - Assert.Equal(VolumeUnit.AuTablespoon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 bf", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.BoardFeet, BoardFeetTolerance); - Assert.Equal(VolumeUnit.BoardFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 board foot", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.BoardFeet, BoardFeetTolerance); - Assert.Equal(VolumeUnit.BoardFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 board feet", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.BoardFeet, BoardFeetTolerance); - Assert.Equal(VolumeUnit.BoardFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 pmp", CultureInfo.GetCultureInfo("fr-CA")); - AssertEx.EqualTolerance(1, parsed.BoardFeet, BoardFeetTolerance); - Assert.Equal(VolumeUnit.BoardFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 pied-planche", CultureInfo.GetCultureInfo("fr-CA")); - AssertEx.EqualTolerance(1, parsed.BoardFeet, BoardFeetTolerance); - Assert.Equal(VolumeUnit.BoardFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 pied de planche", CultureInfo.GetCultureInfo("fr-CA")); - AssertEx.EqualTolerance(1, parsed.BoardFeet, BoardFeetTolerance); - Assert.Equal(VolumeUnit.BoardFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 cl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Centiliters, CentilitersTolerance); - Assert.Equal(VolumeUnit.Centiliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 сл", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Centiliters, CentilitersTolerance); - Assert.Equal(VolumeUnit.Centiliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 cm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicCentimeters, CubicCentimetersTolerance); - Assert.Equal(VolumeUnit.CubicCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 см³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CubicCentimeters, CubicCentimetersTolerance); - Assert.Equal(VolumeUnit.CubicCentimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 dm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicDecimeters, CubicDecimetersTolerance); - Assert.Equal(VolumeUnit.CubicDecimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 дм³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CubicDecimeters, CubicDecimetersTolerance); - Assert.Equal(VolumeUnit.CubicDecimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 ft³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicFeet, CubicFeetTolerance); - Assert.Equal(VolumeUnit.CubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 фут³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CubicFeet, CubicFeetTolerance); - Assert.Equal(VolumeUnit.CubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 hm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicHectometers, CubicHectometersTolerance); - Assert.Equal(VolumeUnit.CubicHectometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 гм³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CubicHectometers, CubicHectometersTolerance); - Assert.Equal(VolumeUnit.CubicHectometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 in³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicInches, CubicInchesTolerance); - Assert.Equal(VolumeUnit.CubicInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 дюйм³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CubicInches, CubicInchesTolerance); - Assert.Equal(VolumeUnit.CubicInch, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 km³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicKilometers, CubicKilometersTolerance); - Assert.Equal(VolumeUnit.CubicKilometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 км³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CubicKilometers, CubicKilometersTolerance); - Assert.Equal(VolumeUnit.CubicKilometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 m³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicMeters, CubicMetersTolerance); - Assert.Equal(VolumeUnit.CubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 м³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CubicMeters, CubicMetersTolerance); - Assert.Equal(VolumeUnit.CubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 µm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicMicrometers, CubicMicrometersTolerance); - Assert.Equal(VolumeUnit.CubicMicrometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 мкм³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CubicMicrometers, CubicMicrometersTolerance); - Assert.Equal(VolumeUnit.CubicMicrometer, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 mi³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicMiles, CubicMilesTolerance); - Assert.Equal(VolumeUnit.CubicMile, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 миля³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CubicMiles, CubicMilesTolerance); - Assert.Equal(VolumeUnit.CubicMile, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 mm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicMillimeters, CubicMillimetersTolerance); - Assert.Equal(VolumeUnit.CubicMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 мм³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CubicMillimeters, CubicMillimetersTolerance); - Assert.Equal(VolumeUnit.CubicMillimeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 yd³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CubicYards, CubicYardsTolerance); - Assert.Equal(VolumeUnit.CubicYard, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 ярд³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.CubicYards, CubicYardsTolerance); - Assert.Equal(VolumeUnit.CubicYard, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 dal", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Decaliters, DecalitersTolerance); - Assert.Equal(VolumeUnit.Decaliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 дал", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Decaliters, DecalitersTolerance); - Assert.Equal(VolumeUnit.Decaliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 dagal (U.S.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecausGallons, DecausGallonsTolerance); - Assert.Equal(VolumeUnit.DecausGallon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 даАмериканский галлон", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.DecausGallons, DecausGallonsTolerance); - Assert.Equal(VolumeUnit.DecausGallon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 dl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Deciliters, DecilitersTolerance); - Assert.Equal(VolumeUnit.Deciliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 дл", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Deciliters, DecilitersTolerance); - Assert.Equal(VolumeUnit.Deciliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 dgal (U.S.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DeciusGallons, DeciusGallonsTolerance); - Assert.Equal(VolumeUnit.DeciusGallon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 дАмериканский галлон", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.DeciusGallons, DeciusGallonsTolerance); - Assert.Equal(VolumeUnit.DeciusGallon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 hft³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.HectocubicFeet, HectocubicFeetTolerance); - Assert.Equal(VolumeUnit.HectocubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 гфут³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.HectocubicFeet, HectocubicFeetTolerance); - Assert.Equal(VolumeUnit.HectocubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 hm³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.HectocubicMeters, HectocubicMetersTolerance); - Assert.Equal(VolumeUnit.HectocubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 гм³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.HectocubicMeters, HectocubicMetersTolerance); - Assert.Equal(VolumeUnit.HectocubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 hl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Hectoliters, HectolitersTolerance); - Assert.Equal(VolumeUnit.Hectoliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 гл", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Hectoliters, HectolitersTolerance); - Assert.Equal(VolumeUnit.Hectoliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 hgal (U.S.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.HectousGallons, HectousGallonsTolerance); - Assert.Equal(VolumeUnit.HectousGallon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 гАмериканский галлон", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.HectousGallons, HectousGallonsTolerance); - Assert.Equal(VolumeUnit.HectousGallon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 bl (imp.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ImperialBeerBarrels, ImperialBeerBarrelsTolerance); - Assert.Equal(VolumeUnit.ImperialBeerBarrel, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 gal (imp.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ImperialGallons, ImperialGallonsTolerance); - Assert.Equal(VolumeUnit.ImperialGallon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 Английский галлон", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.ImperialGallons, ImperialGallonsTolerance); - Assert.Equal(VolumeUnit.ImperialGallon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 oz (imp.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ImperialOunces, ImperialOuncesTolerance); - Assert.Equal(VolumeUnit.ImperialOunce, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 Английская унция", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.ImperialOunces, ImperialOuncesTolerance); - Assert.Equal(VolumeUnit.ImperialOunce, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 pt (imp.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ImperialPints, ImperialPintsTolerance); - Assert.Equal(VolumeUnit.ImperialPint, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 UK pt", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ImperialPints, ImperialPintsTolerance); - Assert.Equal(VolumeUnit.ImperialPint, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 pt", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ImperialPints, ImperialPintsTolerance); - Assert.Equal(VolumeUnit.ImperialPint, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 p", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ImperialPints, ImperialPintsTolerance); - Assert.Equal(VolumeUnit.ImperialPint, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 qt (imp.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.ImperialQuarts, ImperialQuartsTolerance); - Assert.Equal(VolumeUnit.ImperialQuart, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 kft³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilocubicFeet, KilocubicFeetTolerance); - Assert.Equal(VolumeUnit.KilocubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 кфут³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilocubicFeet, KilocubicFeetTolerance); - Assert.Equal(VolumeUnit.KilocubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 km³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilocubicMeters, KilocubicMetersTolerance); - Assert.Equal(VolumeUnit.KilocubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 км³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilocubicMeters, KilocubicMetersTolerance); - Assert.Equal(VolumeUnit.KilocubicMeter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 kgal (imp.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KiloimperialGallons, KiloimperialGallonsTolerance); - Assert.Equal(VolumeUnit.KiloimperialGallon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 кАнглийский галлон", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KiloimperialGallons, KiloimperialGallonsTolerance); - Assert.Equal(VolumeUnit.KiloimperialGallon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 kl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Kiloliters, KilolitersTolerance); - Assert.Equal(VolumeUnit.Kiloliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 кл", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Kiloliters, KilolitersTolerance); - Assert.Equal(VolumeUnit.Kiloliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 kgal (U.S.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilousGallons, KilousGallonsTolerance); - Assert.Equal(VolumeUnit.KilousGallon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 кАмериканский галлон", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.KilousGallons, KilousGallonsTolerance); - Assert.Equal(VolumeUnit.KilousGallon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 l", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Liters, LitersTolerance); - Assert.Equal(VolumeUnit.Liter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 л", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Liters, LitersTolerance); - Assert.Equal(VolumeUnit.Liter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 Mft³", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegacubicFeet, MegacubicFeetTolerance); - Assert.Equal(VolumeUnit.MegacubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 Мфут³", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MegacubicFeet, MegacubicFeetTolerance); - Assert.Equal(VolumeUnit.MegacubicFoot, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 Mgal (imp.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegaimperialGallons, MegaimperialGallonsTolerance); - Assert.Equal(VolumeUnit.MegaimperialGallon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 МАнглийский галлон", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MegaimperialGallons, MegaimperialGallonsTolerance); - Assert.Equal(VolumeUnit.MegaimperialGallon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 Ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Megaliters, MegalitersTolerance); - Assert.Equal(VolumeUnit.Megaliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 Мл", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Megaliters, MegalitersTolerance); - Assert.Equal(VolumeUnit.Megaliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 Mgal (U.S.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegausGallons, MegausGallonsTolerance); - Assert.Equal(VolumeUnit.MegausGallon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 МАмериканский галлон", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.MegausGallons, MegausGallonsTolerance); - Assert.Equal(VolumeUnit.MegausGallon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 metric cup", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MetricCups, MetricCupsTolerance); - Assert.Equal(VolumeUnit.MetricCup, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 tsp", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MetricTeaspoons, MetricTeaspoonsTolerance); - Assert.Equal(VolumeUnit.MetricTeaspoon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 t", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MetricTeaspoons, MetricTeaspoonsTolerance); - Assert.Equal(VolumeUnit.MetricTeaspoon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 ts", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MetricTeaspoons, MetricTeaspoonsTolerance); - Assert.Equal(VolumeUnit.MetricTeaspoon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 tspn", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MetricTeaspoons, MetricTeaspoonsTolerance); - Assert.Equal(VolumeUnit.MetricTeaspoon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 t.", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MetricTeaspoons, MetricTeaspoonsTolerance); - Assert.Equal(VolumeUnit.MetricTeaspoon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 ts.", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MetricTeaspoons, MetricTeaspoonsTolerance); - Assert.Equal(VolumeUnit.MetricTeaspoon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 tsp.", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MetricTeaspoons, MetricTeaspoonsTolerance); - Assert.Equal(VolumeUnit.MetricTeaspoon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 tspn.", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MetricTeaspoons, MetricTeaspoonsTolerance); - Assert.Equal(VolumeUnit.MetricTeaspoon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 teaspoon", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MetricTeaspoons, MetricTeaspoonsTolerance); - Assert.Equal(VolumeUnit.MetricTeaspoon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 µl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Microliters, MicrolitersTolerance); - Assert.Equal(VolumeUnit.Microliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 мкл", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Microliters, MicrolitersTolerance); - Assert.Equal(VolumeUnit.Microliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 ml", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Milliliters, MillilitersTolerance); - Assert.Equal(VolumeUnit.Milliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 мл", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Milliliters, MillilitersTolerance); - Assert.Equal(VolumeUnit.Milliliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 nl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.Nanoliters, NanolitersTolerance); - Assert.Equal(VolumeUnit.Nanoliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 нл", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.Nanoliters, NanolitersTolerance); - Assert.Equal(VolumeUnit.Nanoliter, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 bbl", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.OilBarrels, OilBarrelsTolerance); - Assert.Equal(VolumeUnit.OilBarrel, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 tablespoon (U.K.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.UkTablespoons, UkTablespoonsTolerance); - Assert.Equal(VolumeUnit.UkTablespoon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 bl (U.S.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.UsBeerBarrels, UsBeerBarrelsTolerance); - Assert.Equal(VolumeUnit.UsBeerBarrel, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 cup (U.S. customary)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.UsCustomaryCups, UsCustomaryCupsTolerance); - Assert.Equal(VolumeUnit.UsCustomaryCup, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 gal (U.S.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.UsGallons, UsGallonsTolerance); - Assert.Equal(VolumeUnit.UsGallon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 Американский галлон", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.UsGallons, UsGallonsTolerance); - Assert.Equal(VolumeUnit.UsGallon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 cup (U.S.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.UsLegalCups, UsLegalCupsTolerance); - Assert.Equal(VolumeUnit.UsLegalCup, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 oz (U.S.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.UsOunces, UsOuncesTolerance); - Assert.Equal(VolumeUnit.UsOunce, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 Американская унция", CultureInfo.GetCultureInfo("ru-RU")); - AssertEx.EqualTolerance(1, parsed.UsOunces, UsOuncesTolerance); - Assert.Equal(VolumeUnit.UsOunce, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 pt (U.S.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.UsPints, UsPintsTolerance); - Assert.Equal(VolumeUnit.UsPint, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 qt (U.S.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.UsQuarts, UsQuartsTolerance); - Assert.Equal(VolumeUnit.UsQuart, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 tablespoon (U.S.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.UsTablespoons, UsTablespoonsTolerance); - Assert.Equal(VolumeUnit.UsTablespoon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = Volume.Parse("1 teaspoon (U.S.)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.UsTeaspoons, UsTeaspoonsTolerance); - Assert.Equal(VolumeUnit.UsTeaspoon, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - } - - [Fact] - public void TryParse() - { - { - Assert.True(Volume.TryParse("1 ac-ft", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.AcreFeet, AcreFeetTolerance); - Assert.Equal(VolumeUnit.AcreFoot, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 acre-foot", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.AcreFeet, AcreFeetTolerance); - Assert.Equal(VolumeUnit.AcreFoot, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 acre-feet", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.AcreFeet, AcreFeetTolerance); - Assert.Equal(VolumeUnit.AcreFoot, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 tablespoon (A.U.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.AuTablespoons, AuTablespoonsTolerance); - Assert.Equal(VolumeUnit.AuTablespoon, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 bf", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BoardFeet, BoardFeetTolerance); - Assert.Equal(VolumeUnit.BoardFoot, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 board foot", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BoardFeet, BoardFeetTolerance); - Assert.Equal(VolumeUnit.BoardFoot, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 board feet", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BoardFeet, BoardFeetTolerance); - Assert.Equal(VolumeUnit.BoardFoot, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 pmp", CultureInfo.GetCultureInfo("fr-CA"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BoardFeet, BoardFeetTolerance); - Assert.Equal(VolumeUnit.BoardFoot, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 pied-planche", CultureInfo.GetCultureInfo("fr-CA"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BoardFeet, BoardFeetTolerance); - Assert.Equal(VolumeUnit.BoardFoot, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 pied de planche", CultureInfo.GetCultureInfo("fr-CA"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BoardFeet, BoardFeetTolerance); - Assert.Equal(VolumeUnit.BoardFoot, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 cl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Centiliters, CentilitersTolerance); - Assert.Equal(VolumeUnit.Centiliter, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 сл", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Centiliters, CentilitersTolerance); - Assert.Equal(VolumeUnit.Centiliter, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 cm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicCentimeters, CubicCentimetersTolerance); - Assert.Equal(VolumeUnit.CubicCentimeter, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 см³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicCentimeters, CubicCentimetersTolerance); - Assert.Equal(VolumeUnit.CubicCentimeter, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 dm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicDecimeters, CubicDecimetersTolerance); - Assert.Equal(VolumeUnit.CubicDecimeter, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 дм³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicDecimeters, CubicDecimetersTolerance); - Assert.Equal(VolumeUnit.CubicDecimeter, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 ft³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicFeet, CubicFeetTolerance); - Assert.Equal(VolumeUnit.CubicFoot, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 фут³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicFeet, CubicFeetTolerance); - Assert.Equal(VolumeUnit.CubicFoot, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 in³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicInches, CubicInchesTolerance); - Assert.Equal(VolumeUnit.CubicInch, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 дюйм³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicInches, CubicInchesTolerance); - Assert.Equal(VolumeUnit.CubicInch, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 m³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicMeters, CubicMetersTolerance); - Assert.Equal(VolumeUnit.CubicMeter, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 м³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicMeters, CubicMetersTolerance); - Assert.Equal(VolumeUnit.CubicMeter, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 µm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicMicrometers, CubicMicrometersTolerance); - Assert.Equal(VolumeUnit.CubicMicrometer, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 мкм³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicMicrometers, CubicMicrometersTolerance); - Assert.Equal(VolumeUnit.CubicMicrometer, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 mi³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicMiles, CubicMilesTolerance); - Assert.Equal(VolumeUnit.CubicMile, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 миля³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicMiles, CubicMilesTolerance); - Assert.Equal(VolumeUnit.CubicMile, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 mm³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicMillimeters, CubicMillimetersTolerance); - Assert.Equal(VolumeUnit.CubicMillimeter, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 мм³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicMillimeters, CubicMillimetersTolerance); - Assert.Equal(VolumeUnit.CubicMillimeter, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 yd³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicYards, CubicYardsTolerance); - Assert.Equal(VolumeUnit.CubicYard, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 ярд³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CubicYards, CubicYardsTolerance); - Assert.Equal(VolumeUnit.CubicYard, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 dal", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Decaliters, DecalitersTolerance); - Assert.Equal(VolumeUnit.Decaliter, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 дал", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Decaliters, DecalitersTolerance); - Assert.Equal(VolumeUnit.Decaliter, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 dagal (U.S.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecausGallons, DecausGallonsTolerance); - Assert.Equal(VolumeUnit.DecausGallon, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 даАмериканский галлон", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecausGallons, DecausGallonsTolerance); - Assert.Equal(VolumeUnit.DecausGallon, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 dl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Deciliters, DecilitersTolerance); - Assert.Equal(VolumeUnit.Deciliter, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 дл", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Deciliters, DecilitersTolerance); - Assert.Equal(VolumeUnit.Deciliter, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 dgal (U.S.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DeciusGallons, DeciusGallonsTolerance); - Assert.Equal(VolumeUnit.DeciusGallon, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 дАмериканский галлон", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DeciusGallons, DeciusGallonsTolerance); - Assert.Equal(VolumeUnit.DeciusGallon, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 hft³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HectocubicFeet, HectocubicFeetTolerance); - Assert.Equal(VolumeUnit.HectocubicFoot, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 гфут³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HectocubicFeet, HectocubicFeetTolerance); - Assert.Equal(VolumeUnit.HectocubicFoot, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 hl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Hectoliters, HectolitersTolerance); - Assert.Equal(VolumeUnit.Hectoliter, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 гл", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Hectoliters, HectolitersTolerance); - Assert.Equal(VolumeUnit.Hectoliter, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 hgal (U.S.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HectousGallons, HectousGallonsTolerance); - Assert.Equal(VolumeUnit.HectousGallon, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 гАмериканский галлон", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.HectousGallons, HectousGallonsTolerance); - Assert.Equal(VolumeUnit.HectousGallon, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 bl (imp.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ImperialBeerBarrels, ImperialBeerBarrelsTolerance); - Assert.Equal(VolumeUnit.ImperialBeerBarrel, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 gal (imp.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ImperialGallons, ImperialGallonsTolerance); - Assert.Equal(VolumeUnit.ImperialGallon, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 Английский галлон", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ImperialGallons, ImperialGallonsTolerance); - Assert.Equal(VolumeUnit.ImperialGallon, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 oz (imp.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ImperialOunces, ImperialOuncesTolerance); - Assert.Equal(VolumeUnit.ImperialOunce, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 Английская унция", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ImperialOunces, ImperialOuncesTolerance); - Assert.Equal(VolumeUnit.ImperialOunce, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 pt (imp.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ImperialPints, ImperialPintsTolerance); - Assert.Equal(VolumeUnit.ImperialPint, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 UK pt", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ImperialPints, ImperialPintsTolerance); - Assert.Equal(VolumeUnit.ImperialPint, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 pt", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ImperialPints, ImperialPintsTolerance); - Assert.Equal(VolumeUnit.ImperialPint, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 p", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ImperialPints, ImperialPintsTolerance); - Assert.Equal(VolumeUnit.ImperialPint, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 qt (imp.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.ImperialQuarts, ImperialQuartsTolerance); - Assert.Equal(VolumeUnit.ImperialQuart, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 kft³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilocubicFeet, KilocubicFeetTolerance); - Assert.Equal(VolumeUnit.KilocubicFoot, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 кфут³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilocubicFeet, KilocubicFeetTolerance); - Assert.Equal(VolumeUnit.KilocubicFoot, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 kgal (imp.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KiloimperialGallons, KiloimperialGallonsTolerance); - Assert.Equal(VolumeUnit.KiloimperialGallon, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 кАнглийский галлон", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KiloimperialGallons, KiloimperialGallonsTolerance); - Assert.Equal(VolumeUnit.KiloimperialGallon, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 kl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kiloliters, KilolitersTolerance); - Assert.Equal(VolumeUnit.Kiloliter, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 кл", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Kiloliters, KilolitersTolerance); - Assert.Equal(VolumeUnit.Kiloliter, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 kgal (U.S.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilousGallons, KilousGallonsTolerance); - Assert.Equal(VolumeUnit.KilousGallon, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 кАмериканский галлон", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilousGallons, KilousGallonsTolerance); - Assert.Equal(VolumeUnit.KilousGallon, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 l", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Liters, LitersTolerance); - Assert.Equal(VolumeUnit.Liter, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 л", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Liters, LitersTolerance); - Assert.Equal(VolumeUnit.Liter, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 Mft³", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegacubicFeet, MegacubicFeetTolerance); - Assert.Equal(VolumeUnit.MegacubicFoot, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 Мфут³", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegacubicFeet, MegacubicFeetTolerance); - Assert.Equal(VolumeUnit.MegacubicFoot, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 Mgal (imp.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegaimperialGallons, MegaimperialGallonsTolerance); - Assert.Equal(VolumeUnit.MegaimperialGallon, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 МАнглийский галлон", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegaimperialGallons, MegaimperialGallonsTolerance); - Assert.Equal(VolumeUnit.MegaimperialGallon, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 Mgal (U.S.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegausGallons, MegausGallonsTolerance); - Assert.Equal(VolumeUnit.MegausGallon, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 МАмериканский галлон", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegausGallons, MegausGallonsTolerance); - Assert.Equal(VolumeUnit.MegausGallon, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 metric cup", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetricCups, MetricCupsTolerance); - Assert.Equal(VolumeUnit.MetricCup, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 tsp", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetricTeaspoons, MetricTeaspoonsTolerance); - Assert.Equal(VolumeUnit.MetricTeaspoon, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 t", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetricTeaspoons, MetricTeaspoonsTolerance); - Assert.Equal(VolumeUnit.MetricTeaspoon, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 ts", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetricTeaspoons, MetricTeaspoonsTolerance); - Assert.Equal(VolumeUnit.MetricTeaspoon, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 tspn", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetricTeaspoons, MetricTeaspoonsTolerance); - Assert.Equal(VolumeUnit.MetricTeaspoon, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 t.", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetricTeaspoons, MetricTeaspoonsTolerance); - Assert.Equal(VolumeUnit.MetricTeaspoon, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 ts.", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetricTeaspoons, MetricTeaspoonsTolerance); - Assert.Equal(VolumeUnit.MetricTeaspoon, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 tsp.", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetricTeaspoons, MetricTeaspoonsTolerance); - Assert.Equal(VolumeUnit.MetricTeaspoon, parsed.Unit); - } - - { - Assert.True(Volume.TryParse("1 tspn.", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetricTeaspoons, MetricTeaspoonsTolerance); - Assert.Equal(VolumeUnit.MetricTeaspoon, parsed.Unit); - } + Assert.Equal(expectedValue, convertedValue); + } - { - Assert.True(Volume.TryParse("1 teaspoon", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetricTeaspoons, MetricTeaspoonsTolerance); - Assert.Equal(VolumeUnit.MetricTeaspoon, parsed.Unit); - } + [Fact] + public void As_UnitSystem_ThrowsArgumentNullExceptionIfNull() + { + var quantity = new Volume(value: 1, unit: Volume.BaseUnit); + UnitSystem nullUnitSystem = null!; + Assert.Throws(() => quantity.As(nullUnitSystem)); + } - { - Assert.True(Volume.TryParse("1 µl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microliters, MicrolitersTolerance); - Assert.Equal(VolumeUnit.Microliter, parsed.Unit); - } + [Fact] + public void As_UnitSystem_ThrowsArgumentExceptionIfNotSupported() + { + var quantity = new Volume(value: 1, unit: Volume.BaseUnit); + var unsupportedUnitSystem = new UnitSystem(UnsupportedBaseUnits); + Assert.Throws(() => quantity.As(unsupportedUnitSystem)); + } - { - Assert.True(Volume.TryParse("1 мкл", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Microliters, MicrolitersTolerance); - Assert.Equal(VolumeUnit.Microliter, parsed.Unit); - } + [Fact] + public virtual void ToUnit_UnitSystem_SI_ReturnsQuantityInSIUnits() + { + var quantity = new Volume(value: 1, unit: Volume.BaseUnit); + var expectedUnit = Volume.Info.GetDefaultUnit(UnitSystem.SI); + var expectedValue = quantity.As(expectedUnit); + Assert.Multiple(() => { - Assert.True(Volume.TryParse("1 nl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanoliters, NanolitersTolerance); - Assert.Equal(VolumeUnit.Nanoliter, parsed.Unit); - } + Volume quantityToConvert = quantity; - { - Assert.True(Volume.TryParse("1 нл", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.Nanoliters, NanolitersTolerance); - Assert.Equal(VolumeUnit.Nanoliter, parsed.Unit); - } + Volume convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); + Assert.Equal(expectedUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }, () => { - Assert.True(Volume.TryParse("1 bbl", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.OilBarrels, OilBarrelsTolerance); - Assert.Equal(VolumeUnit.OilBarrel, parsed.Unit); - } + IQuantity quantityToConvert = quantity; - { - Assert.True(Volume.TryParse("1 tablespoon (U.K.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UkTablespoons, UkTablespoonsTolerance); - Assert.Equal(VolumeUnit.UkTablespoon, parsed.Unit); - } + IQuantity convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); + Assert.Equal(expectedUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }, () => { - Assert.True(Volume.TryParse("1 bl (U.S.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UsBeerBarrels, UsBeerBarrelsTolerance); - Assert.Equal(VolumeUnit.UsBeerBarrel, parsed.Unit); - } + IQuantity quantityToConvert = quantity; - { - Assert.True(Volume.TryParse("1 cup (U.S. customary)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UsCustomaryCups, UsCustomaryCupsTolerance); - Assert.Equal(VolumeUnit.UsCustomaryCup, parsed.Unit); - } + IQuantity convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI); - { - Assert.True(Volume.TryParse("1 gal (U.S.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UsGallons, UsGallonsTolerance); - Assert.Equal(VolumeUnit.UsGallon, parsed.Unit); - } + Assert.Equal(expectedUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }); + } + [Fact] + public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() + { + UnitSystem nullUnitSystem = null!; + Assert.Multiple(() => { - Assert.True(Volume.TryParse("1 Американский галлон", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UsGallons, UsGallonsTolerance); - Assert.Equal(VolumeUnit.UsGallon, parsed.Unit); - } - + var quantity = new Volume(value: 1, unit: Volume.BaseUnit); + Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); + }, () => { - Assert.True(Volume.TryParse("1 cup (U.S.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UsLegalCups, UsLegalCupsTolerance); - Assert.Equal(VolumeUnit.UsLegalCup, parsed.Unit); - } - + IQuantity quantity = new Volume(value: 1, unit: Volume.BaseUnit); + Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); + }, () => { - Assert.True(Volume.TryParse("1 oz (U.S.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UsOunces, UsOuncesTolerance); - Assert.Equal(VolumeUnit.UsOunce, parsed.Unit); - } + IQuantity quantity = new Volume(value: 1, unit: Volume.BaseUnit); + Assert.Throws(() => quantity.ToUnit(nullUnitSystem)); + }); + } + [Fact] + public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() + { + var unsupportedUnitSystem = new UnitSystem(UnsupportedBaseUnits); + Assert.Multiple(() => { - Assert.True(Volume.TryParse("1 Американская унция", CultureInfo.GetCultureInfo("ru-RU"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UsOunces, UsOuncesTolerance); - Assert.Equal(VolumeUnit.UsOunce, parsed.Unit); - } - + var quantity = new Volume(value: 1, unit: Volume.BaseUnit); + Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); + }, () => { - Assert.True(Volume.TryParse("1 pt (U.S.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UsPints, UsPintsTolerance); - Assert.Equal(VolumeUnit.UsPint, parsed.Unit); - } - + IQuantity quantity = new Volume(value: 1, unit: Volume.BaseUnit); + Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); + }, () => { - Assert.True(Volume.TryParse("1 qt (U.S.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UsQuarts, UsQuartsTolerance); - Assert.Equal(VolumeUnit.UsQuart, parsed.Unit); - } + IQuantity quantity = new Volume(value: 1, unit: Volume.BaseUnit); + Assert.Throws(() => quantity.ToUnit(unsupportedUnitSystem)); + }); + } - { - Assert.True(Volume.TryParse("1 tablespoon (U.S.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UsTablespoons, UsTablespoonsTolerance); - Assert.Equal(VolumeUnit.UsTablespoon, parsed.Unit); - } + [Theory] + [InlineData("en-US", "4.2 ac-ft", VolumeUnit.AcreFoot, 4.2)] + [InlineData("en-US", "4.2 acre-foot", VolumeUnit.AcreFoot, 4.2)] + [InlineData("en-US", "4.2 acre-feet", VolumeUnit.AcreFoot, 4.2)] + [InlineData("en-US", "4.2 tablespoon (A.U.)", VolumeUnit.AuTablespoon, 4.2)] + [InlineData("en-US", "4.2 bf", VolumeUnit.BoardFoot, 4.2)] + [InlineData("en-US", "4.2 board foot", VolumeUnit.BoardFoot, 4.2)] + [InlineData("en-US", "4.2 board feet", VolumeUnit.BoardFoot, 4.2)] + [InlineData("en-US", "4.2 cl", VolumeUnit.Centiliter, 4.2)] + [InlineData("en-US", "4.2 cm³", VolumeUnit.CubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 dm³", VolumeUnit.CubicDecimeter, 4.2)] + [InlineData("en-US", "4.2 ft³", VolumeUnit.CubicFoot, 4.2)] + [InlineData("en-US", "4.2 in³", VolumeUnit.CubicInch, 4.2)] + [InlineData("en-US", "4.2 m³", VolumeUnit.CubicMeter, 4.2)] + [InlineData("en-US", "4.2 µm³", VolumeUnit.CubicMicrometer, 4.2)] + [InlineData("en-US", "4.2 mi³", VolumeUnit.CubicMile, 4.2)] + [InlineData("en-US", "4.2 mm³", VolumeUnit.CubicMillimeter, 4.2)] + [InlineData("en-US", "4.2 yd³", VolumeUnit.CubicYard, 4.2)] + [InlineData("en-US", "4.2 dal", VolumeUnit.Decaliter, 4.2)] + [InlineData("en-US", "4.2 dagal (U.S.)", VolumeUnit.DecausGallon, 4.2)] + [InlineData("en-US", "4.2 dl", VolumeUnit.Deciliter, 4.2)] + [InlineData("en-US", "4.2 dgal (U.S.)", VolumeUnit.DeciusGallon, 4.2)] + [InlineData("en-US", "4.2 hft³", VolumeUnit.HectocubicFoot, 4.2)] + [InlineData("en-US", "4.2 hl", VolumeUnit.Hectoliter, 4.2)] + [InlineData("en-US", "4.2 hgal (U.S.)", VolumeUnit.HectousGallon, 4.2)] + [InlineData("en-US", "4.2 bl (imp.)", VolumeUnit.ImperialBeerBarrel, 4.2)] + [InlineData("en-US", "4.2 gal (imp.)", VolumeUnit.ImperialGallon, 4.2)] + [InlineData("en-US", "4.2 oz (imp.)", VolumeUnit.ImperialOunce, 4.2)] + [InlineData("en-US", "4.2 pt (imp.)", VolumeUnit.ImperialPint, 4.2)] + [InlineData("en-US", "4.2 UK pt", VolumeUnit.ImperialPint, 4.2)] + [InlineData("en-US", "4.2 pt", VolumeUnit.ImperialPint, 4.2)] + [InlineData("en-US", "4.2 p", VolumeUnit.ImperialPint, 4.2)] + [InlineData("en-US", "4.2 qt (imp.)", VolumeUnit.ImperialQuart, 4.2)] + [InlineData("en-US", "4.2 kft³", VolumeUnit.KilocubicFoot, 4.2)] + [InlineData("en-US", "4.2 kgal (imp.)", VolumeUnit.KiloimperialGallon, 4.2)] + [InlineData("en-US", "4.2 kl", VolumeUnit.Kiloliter, 4.2)] + [InlineData("en-US", "4.2 kgal (U.S.)", VolumeUnit.KilousGallon, 4.2)] + [InlineData("en-US", "4.2 l", VolumeUnit.Liter, 4.2)] + [InlineData("en-US", "4.2 Mft³", VolumeUnit.MegacubicFoot, 4.2)] + [InlineData("en-US", "4.2 Mgal (imp.)", VolumeUnit.MegaimperialGallon, 4.2)] + [InlineData("en-US", "4.2 Ml", VolumeUnit.Megaliter, 4.2)] + [InlineData("en-US", "4.2 Mgal (U.S.)", VolumeUnit.MegausGallon, 4.2)] + [InlineData("en-US", "4.2 metric cup", VolumeUnit.MetricCup, 4.2)] + [InlineData("en-US", "4.2 tsp", VolumeUnit.MetricTeaspoon, 4.2)] + [InlineData("en-US", "4.2 t", VolumeUnit.MetricTeaspoon, 4.2)] + [InlineData("en-US", "4.2 ts", VolumeUnit.MetricTeaspoon, 4.2)] + [InlineData("en-US", "4.2 tspn", VolumeUnit.MetricTeaspoon, 4.2)] + [InlineData("en-US", "4.2 t.", VolumeUnit.MetricTeaspoon, 4.2)] + [InlineData("en-US", "4.2 ts.", VolumeUnit.MetricTeaspoon, 4.2)] + [InlineData("en-US", "4.2 tsp.", VolumeUnit.MetricTeaspoon, 4.2)] + [InlineData("en-US", "4.2 tspn.", VolumeUnit.MetricTeaspoon, 4.2)] + [InlineData("en-US", "4.2 teaspoon", VolumeUnit.MetricTeaspoon, 4.2)] + [InlineData("en-US", "4.2 µl", VolumeUnit.Microliter, 4.2)] + [InlineData("en-US", "4.2 ml", VolumeUnit.Milliliter, 4.2)] + [InlineData("en-US", "4.2 nl", VolumeUnit.Nanoliter, 4.2)] + [InlineData("en-US", "4.2 bbl", VolumeUnit.OilBarrel, 4.2)] + [InlineData("en-US", "4.2 tablespoon (U.K.)", VolumeUnit.UkTablespoon, 4.2)] + [InlineData("en-US", "4.2 bl (U.S.)", VolumeUnit.UsBeerBarrel, 4.2)] + [InlineData("en-US", "4.2 cup (U.S. customary)", VolumeUnit.UsCustomaryCup, 4.2)] + [InlineData("en-US", "4.2 gal (U.S.)", VolumeUnit.UsGallon, 4.2)] + [InlineData("en-US", "4.2 cup (U.S.)", VolumeUnit.UsLegalCup, 4.2)] + [InlineData("en-US", "4.2 oz (U.S.)", VolumeUnit.UsOunce, 4.2)] + [InlineData("en-US", "4.2 pt (U.S.)", VolumeUnit.UsPint, 4.2)] + [InlineData("en-US", "4.2 qt (U.S.)", VolumeUnit.UsQuart, 4.2)] + [InlineData("en-US", "4.2 tablespoon (U.S.)", VolumeUnit.UsTablespoon, 4.2)] + [InlineData("en-US", "4.2 teaspoon (U.S.)", VolumeUnit.UsTeaspoon, 4.2)] + [InlineData("fr-CA", "4,2 pmp", VolumeUnit.BoardFoot, 4.2)] + [InlineData("fr-CA", "4,2 pied-planche", VolumeUnit.BoardFoot, 4.2)] + [InlineData("fr-CA", "4,2 pied de planche", VolumeUnit.BoardFoot, 4.2)] + [InlineData("ru-RU", "4,2 сл", VolumeUnit.Centiliter, 4.2)] + [InlineData("ru-RU", "4,2 см³", VolumeUnit.CubicCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 дм³", VolumeUnit.CubicDecimeter, 4.2)] + [InlineData("ru-RU", "4,2 фут³", VolumeUnit.CubicFoot, 4.2)] + [InlineData("ru-RU", "4,2 дюйм³", VolumeUnit.CubicInch, 4.2)] + [InlineData("ru-RU", "4,2 м³", VolumeUnit.CubicMeter, 4.2)] + [InlineData("ru-RU", "4,2 мкм³", VolumeUnit.CubicMicrometer, 4.2)] + [InlineData("ru-RU", "4,2 миля³", VolumeUnit.CubicMile, 4.2)] + [InlineData("ru-RU", "4,2 мм³", VolumeUnit.CubicMillimeter, 4.2)] + [InlineData("ru-RU", "4,2 ярд³", VolumeUnit.CubicYard, 4.2)] + [InlineData("ru-RU", "4,2 дал", VolumeUnit.Decaliter, 4.2)] + [InlineData("ru-RU", "4,2 даАмериканский галлон", VolumeUnit.DecausGallon, 4.2)] + [InlineData("ru-RU", "4,2 дл", VolumeUnit.Deciliter, 4.2)] + [InlineData("ru-RU", "4,2 дАмериканский галлон", VolumeUnit.DeciusGallon, 4.2)] + [InlineData("ru-RU", "4,2 гфут³", VolumeUnit.HectocubicFoot, 4.2)] + [InlineData("ru-RU", "4,2 гл", VolumeUnit.Hectoliter, 4.2)] + [InlineData("ru-RU", "4,2 гАмериканский галлон", VolumeUnit.HectousGallon, 4.2)] + [InlineData("ru-RU", "4,2 Английский галлон", VolumeUnit.ImperialGallon, 4.2)] + [InlineData("ru-RU", "4,2 Английская унция", VolumeUnit.ImperialOunce, 4.2)] + [InlineData("ru-RU", "4,2 кфут³", VolumeUnit.KilocubicFoot, 4.2)] + [InlineData("ru-RU", "4,2 кАнглийский галлон", VolumeUnit.KiloimperialGallon, 4.2)] + [InlineData("ru-RU", "4,2 кл", VolumeUnit.Kiloliter, 4.2)] + [InlineData("ru-RU", "4,2 кАмериканский галлон", VolumeUnit.KilousGallon, 4.2)] + [InlineData("ru-RU", "4,2 л", VolumeUnit.Liter, 4.2)] + [InlineData("ru-RU", "4,2 Мфут³", VolumeUnit.MegacubicFoot, 4.2)] + [InlineData("ru-RU", "4,2 МАнглийский галлон", VolumeUnit.MegaimperialGallon, 4.2)] + [InlineData("ru-RU", "4,2 Мл", VolumeUnit.Megaliter, 4.2)] + [InlineData("ru-RU", "4,2 МАмериканский галлон", VolumeUnit.MegausGallon, 4.2)] + [InlineData("ru-RU", "4,2 мкл", VolumeUnit.Microliter, 4.2)] + [InlineData("ru-RU", "4,2 мл", VolumeUnit.Milliliter, 4.2)] + [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, decimal expectedValue) + { + using var _ = new CultureScope(culture); + var parsed = Volume.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); + } - { - Assert.True(Volume.TryParse("1 teaspoon (U.S.)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.UsTeaspoons, UsTeaspoonsTolerance); - Assert.Equal(VolumeUnit.UsTeaspoon, parsed.Unit); - } + [Theory] + [InlineData("en-US", "1 hm³")] // [CubicHectometer, HectocubicMeter] + [InlineData("en-US", "1 km³")] // [CubicKilometer, KilocubicMeter] + [InlineData("ru-RU", "1 гм³")] // [CubicHectometer, HectocubicMeter] + [InlineData("ru-RU", "1 км³")] // [CubicKilometer, KilocubicMeter] + public void ParseWithAmbiguousAbbreviation(string culture, string quantityString) + { + Assert.Throws(() => Volume.Parse(quantityString, CultureInfo.GetCultureInfo(culture))); + } + + [Theory] + [InlineData("en-US", "4.2 ac-ft", VolumeUnit.AcreFoot, 4.2)] + [InlineData("en-US", "4.2 acre-foot", VolumeUnit.AcreFoot, 4.2)] + [InlineData("en-US", "4.2 acre-feet", VolumeUnit.AcreFoot, 4.2)] + [InlineData("en-US", "4.2 tablespoon (A.U.)", VolumeUnit.AuTablespoon, 4.2)] + [InlineData("en-US", "4.2 bf", VolumeUnit.BoardFoot, 4.2)] + [InlineData("en-US", "4.2 board foot", VolumeUnit.BoardFoot, 4.2)] + [InlineData("en-US", "4.2 board feet", VolumeUnit.BoardFoot, 4.2)] + [InlineData("en-US", "4.2 cl", VolumeUnit.Centiliter, 4.2)] + [InlineData("en-US", "4.2 cm³", VolumeUnit.CubicCentimeter, 4.2)] + [InlineData("en-US", "4.2 dm³", VolumeUnit.CubicDecimeter, 4.2)] + [InlineData("en-US", "4.2 ft³", VolumeUnit.CubicFoot, 4.2)] + [InlineData("en-US", "4.2 in³", VolumeUnit.CubicInch, 4.2)] + [InlineData("en-US", "4.2 m³", VolumeUnit.CubicMeter, 4.2)] + [InlineData("en-US", "4.2 µm³", VolumeUnit.CubicMicrometer, 4.2)] + [InlineData("en-US", "4.2 mi³", VolumeUnit.CubicMile, 4.2)] + [InlineData("en-US", "4.2 mm³", VolumeUnit.CubicMillimeter, 4.2)] + [InlineData("en-US", "4.2 yd³", VolumeUnit.CubicYard, 4.2)] + [InlineData("en-US", "4.2 dal", VolumeUnit.Decaliter, 4.2)] + [InlineData("en-US", "4.2 dagal (U.S.)", VolumeUnit.DecausGallon, 4.2)] + [InlineData("en-US", "4.2 dl", VolumeUnit.Deciliter, 4.2)] + [InlineData("en-US", "4.2 dgal (U.S.)", VolumeUnit.DeciusGallon, 4.2)] + [InlineData("en-US", "4.2 hft³", VolumeUnit.HectocubicFoot, 4.2)] + [InlineData("en-US", "4.2 hl", VolumeUnit.Hectoliter, 4.2)] + [InlineData("en-US", "4.2 hgal (U.S.)", VolumeUnit.HectousGallon, 4.2)] + [InlineData("en-US", "4.2 bl (imp.)", VolumeUnit.ImperialBeerBarrel, 4.2)] + [InlineData("en-US", "4.2 gal (imp.)", VolumeUnit.ImperialGallon, 4.2)] + [InlineData("en-US", "4.2 oz (imp.)", VolumeUnit.ImperialOunce, 4.2)] + [InlineData("en-US", "4.2 pt (imp.)", VolumeUnit.ImperialPint, 4.2)] + [InlineData("en-US", "4.2 UK pt", VolumeUnit.ImperialPint, 4.2)] + [InlineData("en-US", "4.2 pt", VolumeUnit.ImperialPint, 4.2)] + [InlineData("en-US", "4.2 p", VolumeUnit.ImperialPint, 4.2)] + [InlineData("en-US", "4.2 qt (imp.)", VolumeUnit.ImperialQuart, 4.2)] + [InlineData("en-US", "4.2 kft³", VolumeUnit.KilocubicFoot, 4.2)] + [InlineData("en-US", "4.2 kgal (imp.)", VolumeUnit.KiloimperialGallon, 4.2)] + [InlineData("en-US", "4.2 kl", VolumeUnit.Kiloliter, 4.2)] + [InlineData("en-US", "4.2 kgal (U.S.)", VolumeUnit.KilousGallon, 4.2)] + [InlineData("en-US", "4.2 l", VolumeUnit.Liter, 4.2)] + [InlineData("en-US", "4.2 Mft³", VolumeUnit.MegacubicFoot, 4.2)] + [InlineData("en-US", "4.2 Mgal (imp.)", VolumeUnit.MegaimperialGallon, 4.2)] + [InlineData("en-US", "4.2 Ml", VolumeUnit.Megaliter, 4.2)] + [InlineData("en-US", "4.2 Mgal (U.S.)", VolumeUnit.MegausGallon, 4.2)] + [InlineData("en-US", "4.2 metric cup", VolumeUnit.MetricCup, 4.2)] + [InlineData("en-US", "4.2 tsp", VolumeUnit.MetricTeaspoon, 4.2)] + [InlineData("en-US", "4.2 t", VolumeUnit.MetricTeaspoon, 4.2)] + [InlineData("en-US", "4.2 ts", VolumeUnit.MetricTeaspoon, 4.2)] + [InlineData("en-US", "4.2 tspn", VolumeUnit.MetricTeaspoon, 4.2)] + [InlineData("en-US", "4.2 t.", VolumeUnit.MetricTeaspoon, 4.2)] + [InlineData("en-US", "4.2 ts.", VolumeUnit.MetricTeaspoon, 4.2)] + [InlineData("en-US", "4.2 tsp.", VolumeUnit.MetricTeaspoon, 4.2)] + [InlineData("en-US", "4.2 tspn.", VolumeUnit.MetricTeaspoon, 4.2)] + [InlineData("en-US", "4.2 teaspoon", VolumeUnit.MetricTeaspoon, 4.2)] + [InlineData("en-US", "4.2 µl", VolumeUnit.Microliter, 4.2)] + [InlineData("en-US", "4.2 ml", VolumeUnit.Milliliter, 4.2)] + [InlineData("en-US", "4.2 nl", VolumeUnit.Nanoliter, 4.2)] + [InlineData("en-US", "4.2 bbl", VolumeUnit.OilBarrel, 4.2)] + [InlineData("en-US", "4.2 tablespoon (U.K.)", VolumeUnit.UkTablespoon, 4.2)] + [InlineData("en-US", "4.2 bl (U.S.)", VolumeUnit.UsBeerBarrel, 4.2)] + [InlineData("en-US", "4.2 cup (U.S. customary)", VolumeUnit.UsCustomaryCup, 4.2)] + [InlineData("en-US", "4.2 gal (U.S.)", VolumeUnit.UsGallon, 4.2)] + [InlineData("en-US", "4.2 cup (U.S.)", VolumeUnit.UsLegalCup, 4.2)] + [InlineData("en-US", "4.2 oz (U.S.)", VolumeUnit.UsOunce, 4.2)] + [InlineData("en-US", "4.2 pt (U.S.)", VolumeUnit.UsPint, 4.2)] + [InlineData("en-US", "4.2 qt (U.S.)", VolumeUnit.UsQuart, 4.2)] + [InlineData("en-US", "4.2 tablespoon (U.S.)", VolumeUnit.UsTablespoon, 4.2)] + [InlineData("en-US", "4.2 teaspoon (U.S.)", VolumeUnit.UsTeaspoon, 4.2)] + [InlineData("fr-CA", "4,2 pmp", VolumeUnit.BoardFoot, 4.2)] + [InlineData("fr-CA", "4,2 pied-planche", VolumeUnit.BoardFoot, 4.2)] + [InlineData("fr-CA", "4,2 pied de planche", VolumeUnit.BoardFoot, 4.2)] + [InlineData("ru-RU", "4,2 сл", VolumeUnit.Centiliter, 4.2)] + [InlineData("ru-RU", "4,2 см³", VolumeUnit.CubicCentimeter, 4.2)] + [InlineData("ru-RU", "4,2 дм³", VolumeUnit.CubicDecimeter, 4.2)] + [InlineData("ru-RU", "4,2 фут³", VolumeUnit.CubicFoot, 4.2)] + [InlineData("ru-RU", "4,2 дюйм³", VolumeUnit.CubicInch, 4.2)] + [InlineData("ru-RU", "4,2 м³", VolumeUnit.CubicMeter, 4.2)] + [InlineData("ru-RU", "4,2 мкм³", VolumeUnit.CubicMicrometer, 4.2)] + [InlineData("ru-RU", "4,2 миля³", VolumeUnit.CubicMile, 4.2)] + [InlineData("ru-RU", "4,2 мм³", VolumeUnit.CubicMillimeter, 4.2)] + [InlineData("ru-RU", "4,2 ярд³", VolumeUnit.CubicYard, 4.2)] + [InlineData("ru-RU", "4,2 дал", VolumeUnit.Decaliter, 4.2)] + [InlineData("ru-RU", "4,2 даАмериканский галлон", VolumeUnit.DecausGallon, 4.2)] + [InlineData("ru-RU", "4,2 дл", VolumeUnit.Deciliter, 4.2)] + [InlineData("ru-RU", "4,2 дАмериканский галлон", VolumeUnit.DeciusGallon, 4.2)] + [InlineData("ru-RU", "4,2 гфут³", VolumeUnit.HectocubicFoot, 4.2)] + [InlineData("ru-RU", "4,2 гл", VolumeUnit.Hectoliter, 4.2)] + [InlineData("ru-RU", "4,2 гАмериканский галлон", VolumeUnit.HectousGallon, 4.2)] + [InlineData("ru-RU", "4,2 Английский галлон", VolumeUnit.ImperialGallon, 4.2)] + [InlineData("ru-RU", "4,2 Английская унция", VolumeUnit.ImperialOunce, 4.2)] + [InlineData("ru-RU", "4,2 кфут³", VolumeUnit.KilocubicFoot, 4.2)] + [InlineData("ru-RU", "4,2 кАнглийский галлон", VolumeUnit.KiloimperialGallon, 4.2)] + [InlineData("ru-RU", "4,2 кл", VolumeUnit.Kiloliter, 4.2)] + [InlineData("ru-RU", "4,2 кАмериканский галлон", VolumeUnit.KilousGallon, 4.2)] + [InlineData("ru-RU", "4,2 л", VolumeUnit.Liter, 4.2)] + [InlineData("ru-RU", "4,2 Мфут³", VolumeUnit.MegacubicFoot, 4.2)] + [InlineData("ru-RU", "4,2 МАнглийский галлон", VolumeUnit.MegaimperialGallon, 4.2)] + [InlineData("ru-RU", "4,2 Мл", VolumeUnit.Megaliter, 4.2)] + [InlineData("ru-RU", "4,2 МАмериканский галлон", VolumeUnit.MegausGallon, 4.2)] + [InlineData("ru-RU", "4,2 мкл", VolumeUnit.Microliter, 4.2)] + [InlineData("ru-RU", "4,2 мл", VolumeUnit.Milliliter, 4.2)] + [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, decimal expectedValue) + { + using var _ = new CultureScope(culture); + Assert.True(Volume.TryParse(quantityString, out Volume parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); + } + [Theory] + [InlineData("en-US", "1 hm³")] // [CubicHectometer, HectocubicMeter] + [InlineData("en-US", "1 km³")] // [CubicKilometer, KilocubicMeter] + [InlineData("ru-RU", "1 гм³")] // [CubicHectometer, HectocubicMeter] + [InlineData("ru-RU", "1 км³")] // [CubicKilometer, KilocubicMeter] + public void TryParseWithAmbiguousAbbreviation(string culture, string quantityString) + { + Assert.False(Volume.TryParse(quantityString, CultureInfo.GetCultureInfo(culture), out _)); } [Theory] @@ -2902,6 +1805,118 @@ public void TryParseUnitWithAmbiguousAbbreviation(string culture, string abbrevi Assert.False(Volume.TryParseUnit(abbreviation, CultureInfo.GetCultureInfo(culture), out _)); } + [Theory] + [InlineData("en-US", VolumeUnit.AcreFoot, "ac-ft")] + [InlineData("en-US", VolumeUnit.AuTablespoon, "tablespoon (A.U.)")] + [InlineData("en-US", VolumeUnit.BoardFoot, "bf")] + [InlineData("en-US", VolumeUnit.Centiliter, "cl")] + [InlineData("en-US", VolumeUnit.CubicCentimeter, "cm³")] + [InlineData("en-US", VolumeUnit.CubicDecimeter, "dm³")] + [InlineData("en-US", VolumeUnit.CubicFoot, "ft³")] + [InlineData("en-US", VolumeUnit.CubicHectometer, "hm³")] + [InlineData("en-US", VolumeUnit.CubicInch, "in³")] + [InlineData("en-US", VolumeUnit.CubicKilometer, "km³")] + [InlineData("en-US", VolumeUnit.CubicMeter, "m³")] + [InlineData("en-US", VolumeUnit.CubicMicrometer, "µm³")] + [InlineData("en-US", VolumeUnit.CubicMile, "mi³")] + [InlineData("en-US", VolumeUnit.CubicMillimeter, "mm³")] + [InlineData("en-US", VolumeUnit.CubicYard, "yd³")] + [InlineData("en-US", VolumeUnit.Decaliter, "dal")] + [InlineData("en-US", VolumeUnit.DecausGallon, "dagal (U.S.)")] + [InlineData("en-US", VolumeUnit.Deciliter, "dl")] + [InlineData("en-US", VolumeUnit.DeciusGallon, "dgal (U.S.)")] + [InlineData("en-US", VolumeUnit.HectocubicFoot, "hft³")] + [InlineData("en-US", VolumeUnit.HectocubicMeter, "hm³")] + [InlineData("en-US", VolumeUnit.Hectoliter, "hl")] + [InlineData("en-US", VolumeUnit.HectousGallon, "hgal (U.S.)")] + [InlineData("en-US", VolumeUnit.ImperialBeerBarrel, "bl (imp.)")] + [InlineData("en-US", VolumeUnit.ImperialGallon, "gal (imp.)")] + [InlineData("en-US", VolumeUnit.ImperialOunce, "oz (imp.)")] + [InlineData("en-US", VolumeUnit.ImperialPint, "pt (imp.)")] + [InlineData("en-US", VolumeUnit.ImperialQuart, "qt (imp.)")] + [InlineData("en-US", VolumeUnit.KilocubicFoot, "kft³")] + [InlineData("en-US", VolumeUnit.KilocubicMeter, "km³")] + [InlineData("en-US", VolumeUnit.KiloimperialGallon, "kgal (imp.)")] + [InlineData("en-US", VolumeUnit.Kiloliter, "kl")] + [InlineData("en-US", VolumeUnit.KilousGallon, "kgal (U.S.)")] + [InlineData("en-US", VolumeUnit.Liter, "l")] + [InlineData("en-US", VolumeUnit.MegacubicFoot, "Mft³")] + [InlineData("en-US", VolumeUnit.MegaimperialGallon, "Mgal (imp.)")] + [InlineData("en-US", VolumeUnit.Megaliter, "Ml")] + [InlineData("en-US", VolumeUnit.MegausGallon, "Mgal (U.S.)")] + [InlineData("en-US", VolumeUnit.MetricCup, "metric cup")] + [InlineData("en-US", VolumeUnit.MetricTeaspoon, "tsp")] + [InlineData("en-US", VolumeUnit.Microliter, "µl")] + [InlineData("en-US", VolumeUnit.Milliliter, "ml")] + [InlineData("en-US", VolumeUnit.Nanoliter, "nl")] + [InlineData("en-US", VolumeUnit.OilBarrel, "bbl")] + [InlineData("en-US", VolumeUnit.UkTablespoon, "tablespoon (U.K.)")] + [InlineData("en-US", VolumeUnit.UsBeerBarrel, "bl (U.S.)")] + [InlineData("en-US", VolumeUnit.UsCustomaryCup, "cup (U.S. customary)")] + [InlineData("en-US", VolumeUnit.UsGallon, "gal (U.S.)")] + [InlineData("en-US", VolumeUnit.UsLegalCup, "cup (U.S.)")] + [InlineData("en-US", VolumeUnit.UsOunce, "oz (U.S.)")] + [InlineData("en-US", VolumeUnit.UsPint, "pt (U.S.)")] + [InlineData("en-US", VolumeUnit.UsQuart, "qt (U.S.)")] + [InlineData("en-US", VolumeUnit.UsTablespoon, "tablespoon (U.S.)")] + [InlineData("en-US", VolumeUnit.UsTeaspoon, "teaspoon (U.S.)")] + [InlineData("fr-CA", VolumeUnit.BoardFoot, "pmp")] + [InlineData("ru-RU", VolumeUnit.Centiliter, "сл")] + [InlineData("ru-RU", VolumeUnit.CubicCentimeter, "см³")] + [InlineData("ru-RU", VolumeUnit.CubicDecimeter, "дм³")] + [InlineData("ru-RU", VolumeUnit.CubicFoot, "фут³")] + [InlineData("ru-RU", VolumeUnit.CubicHectometer, "гм³")] + [InlineData("ru-RU", VolumeUnit.CubicInch, "дюйм³")] + [InlineData("ru-RU", VolumeUnit.CubicKilometer, "км³")] + [InlineData("ru-RU", VolumeUnit.CubicMeter, "м³")] + [InlineData("ru-RU", VolumeUnit.CubicMicrometer, "мкм³")] + [InlineData("ru-RU", VolumeUnit.CubicMile, "миля³")] + [InlineData("ru-RU", VolumeUnit.CubicMillimeter, "мм³")] + [InlineData("ru-RU", VolumeUnit.CubicYard, "ярд³")] + [InlineData("ru-RU", VolumeUnit.Decaliter, "дал")] + [InlineData("ru-RU", VolumeUnit.DecausGallon, "даАмериканский галлон")] + [InlineData("ru-RU", VolumeUnit.Deciliter, "дл")] + [InlineData("ru-RU", VolumeUnit.DeciusGallon, "дАмериканский галлон")] + [InlineData("ru-RU", VolumeUnit.HectocubicFoot, "гфут³")] + [InlineData("ru-RU", VolumeUnit.HectocubicMeter, "гм³")] + [InlineData("ru-RU", VolumeUnit.Hectoliter, "гл")] + [InlineData("ru-RU", VolumeUnit.HectousGallon, "гАмериканский галлон")] + [InlineData("ru-RU", VolumeUnit.ImperialGallon, "Английский галлон")] + [InlineData("ru-RU", VolumeUnit.ImperialOunce, "Английская унция")] + [InlineData("ru-RU", VolumeUnit.KilocubicFoot, "кфут³")] + [InlineData("ru-RU", VolumeUnit.KilocubicMeter, "км³")] + [InlineData("ru-RU", VolumeUnit.KiloimperialGallon, "кАнглийский галлон")] + [InlineData("ru-RU", VolumeUnit.Kiloliter, "кл")] + [InlineData("ru-RU", VolumeUnit.KilousGallon, "кАмериканский галлон")] + [InlineData("ru-RU", VolumeUnit.Liter, "л")] + [InlineData("ru-RU", VolumeUnit.MegacubicFoot, "Мфут³")] + [InlineData("ru-RU", VolumeUnit.MegaimperialGallon, "МАнглийский галлон")] + [InlineData("ru-RU", VolumeUnit.Megaliter, "Мл")] + [InlineData("ru-RU", VolumeUnit.MegausGallon, "МАмериканский галлон")] + [InlineData("ru-RU", VolumeUnit.Microliter, "мкл")] + [InlineData("ru-RU", VolumeUnit.Milliliter, "мл")] + [InlineData("ru-RU", VolumeUnit.Nanoliter, "нл")] + [InlineData("ru-RU", VolumeUnit.UsGallon, "Американский галлон")] + [InlineData("ru-RU", VolumeUnit.UsOunce, "Американская унция")] + public void GetAbbreviationForCulture(string culture, VolumeUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = Volume.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(Volume.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = Volume.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(VolumeUnit unit) @@ -2932,6 +1947,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); }); } @@ -2955,85 +1971,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] @@ -3079,8 +2097,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); @@ -3117,23 +2133,6 @@ public void Equals_Null_ReturnsFalse() #pragma warning restore CS8073 } - [Fact] - public void Equals_RelativeTolerance_IsImplemented() - { - var v = Volume.FromCubicMeters(1); - Assert.True(v.Equals(Volume.FromCubicMeters(1), CubicMetersTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(Volume.Zero, CubicMetersTolerance, ComparisonType.Relative)); - Assert.True(Volume.FromCubicMeters(100).Equals(Volume.FromCubicMeters(120), 0.3, ComparisonType.Relative)); - Assert.False(Volume.FromCubicMeters(100).Equals(Volume.FromCubicMeters(120), 0.1, ComparisonType.Relative)); - } - - [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() - { - var v = Volume.FromCubicMeters(1); - Assert.Throws(() => v.Equals(Volume.FromCubicMeters(1), -1, ComparisonType.Relative)); - } - [Fact] public void EqualsReturnsFalseOnTypeMismatch() { @@ -3148,6 +2147,32 @@ public void EqualsReturnsFalseOnNull() Assert.False(cubicmeter.Equals(null)); } + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(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.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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + } + + [Fact] + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = Volume.FromCubicMeters(1); + var negativeTolerance = Volume.FromCubicMeters(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); + } + [Fact] public void HasAtLeastOneAbbreviationSpecified() { @@ -3164,6 +2189,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() { @@ -3328,158 +2365,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(Volume))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(VolumeUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal(Volume.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal(Volume.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal(new {Volume.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 d3f5d820cb..d52c155d55 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumetricHeatCapacityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumetricHeatCapacityTestsBase.g.cs @@ -128,7 +128,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new VolumetricHeatCapacity(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -141,15 +141,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void VolumetricHeatCapacity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + VolumetricHeatCapacityUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new VolumetricHeatCapacity(1, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(VolumetricHeatCapacity.Zero, quantityInfo.Zero); Assert.Equal("VolumetricHeatCapacity", quantityInfo.Name); + Assert.Equal(VolumetricHeatCapacity.Zero, quantityInfo.Zero); + Assert.Equal(VolumetricHeatCapacity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(VolumetricHeatCapacity.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + 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)); - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -171,39 +189,39 @@ public void JoulePerCubicMeterKelvinToVolumetricHeatCapacityUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = VolumetricHeatCapacity.From(1, VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit); - AssertEx.EqualTolerance(1, quantity00.BtusPerCubicFootDegreeFahrenheit, BtusPerCubicFootDegreeFahrenheitTolerance); + Assert.Equal(1, quantity00.BtusPerCubicFootDegreeFahrenheit); Assert.Equal(VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit, quantity00.Unit); var quantity01 = VolumetricHeatCapacity.From(1, VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius); - AssertEx.EqualTolerance(1, quantity01.CaloriesPerCubicCentimeterDegreeCelsius, CaloriesPerCubicCentimeterDegreeCelsiusTolerance); + Assert.Equal(1, quantity01.CaloriesPerCubicCentimeterDegreeCelsius); Assert.Equal(VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius, quantity01.Unit); var quantity02 = VolumetricHeatCapacity.From(1, VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius); - AssertEx.EqualTolerance(1, quantity02.JoulesPerCubicMeterDegreeCelsius, JoulesPerCubicMeterDegreeCelsiusTolerance); + Assert.Equal(1, quantity02.JoulesPerCubicMeterDegreeCelsius); Assert.Equal(VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius, quantity02.Unit); var quantity03 = VolumetricHeatCapacity.From(1, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin); - AssertEx.EqualTolerance(1, quantity03.JoulesPerCubicMeterKelvin, JoulesPerCubicMeterKelvinTolerance); + Assert.Equal(1, quantity03.JoulesPerCubicMeterKelvin); Assert.Equal(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity03.Unit); var quantity04 = VolumetricHeatCapacity.From(1, VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius); - AssertEx.EqualTolerance(1, quantity04.KilocaloriesPerCubicCentimeterDegreeCelsius, KilocaloriesPerCubicCentimeterDegreeCelsiusTolerance); + Assert.Equal(1, quantity04.KilocaloriesPerCubicCentimeterDegreeCelsius); Assert.Equal(VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius, quantity04.Unit); var quantity05 = VolumetricHeatCapacity.From(1, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius); - AssertEx.EqualTolerance(1, quantity05.KilojoulesPerCubicMeterDegreeCelsius, KilojoulesPerCubicMeterDegreeCelsiusTolerance); + Assert.Equal(1, quantity05.KilojoulesPerCubicMeterDegreeCelsius); Assert.Equal(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius, quantity05.Unit); var quantity06 = VolumetricHeatCapacity.From(1, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin); - AssertEx.EqualTolerance(1, quantity06.KilojoulesPerCubicMeterKelvin, KilojoulesPerCubicMeterKelvinTolerance); + Assert.Equal(1, quantity06.KilojoulesPerCubicMeterKelvin); Assert.Equal(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin, quantity06.Unit); var quantity07 = VolumetricHeatCapacity.From(1, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius); - AssertEx.EqualTolerance(1, quantity07.MegajoulesPerCubicMeterDegreeCelsius, MegajoulesPerCubicMeterDegreeCelsiusTolerance); + Assert.Equal(1, quantity07.MegajoulesPerCubicMeterDegreeCelsius); Assert.Equal(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius, quantity07.Unit); var quantity08 = VolumetricHeatCapacity.From(1, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin); - AssertEx.EqualTolerance(1, quantity08.MegajoulesPerCubicMeterKelvin, MegajoulesPerCubicMeterKelvinTolerance); + Assert.Equal(1, quantity08.MegajoulesPerCubicMeterKelvin); Assert.Equal(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin, quantity08.Unit); } @@ -347,131 +365,40 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 BTU/(ft³·°F)", VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit, 4.2)] + [InlineData("en-US", "4.2 cal/(cm³·°C)", VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 J/(m³·°C)", VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 J/(m³·K)", VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, 4.2)] + [InlineData("en-US", "4.2 kcal/(cm³·°C)", VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 kJ/(m³·°C)", VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = VolumetricHeatCapacity.Parse("1 BTU/(ft³·°F)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.BtusPerCubicFootDegreeFahrenheit, BtusPerCubicFootDegreeFahrenheitTolerance); - Assert.Equal(VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumetricHeatCapacity.Parse("1 cal/(cm³·°C)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CaloriesPerCubicCentimeterDegreeCelsius, CaloriesPerCubicCentimeterDegreeCelsiusTolerance); - Assert.Equal(VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumetricHeatCapacity.Parse("1 J/(m³·°C)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.JoulesPerCubicMeterDegreeCelsius, JoulesPerCubicMeterDegreeCelsiusTolerance); - Assert.Equal(VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumetricHeatCapacity.Parse("1 J/(m³·K)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.JoulesPerCubicMeterKelvin, JoulesPerCubicMeterKelvinTolerance); - Assert.Equal(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumetricHeatCapacity.Parse("1 kcal/(cm³·°C)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilocaloriesPerCubicCentimeterDegreeCelsius, KilocaloriesPerCubicCentimeterDegreeCelsiusTolerance); - Assert.Equal(VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumetricHeatCapacity.Parse("1 kJ/(m³·°C)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilojoulesPerCubicMeterDegreeCelsius, KilojoulesPerCubicMeterDegreeCelsiusTolerance); - Assert.Equal(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumetricHeatCapacity.Parse("1 kJ/(m³·K)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.KilojoulesPerCubicMeterKelvin, KilojoulesPerCubicMeterKelvinTolerance); - Assert.Equal(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumetricHeatCapacity.Parse("1 MJ/(m³·°C)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegajoulesPerCubicMeterDegreeCelsius, MegajoulesPerCubicMeterDegreeCelsiusTolerance); - Assert.Equal(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = VolumetricHeatCapacity.Parse("1 MJ/(m³·K)", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MegajoulesPerCubicMeterKelvin, MegajoulesPerCubicMeterKelvinTolerance); - Assert.Equal(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = VolumetricHeatCapacity.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 BTU/(ft³·°F)", VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit, 4.2)] + [InlineData("en-US", "4.2 cal/(cm³·°C)", VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 J/(m³·°C)", VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 J/(m³·K)", VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, 4.2)] + [InlineData("en-US", "4.2 kcal/(cm³·°C)", VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius, 4.2)] + [InlineData("en-US", "4.2 kJ/(m³·°C)", VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(VolumetricHeatCapacity.TryParse("1 BTU/(ft³·°F)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.BtusPerCubicFootDegreeFahrenheit, BtusPerCubicFootDegreeFahrenheitTolerance); - Assert.Equal(VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit, parsed.Unit); - } - - { - Assert.True(VolumetricHeatCapacity.TryParse("1 cal/(cm³·°C)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CaloriesPerCubicCentimeterDegreeCelsius, CaloriesPerCubicCentimeterDegreeCelsiusTolerance); - Assert.Equal(VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius, parsed.Unit); - } - - { - Assert.True(VolumetricHeatCapacity.TryParse("1 J/(m³·°C)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.JoulesPerCubicMeterDegreeCelsius, JoulesPerCubicMeterDegreeCelsiusTolerance); - Assert.Equal(VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius, parsed.Unit); - } - - { - Assert.True(VolumetricHeatCapacity.TryParse("1 J/(m³·K)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.JoulesPerCubicMeterKelvin, JoulesPerCubicMeterKelvinTolerance); - Assert.Equal(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, parsed.Unit); - } - - { - Assert.True(VolumetricHeatCapacity.TryParse("1 kcal/(cm³·°C)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilocaloriesPerCubicCentimeterDegreeCelsius, KilocaloriesPerCubicCentimeterDegreeCelsiusTolerance); - Assert.Equal(VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius, parsed.Unit); - } - - { - Assert.True(VolumetricHeatCapacity.TryParse("1 kJ/(m³·°C)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilojoulesPerCubicMeterDegreeCelsius, KilojoulesPerCubicMeterDegreeCelsiusTolerance); - Assert.Equal(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius, parsed.Unit); - } - - { - Assert.True(VolumetricHeatCapacity.TryParse("1 kJ/(m³·K)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.KilojoulesPerCubicMeterKelvin, KilojoulesPerCubicMeterKelvinTolerance); - Assert.Equal(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin, parsed.Unit); - } - - { - Assert.True(VolumetricHeatCapacity.TryParse("1 MJ/(m³·°C)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegajoulesPerCubicMeterDegreeCelsius, MegajoulesPerCubicMeterDegreeCelsiusTolerance); - Assert.Equal(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius, parsed.Unit); - } - - { - Assert.True(VolumetricHeatCapacity.TryParse("1 MJ/(m³·K)", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MegajoulesPerCubicMeterKelvin, MegajoulesPerCubicMeterKelvinTolerance); - Assert.Equal(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(VolumetricHeatCapacity.TryParse(quantityString, out VolumetricHeatCapacity parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -612,6 +539,35 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Volume Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit, "BTU/(ft³·°F)")] + [InlineData("en-US", VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius, "cal/(cm³·°C)")] + [InlineData("en-US", VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius, "J/(m³·°C)")] + [InlineData("en-US", VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, "J/(m³·K)")] + [InlineData("en-US", VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius, "kcal/(cm³·°C)")] + [InlineData("en-US", VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius, "kJ/(m³·°C)")] + [InlineData("en-US", VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin, "kJ/(m³·K)")] + [InlineData("en-US", VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius, "MJ/(m³·°C)")] + [InlineData("en-US", VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin, "MJ/(m³·K)")] + public void GetAbbreviationForCulture(string culture, VolumetricHeatCapacityUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = VolumetricHeatCapacity.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(VolumetricHeatCapacity.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = VolumetricHeatCapacity.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(VolumetricHeatCapacityUnit unit) @@ -642,6 +598,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); }); } @@ -665,40 +622,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] @@ -744,8 +703,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); @@ -783,34 +740,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1); - Assert.True(v.Equals(VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1), JoulesPerCubicMeterKelvinTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(VolumetricHeatCapacity.Zero, JoulesPerCubicMeterKelvinTolerance, ComparisonType.Relative)); - Assert.True(VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(100).Equals(VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(120), 0.3, ComparisonType.Relative)); - Assert.False(VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(100).Equals(VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(120), 0.1, ComparisonType.Relative)); + VolumetricHeatCapacity joulepercubicmeterkelvin = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1); + Assert.False(joulepercubicmeterkelvin.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1); - Assert.Throws(() => v.Equals(VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1), -1, ComparisonType.Relative)); + VolumetricHeatCapacity joulepercubicmeterkelvin = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1); + Assert.False(joulepercubicmeterkelvin.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - VolumetricHeatCapacity joulepercubicmeterkelvin = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1); - Assert.False(joulepercubicmeterkelvin.Equals(new object())); + var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(firstValue); + var otherQuantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(secondValue); + VolumetricHeatCapacity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - VolumetricHeatCapacity joulepercubicmeterkelvin = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1); - Assert.False(joulepercubicmeterkelvin.Equals(null)); + var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1); + var negativeTolerance = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -829,6 +795,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() { @@ -903,158 +881,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(VolumetricHeatCapacity))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(VolumetricHeatCapacityUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal(VolumetricHeatCapacity.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal(VolumetricHeatCapacity.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal(new {VolumetricHeatCapacity.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 585e90a52a..157e3c9cd7 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/WarpingMomentOfInertiaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/WarpingMomentOfInertiaTestsBase.g.cs @@ -116,7 +116,7 @@ public virtual void Ctor_SIUnitSystem_ReturnsQuantityWithSIUnits() { var quantity = new WarpingMomentOfInertia(value: 1, unitSystem: UnitSystem.SI); Assert.Equal(1, quantity.Value); - Assert.True(quantity.QuantityInfo.UnitInfos.First(x => x.Value == quantity.Unit).BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + Assert.True(quantity.QuantityInfo[quantity.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); } [Fact] @@ -129,15 +129,33 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Fact] public void WarpingMomentOfInertia_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() { + WarpingMomentOfInertiaUnit[] unitsOrderedByName = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); var quantity = new WarpingMomentOfInertia(1, WarpingMomentOfInertiaUnit.MeterToTheSixth); - QuantityInfo quantityInfo = quantity.QuantityInfo; + QuantityInfo quantityInfo = quantity.QuantityInfo; - Assert.Equal(WarpingMomentOfInertia.Zero, quantityInfo.Zero); Assert.Equal("WarpingMomentOfInertia", quantityInfo.Name); + Assert.Equal(WarpingMomentOfInertia.Zero, quantityInfo.Zero); + Assert.Equal(WarpingMomentOfInertia.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(unitsOrderedByName, quantityInfo.Units); + Assert.Equal(unitsOrderedByName, quantityInfo.UnitInfos.Select(x => x.Value)); + Assert.Equal(WarpingMomentOfInertia.Info, quantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); + } + + [Fact] + public void WarpingMomentOfInertiaInfo_CreateWithCustomUnitInfos() + { + WarpingMomentOfInertiaUnit[] expectedUnits = [WarpingMomentOfInertiaUnit.MeterToTheSixth]; - var units = EnumUtils.GetEnumValues().OrderBy(x => x.ToString()).ToArray(); - var unitNames = units.Select(x => x.ToString()); + 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] @@ -156,27 +174,27 @@ public void MeterToTheSixthToWarpingMomentOfInertiaUnits() public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit() { var quantity00 = WarpingMomentOfInertia.From(1, WarpingMomentOfInertiaUnit.CentimeterToTheSixth); - AssertEx.EqualTolerance(1, quantity00.CentimetersToTheSixth, CentimetersToTheSixthTolerance); + Assert.Equal(1, quantity00.CentimetersToTheSixth); Assert.Equal(WarpingMomentOfInertiaUnit.CentimeterToTheSixth, quantity00.Unit); var quantity01 = WarpingMomentOfInertia.From(1, WarpingMomentOfInertiaUnit.DecimeterToTheSixth); - AssertEx.EqualTolerance(1, quantity01.DecimetersToTheSixth, DecimetersToTheSixthTolerance); + Assert.Equal(1, quantity01.DecimetersToTheSixth); Assert.Equal(WarpingMomentOfInertiaUnit.DecimeterToTheSixth, quantity01.Unit); var quantity02 = WarpingMomentOfInertia.From(1, WarpingMomentOfInertiaUnit.FootToTheSixth); - AssertEx.EqualTolerance(1, quantity02.FeetToTheSixth, FeetToTheSixthTolerance); + Assert.Equal(1, quantity02.FeetToTheSixth); Assert.Equal(WarpingMomentOfInertiaUnit.FootToTheSixth, quantity02.Unit); var quantity03 = WarpingMomentOfInertia.From(1, WarpingMomentOfInertiaUnit.InchToTheSixth); - AssertEx.EqualTolerance(1, quantity03.InchesToTheSixth, InchesToTheSixthTolerance); + Assert.Equal(1, quantity03.InchesToTheSixth); Assert.Equal(WarpingMomentOfInertiaUnit.InchToTheSixth, quantity03.Unit); var quantity04 = WarpingMomentOfInertia.From(1, WarpingMomentOfInertiaUnit.MeterToTheSixth); - AssertEx.EqualTolerance(1, quantity04.MetersToTheSixth, MetersToTheSixthTolerance); + Assert.Equal(1, quantity04.MetersToTheSixth); Assert.Equal(WarpingMomentOfInertiaUnit.MeterToTheSixth, quantity04.Unit); var quantity05 = WarpingMomentOfInertia.From(1, WarpingMomentOfInertiaUnit.MillimeterToTheSixth); - AssertEx.EqualTolerance(1, quantity05.MillimetersToTheSixth, MillimetersToTheSixthTolerance); + Assert.Equal(1, quantity05.MillimetersToTheSixth); Assert.Equal(WarpingMomentOfInertiaUnit.MillimeterToTheSixth, quantity05.Unit); } @@ -317,92 +335,34 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() }); } - [Fact] - public void Parse() + [Theory] + [InlineData("en-US", "4.2 cm⁶", WarpingMomentOfInertiaUnit.CentimeterToTheSixth, 4.2)] + [InlineData("en-US", "4.2 dm⁶", WarpingMomentOfInertiaUnit.DecimeterToTheSixth, 4.2)] + [InlineData("en-US", "4.2 ft⁶", WarpingMomentOfInertiaUnit.FootToTheSixth, 4.2)] + [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, decimal expectedValue) { - try - { - var parsed = WarpingMomentOfInertia.Parse("1 cm⁶", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.CentimetersToTheSixth, CentimetersToTheSixthTolerance); - Assert.Equal(WarpingMomentOfInertiaUnit.CentimeterToTheSixth, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = WarpingMomentOfInertia.Parse("1 dm⁶", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.DecimetersToTheSixth, DecimetersToTheSixthTolerance); - Assert.Equal(WarpingMomentOfInertiaUnit.DecimeterToTheSixth, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = WarpingMomentOfInertia.Parse("1 ft⁶", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.FeetToTheSixth, FeetToTheSixthTolerance); - Assert.Equal(WarpingMomentOfInertiaUnit.FootToTheSixth, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = WarpingMomentOfInertia.Parse("1 in⁶", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.InchesToTheSixth, InchesToTheSixthTolerance); - Assert.Equal(WarpingMomentOfInertiaUnit.InchToTheSixth, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = WarpingMomentOfInertia.Parse("1 m⁶", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MetersToTheSixth, MetersToTheSixthTolerance); - Assert.Equal(WarpingMomentOfInertiaUnit.MeterToTheSixth, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - - try - { - var parsed = WarpingMomentOfInertia.Parse("1 mm⁶", CultureInfo.GetCultureInfo("en-US")); - AssertEx.EqualTolerance(1, parsed.MillimetersToTheSixth, MillimetersToTheSixthTolerance); - Assert.Equal(WarpingMomentOfInertiaUnit.MillimeterToTheSixth, parsed.Unit); - } catch (AmbiguousUnitParseException) { /* Some units have the same abbreviations */ } - + using var _ = new CultureScope(culture); + var parsed = WarpingMomentOfInertia.Parse(quantityString); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } - [Fact] - public void TryParse() + [Theory] + [InlineData("en-US", "4.2 cm⁶", WarpingMomentOfInertiaUnit.CentimeterToTheSixth, 4.2)] + [InlineData("en-US", "4.2 dm⁶", WarpingMomentOfInertiaUnit.DecimeterToTheSixth, 4.2)] + [InlineData("en-US", "4.2 ft⁶", WarpingMomentOfInertiaUnit.FootToTheSixth, 4.2)] + [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, decimal expectedValue) { - { - Assert.True(WarpingMomentOfInertia.TryParse("1 cm⁶", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.CentimetersToTheSixth, CentimetersToTheSixthTolerance); - Assert.Equal(WarpingMomentOfInertiaUnit.CentimeterToTheSixth, parsed.Unit); - } - - { - Assert.True(WarpingMomentOfInertia.TryParse("1 dm⁶", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.DecimetersToTheSixth, DecimetersToTheSixthTolerance); - Assert.Equal(WarpingMomentOfInertiaUnit.DecimeterToTheSixth, parsed.Unit); - } - - { - Assert.True(WarpingMomentOfInertia.TryParse("1 ft⁶", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.FeetToTheSixth, FeetToTheSixthTolerance); - Assert.Equal(WarpingMomentOfInertiaUnit.FootToTheSixth, parsed.Unit); - } - - { - Assert.True(WarpingMomentOfInertia.TryParse("1 in⁶", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.InchesToTheSixth, InchesToTheSixthTolerance); - Assert.Equal(WarpingMomentOfInertiaUnit.InchToTheSixth, parsed.Unit); - } - - { - Assert.True(WarpingMomentOfInertia.TryParse("1 m⁶", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MetersToTheSixth, MetersToTheSixthTolerance); - Assert.Equal(WarpingMomentOfInertiaUnit.MeterToTheSixth, parsed.Unit); - } - - { - Assert.True(WarpingMomentOfInertia.TryParse("1 mm⁶", CultureInfo.GetCultureInfo("en-US"), out var parsed)); - AssertEx.EqualTolerance(1, parsed.MillimetersToTheSixth, MillimetersToTheSixthTolerance); - Assert.Equal(WarpingMomentOfInertiaUnit.MillimeterToTheSixth, parsed.Unit); - } - + using var _ = new CultureScope(culture); + Assert.True(WarpingMomentOfInertia.TryParse(quantityString, out WarpingMomentOfInertia parsed)); + Assert.Equal(expectedUnit, parsed.Unit); + Assert.Equal(expectedValue, parsed.Value); } [Theory] @@ -519,6 +479,32 @@ public void TryParseUnit_WithCulture(string culture, string abbreviation, Warpin Assert.Equal(expectedUnit, parsedUnit); } + [Theory] + [InlineData("en-US", WarpingMomentOfInertiaUnit.CentimeterToTheSixth, "cm⁶")] + [InlineData("en-US", WarpingMomentOfInertiaUnit.DecimeterToTheSixth, "dm⁶")] + [InlineData("en-US", WarpingMomentOfInertiaUnit.FootToTheSixth, "ft⁶")] + [InlineData("en-US", WarpingMomentOfInertiaUnit.InchToTheSixth, "in⁶")] + [InlineData("en-US", WarpingMomentOfInertiaUnit.MeterToTheSixth, "m⁶")] + [InlineData("en-US", WarpingMomentOfInertiaUnit.MillimeterToTheSixth, "mm⁶")] + public void GetAbbreviationForCulture(string culture, WarpingMomentOfInertiaUnit unit, string expectedAbbreviation) + { + var defaultAbbreviation = WarpingMomentOfInertia.GetAbbreviation(unit, CultureInfo.GetCultureInfo(culture)); + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + } + + [Fact] + public void GetAbbreviationWithDefaultCulture() + { + Assert.All(WarpingMomentOfInertia.Units, unit => + { + var expectedAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); + + var defaultAbbreviation = WarpingMomentOfInertia.GetAbbreviation(unit); + + Assert.Equal(expectedAbbreviation, defaultAbbreviation); + }); + } + [Theory] [MemberData(nameof(UnitTypes))] public void ToUnit(WarpingMomentOfInertiaUnit unit) @@ -549,6 +535,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); }); } @@ -572,37 +559,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] @@ -648,8 +637,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); @@ -687,34 +674,43 @@ public void Equals_Null_ReturnsFalse() } [Fact] - public void Equals_RelativeTolerance_IsImplemented() + public void EqualsReturnsFalseOnTypeMismatch() { - var v = WarpingMomentOfInertia.FromMetersToTheSixth(1); - Assert.True(v.Equals(WarpingMomentOfInertia.FromMetersToTheSixth(1), MetersToTheSixthTolerance, ComparisonType.Relative)); - Assert.False(v.Equals(WarpingMomentOfInertia.Zero, MetersToTheSixthTolerance, ComparisonType.Relative)); - Assert.True(WarpingMomentOfInertia.FromMetersToTheSixth(100).Equals(WarpingMomentOfInertia.FromMetersToTheSixth(120), 0.3, ComparisonType.Relative)); - Assert.False(WarpingMomentOfInertia.FromMetersToTheSixth(100).Equals(WarpingMomentOfInertia.FromMetersToTheSixth(120), 0.1, ComparisonType.Relative)); + WarpingMomentOfInertia metertothesixth = WarpingMomentOfInertia.FromMetersToTheSixth(1); + Assert.False(metertothesixth.Equals(new object())); } [Fact] - public void Equals_NegativeRelativeTolerance_ThrowsArgumentOutOfRangeException() + public void EqualsReturnsFalseOnNull() { - var v = WarpingMomentOfInertia.FromMetersToTheSixth(1); - Assert.Throws(() => v.Equals(WarpingMomentOfInertia.FromMetersToTheSixth(1), -1, ComparisonType.Relative)); + WarpingMomentOfInertia metertothesixth = WarpingMomentOfInertia.FromMetersToTheSixth(1); + Assert.False(metertothesixth.Equals(null)); } - [Fact] - public void EqualsReturnsFalseOnTypeMismatch() + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_WithTolerance_IsImplemented(double firstValue, double secondValue) { - WarpingMomentOfInertia metertothesixth = WarpingMomentOfInertia.FromMetersToTheSixth(1); - Assert.False(metertothesixth.Equals(new object())); + var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(firstValue); + var otherQuantity = WarpingMomentOfInertia.FromMetersToTheSixth(secondValue); + WarpingMomentOfInertia maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.True(quantity.Equals(otherQuantity, largerTolerance)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); } [Fact] - public void EqualsReturnsFalseOnNull() + public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() { - WarpingMomentOfInertia metertothesixth = WarpingMomentOfInertia.FromMetersToTheSixth(1); - Assert.False(metertothesixth.Equals(null)); + var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1); + var negativeTolerance = WarpingMomentOfInertia.FromMetersToTheSixth(-1); + Assert.Throws(() => quantity.Equals(quantity, negativeTolerance)); } [Fact] @@ -733,6 +729,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() { @@ -801,158 +809,12 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) Assert.Equal(quantity.ToString(format, CultureInfo.CurrentCulture), quantity.ToString(format, null)); } - [Fact] - public void Convert_ToBool_ThrowsInvalidCastException() - { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Throws(() => Convert.ToBoolean(quantity)); - } - - [Fact] - public void Convert_ToByte_EqualsValueAsSameType() - { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal((byte)quantity.Value, Convert.ToByte(quantity)); - } - - [Fact] - public void Convert_ToChar_ThrowsInvalidCastException() - { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Throws(() => Convert.ToChar(quantity)); - } - - [Fact] - public void Convert_ToDateTime_ThrowsInvalidCastException() - { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Throws(() => Convert.ToDateTime(quantity)); - } - - [Fact] - public void Convert_ToDecimal_EqualsValueAsSameType() - { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal((decimal)quantity.Value, Convert.ToDecimal(quantity)); - } - - [Fact] - public void Convert_ToDouble_EqualsValueAsSameType() - { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal((double)quantity.Value, Convert.ToDouble(quantity)); - } - - [Fact] - public void Convert_ToInt16_EqualsValueAsSameType() - { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal((short)quantity.Value, Convert.ToInt16(quantity)); - } - - [Fact] - public void Convert_ToInt32_EqualsValueAsSameType() - { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal((int)quantity.Value, Convert.ToInt32(quantity)); - } - - [Fact] - public void Convert_ToInt64_EqualsValueAsSameType() - { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal((long)quantity.Value, Convert.ToInt64(quantity)); - } - - [Fact] - public void Convert_ToSByte_EqualsValueAsSameType() - { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal((sbyte)quantity.Value, Convert.ToSByte(quantity)); - } - - [Fact] - public void Convert_ToSingle_EqualsValueAsSameType() - { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal((float)quantity.Value, Convert.ToSingle(quantity)); - } - - [Fact] - public void Convert_ToString_EqualsToString() - { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal(quantity.ToString(), Convert.ToString(quantity)); - } - - [Fact] - public void Convert_ToUInt16_EqualsValueAsSameType() - { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal((ushort)quantity.Value, Convert.ToUInt16(quantity)); - } - - [Fact] - public void Convert_ToUInt32_EqualsValueAsSameType() - { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal((uint)quantity.Value, Convert.ToUInt32(quantity)); - } - - [Fact] - public void Convert_ToUInt64_EqualsValueAsSameType() - { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal((ulong)quantity.Value, Convert.ToUInt64(quantity)); - } - - [Fact] - public void Convert_ChangeType_SelfType_EqualsSelf() - { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal(quantity, Convert.ChangeType(quantity, typeof(WarpingMomentOfInertia))); - } - - [Fact] - public void Convert_ChangeType_UnitType_EqualsUnit() - { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal(quantity.Unit, Convert.ChangeType(quantity, typeof(WarpingMomentOfInertiaUnit))); - } - - [Fact] - public void Convert_ChangeType_QuantityInfo_EqualsQuantityInfo() - { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal(WarpingMomentOfInertia.Info, Convert.ChangeType(quantity, typeof(QuantityInfo))); - } - - [Fact] - public void Convert_ChangeType_BaseDimensions_EqualsBaseDimensions() - { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal(WarpingMomentOfInertia.BaseDimensions, Convert.ChangeType(quantity, typeof(BaseDimensions))); - } - - [Fact] - public void Convert_ChangeType_InvalidType_ThrowsInvalidCastException() - { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Throws(() => Convert.ChangeType(quantity, typeof(QuantityFormatter))); - } - - [Fact] - public void Convert_GetTypeCode_Returns_Object() - { - var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(quantity)); - } - [Fact] public void GetHashCode_Equals() { var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal(new {WarpingMomentOfInertia.Info.Name, quantity.Value, quantity.Unit}.GetHashCode(), 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 02da53de1f..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,22 +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() { - var smallError = 1e-5; + 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-5m)), "Using a max difference value should not change that fact."); - Assert.True(Length.FromMeters(1).Equals(Length.FromMeters(1), 0, ComparisonType.Relative), "Integer values have zero difference."); - Assert.True(Length.FromMeters(1).Equals(Length.FromMeters(1), smallError, ComparisonType.Relative), "Using a max difference value should not change that fact."); + Assert.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)); + } - Assert.False(Length.FromMeters(1 + 0.39).Equals(Length.FromMeters(1.39), 0, ComparisonType.Relative), - "Example of floating precision arithmetic that produces slightly different results."); - Assert.True(Length.FromMeters(1 + 0.39).Equals(Length.FromMeters(1.39), smallError, ComparisonType.Relative), "But the difference is very small"); + [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] @@ -66,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 @@ -98,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 @@ -109,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 }); @@ -144,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 new file mode 100644 index 0000000000..022590f784 --- /dev/null +++ b/UnitsNet.Tests/LinearQuantityExtensionsTest.cs @@ -0,0 +1,205 @@ +// 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 LinearQuantityExtensionsTest +{ + [Theory] + [InlineData(2.0, 2.0, 0.1, 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)] + public void Equals_WithTolerance_ReturnsExpectedResult(double value1, double value2, double tolerance, bool expected) + { + var quantity1 = Length.FromMeters(value1); + var quantity2 = Length.FromMeters(value2); + var toleranceQuantity = Length.FromMeters(tolerance); + + var result = quantity1.Equals(quantity2, toleranceQuantity); + + Assert.Equal(expected, result); + } + + [Fact] + public void Equals_WithToleranceAtTheLimit_ReturnsTrue() + { + var quantity = Length.FromMeters(1); + var otherQuantity = Length.FromCentimeters(99); + var tolerance = Length.FromMillimeters(10); + + Assert.Multiple(() => + { + Assert.True(quantity.Equals(otherQuantity, tolerance), "Difference == Tolerance"); + Assert.True(quantity.Equals(otherQuantity, tolerance * 2), "Difference < Tolerance"); + Assert.False(quantity.Equals(otherQuantity, tolerance / 2), "Difference > Tolerance"); + }, + () => + { + Assert.True(otherQuantity.Equals(quantity, tolerance), "Difference == Tolerance"); + Assert.True(otherQuantity.Equals(quantity, tolerance * 2), "Difference < Tolerance"); + Assert.False(otherQuantity.Equals(quantity, tolerance / 2), "Difference > Tolerance"); + }); + } + + [Theory] + [InlineData(2.0, 2.0, 0.1, 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)] + public void Equals_IQuantityWithTolerance_ReturnsExpectedResult(double value1, double value2, double tolerance, bool expected) + { + var quantity1 = Length.FromMeters(value1); + IQuantity quantity2 = Length.FromMeters(value2); + IQuantity toleranceQuantity = Length.FromMeters(tolerance); + + var result = quantity1.Equals(quantity2, toleranceQuantity); + + Assert.Equal(expected, result); + } + + [Fact] + public void Equals_WithNullOther_ReturnsFalse() + { + var quantity = Length.FromMeters(2.0); + Length? otherQuantity = null; + var tolerance = Length.FromMeters(0.1); + + var result = quantity.Equals(otherQuantity, tolerance); + + Assert.False(result); + } + + [Fact] + public void Equals_IQuantity_WithNullOther_ReturnsFalse() + { + var quantity = Length.FromMeters(2.0); + var tolerance = Length.FromMeters(0.1); + + var result = quantity.Equals(null, tolerance); + + Assert.False(result); + } + + [Fact] + public void Equals_WithDifferentTypeTolerance_ThrowsArgumentException() + { + var quantity = Length.FromMeters(2.0); + var other = Length.FromMeters(2.0); + var tolerance = Mass.FromKilograms(0.1); + + Assert.Throws(() => quantity.Equals(other, tolerance)); + } + + [Fact] + public void EqualsAbsolute_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + var quantity = Length.FromMeters(2.0); + var other = Length.FromMeters(2.0); + var tolerance = Length.FromMeters(-0.1); + + Assert.Throws(() => quantity.EqualsAbsolute(other, tolerance)); + } + + [Fact] + public void Sum_WithEmptyCollection_ReturnsZero() + { + Length[] quantities = []; + + Length result = quantities.Sum(); + + Assert.Equal(Length.Zero, result); + } + + [Fact] + public void Sum_WithQuantities_ReturnsExpectedSum() + { + Length[] quantities = [Length.FromMeters(1.0), Length.FromCentimeters(200), Length.FromMeters(3.0)]; + + Length result = quantities.Sum(); + + Assert.Equal(Length.FromMeters(6.0), result); + } + + [Fact] + public void Sum_WithSelector_ReturnsExpectedSum() + { + Length[] quantities = [Length.FromMeters(1.0), Length.FromCentimeters(200), Length.FromMeters(3.0)]; + + Length result = quantities.Sum(length => length); + + Assert.Equal(Length.FromMeters(6.0), result); + } + + [Fact] + public void Sum_WithSelectorAndUnit_ReturnsExpectedSum() + { + Length[] quantities = [Length.FromMeters(1.0), Length.FromCentimeters(200), Length.FromMeters(3.0)]; + + Length result = quantities.Sum(length => length, LengthUnit.Centimeter); + + Assert.Equal(600, result.Value); + Assert.Equal(LengthUnit.Centimeter, result.Unit); + } + + [Fact] + public void Average_WithEmptyCollection_ThrowsInvalidOperationException() + { + Length[] quantities = []; + + Assert.Throws(() => quantities.Average()); + } + + [Fact] + public void Average_WithSelector_ThrowsOnEmptyCollection() + { + Length[] quantities = []; + + Assert.Throws(() => quantities.Average(length => length)); + } + + [Fact] + public void Average_WithSelectorAndUnit_ThrowsOnEmptyCollection() + { + Length[] quantities = []; + + Assert.Throws(() => quantities.Average(length => length, LengthUnit.Centimeter)); + } + + [Fact] + public void Average_WithQuantities_ReturnsExpectedAverage() + { + Length[] quantities = [Length.FromMeters(1.0), Length.FromMeters(2.0), Length.FromMeters(3.0)]; + + Length result = quantities.Average(); + + Assert.Equal(Length.FromMeters(2.0), result); + } + + [Fact] + public void Average_WithSelector_ReturnsExpectedAverage() + { + Length[] quantities = [Length.FromMeters(1.0), Length.FromCentimeters(200), Length.FromMeters(3.0)]; + + Length result = quantities.Average(length => length); + + Assert.Equal(Length.FromMeters(2.0), result); + } + + [Fact] + public void Average_WithSelectorAndUnit_ReturnsExpectedAverage() + { + Length[] quantities = [Length.FromMeters(1.0), Length.FromCentimeters(200), Length.FromMeters(3.0)]; + + Length result = quantities.Average(length => length, LengthUnit.Centimeter); + + Assert.Equal(200, result.Value); + Assert.Equal(LengthUnit.Centimeter, result.Unit); + } +} diff --git a/UnitsNet.Tests/LogarithmicQuantityExtensionsTest.cs b/UnitsNet.Tests/LogarithmicQuantityExtensionsTest.cs new file mode 100644 index 0000000000..ea60cd6828 --- /dev/null +++ b/UnitsNet.Tests/LogarithmicQuantityExtensionsTest.cs @@ -0,0 +1,623 @@ +// 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 UnitsNet.Units; +using Xunit; + +namespace UnitsNet.Tests; + +public class LogarithmicQuantityExtensionsTest +{ + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_TQuantity_TOther_TTolerance_ComparesInLinearSpace(double firstValue, double secondValue) + { + var quantity = PowerRatio.FromDecibelWatts(firstValue); + var otherQuantity = PowerRatio.FromDecibelWatts(secondValue); + PowerRatio maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.False(quantity.Equals(otherQuantity, smallerTolerance)); + // note: it's currently not possible to test this due to the rounding error from (quantity - otherQuantity) + // Assert.True(quantity.Equals(otherQuantity, maxTolerance)); + } + + [Theory] + [InlineData(1, 2)] + [InlineData(100, 110)] + [InlineData(100, 90)] + public void Equals_TQuantity_IQuantity_IQuantity_ComparesInLinearSpace(double firstValue, double secondValue) + { + var quantity = PowerRatio.FromDecibelWatts(firstValue); + var otherQuantity = PowerRatio.FromDecibelWatts(secondValue); + PowerRatio maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; + 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)); + Assert.False(quantity.Equals((IQuantity)otherQuantity, smallerTolerance)); + // note: it's currently not possible to test this due to the rounding error from (quantity - otherQuantity) + // Assert.True(quantity.Equals((IQuantity)otherQuantity, maxTolerance)); + } + + [Fact] + public void Equals_NullQuantity_ReturnsFalse() + { + var quantity = PowerRatio.FromDecibelWatts(1); + var tolerance = PowerRatio.FromDecibelWatts(1); + Assert.False(quantity.Equals(null, tolerance)); + } + + [Fact] + public void Equals_NullQuantity_And_NullTolerance_ReturnsFalse() + { + var quantity = PowerRatio.FromDecibelWatts(1); + var tolerance = PowerRatio.FromDecibelWatts(1); + Assert.False(quantity.Equals(null, tolerance)); + } + + [Fact] + public void Equals_NullQuantity_And_AnotherToleranceType_ReturnsFalse() + { + var quantity = PowerRatio.FromDecibelWatts(1); + var tolerance = AmplitudeRatio.FromDecibelVolts(1); + Assert.False(quantity.Equals(null, tolerance)); + } + + [Fact] + public void Equals_IQuantity_And_AnotherToleranceType_ThrowsArgumentException() + { + var quantity = PowerRatio.FromDecibelWatts(1); + var tolerance = AmplitudeRatio.FromDecibelVolts(1); + Assert.Throws(() => quantity.Equals(quantity, tolerance)); + } + + [Fact] + public void Equals_TQuantity_TQuantity_WithUnknownUnits_ThrowsUnitNotFoundException() + { + var quantity = PowerRatio.FromDecibelWatts(1); + var invalidQuantity = new PowerRatio(1, (PowerRatioUnit)(-1)); + Assert.Throws(() => invalidQuantity.Equals(quantity, quantity)); + Assert.Throws(() => quantity.Equals(invalidQuantity, quantity)); + Assert.Throws(() => quantity.Equals(quantity, invalidQuantity)); + } + + [Fact] + public void Equals_IQuantity_IQuantity_WithUnknownUnits_ThrowsUnitNotFoundException() + { + var quantity = PowerRatio.FromDecibelWatts(1); + var invalidQuantity = new PowerRatio(1, (PowerRatioUnit)(-1)); + Assert.Throws(() => invalidQuantity.Equals((IQuantity)quantity, quantity)); + Assert.Throws(() => quantity.Equals((IQuantity)invalidQuantity, quantity)); + Assert.Throws(() => quantity.Equals((IQuantity)quantity, invalidQuantity)); + } + + [Fact] + public void Equals_WithNegativeTolerance_DoesNotThrowArgumentOutOfRangeException() + { + // note: unlike with vector quantities- a small tolerance maybe positive in one unit and negative in another + var quantity = PowerRatio.FromDecibelWatts(1); + var negativeTolerance = PowerRatio.FromDecibelWatts(-1); + Assert.True(quantity.Equals(quantity, negativeTolerance)); + } + + [Fact] + public void Sum_ThrowsOnEmptyCollection() + { + PowerRatio[] quantities = []; + + Assert.Throws(() => quantities.Sum()); + } + + [Fact] + public void Sum_WithSelector_ThrowsOnEmptyCollection() + { + PowerRatio[] quantities = []; + + Assert.Throws(() => quantities.Sum(x => x)); + } + + [Fact] + public void Sum_WithUnit_ThrowsOnEmptyCollection() + { + PowerRatio[] quantities = []; + + Assert.Throws(() => quantities.Sum(PowerRatioUnit.DecibelWatt)); + } + + [Fact] + public void Sum_WithSelectorAndUnit_ThrowsOnEmptyCollection() + { + PowerRatio[] quantities = []; + + Assert.Throws(() => quantities.Sum(x => x, PowerRatioUnit.DecibelWatt)); + } + + [Fact] + public void Sum_WithNullSequence_ThrowsArgumentNullException() + { + PowerRatio[] quantities = null!; + + Assert.Throws(() => quantities.Sum()); + } + + [Fact] + public void Sum_WithNullSequenceAndUnit_ThrowsArgumentNullException() + { + PowerRatio[] quantities = null!; + + Assert.Throws(() => quantities.Sum(PowerRatioUnit.DecibelWatt)); + } + + [Fact] + public void Sum_WithNullSelector_ThrowsArgumentNullException() + { + PowerRatio[] quantities = null!; + + Assert.Throws(() => quantities.Sum(x => x, PowerRatioUnit.DecibelWatt)); + } + + [Theory] + [InlineData(0, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(1, PowerRatioUnit.DecibelWatt)] + [InlineData(double.NaN, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(double.PositiveInfinity, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(double.NegativeInfinity, PowerRatioUnit.DecibelMilliwatt)] + public void Sum_SingleQuantity_ReturnsCorrectSum(double value, PowerRatioUnit unit) + { + var quantity = new PowerRatio(value, unit); + IEnumerable quantities = new List { quantity }; + + PowerRatio result = quantities.Sum(); + + Assert.Equal(quantity.Value, result.Value); + Assert.Equal(quantity.Unit, result.Unit); + } + + [Theory] + [InlineData(0, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(1, PowerRatioUnit.DecibelWatt)] + [InlineData(double.NaN, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(double.PositiveInfinity, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(double.NegativeInfinity, PowerRatioUnit.DecibelMilliwatt)] + public void Sum_SingleQuantity_WithSelector_ReturnsCorrectSum(double value, PowerRatioUnit unit) + { + var quantity = new PowerRatio(value, unit); + IEnumerable quantities = new List { quantity }; + + PowerRatio result = quantities.Sum(x => x); + + Assert.Equal(quantity.Value, result.Value); + Assert.Equal(quantity.Unit, result.Unit); + } + + [Theory] + [InlineData(0, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(0, PowerRatioUnit.DecibelWatt, 1, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, -1, PowerRatioUnit.DecibelWatt)] + [InlineData(2, PowerRatioUnit.DecibelMilliwatt, -10, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(2, PowerRatioUnit.DecibelMilliwatt, -2, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(10, PowerRatioUnit.DecibelWatt, 100, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(-10, PowerRatioUnit.DecibelMilliwatt, 20, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(double.NaN, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(double.PositiveInfinity, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(double.NegativeInfinity, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, double.NaN, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, double.PositiveInfinity, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, double.NegativeInfinity, PowerRatioUnit.DecibelWatt)] + public void Sum_ReturnsCorrectSum(double value1, PowerRatioUnit unit1, double value2, PowerRatioUnit unit2) + { + var quantity1 = new PowerRatio(value1, unit1); + var quantity2 = new PowerRatio(value2, unit2); + IEnumerable quantities = new List { quantity1, quantity2 }; + PowerRatio expectedValue = quantity1 + quantity2; + + PowerRatio result = quantities.Sum(); + + Assert.Equal(expectedValue, result); + Assert.Equal(unit1, result.Unit); + } + + [Theory] + [InlineData(0, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(0, PowerRatioUnit.DecibelWatt, 1, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, -1, PowerRatioUnit.DecibelWatt)] + [InlineData(2, PowerRatioUnit.DecibelMilliwatt, -10, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(2, PowerRatioUnit.DecibelMilliwatt, -2, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(10, PowerRatioUnit.DecibelWatt, 100, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(-10, PowerRatioUnit.DecibelMilliwatt, 20, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(double.NaN, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(double.PositiveInfinity, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(double.NegativeInfinity, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, double.NaN, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, double.PositiveInfinity, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, double.NegativeInfinity, PowerRatioUnit.DecibelWatt)] + public void Sum_WithSelector_ReturnsCorrectSum(double value1, PowerRatioUnit unit1, double value2, PowerRatioUnit unit2) + { + var quantity1 = new PowerRatio(value1, unit1); + var quantity2 = new PowerRatio(value2, unit2); + IEnumerable quantities = new List { quantity1, quantity2 }; + PowerRatio expectedValue = quantity1 + quantity2; + + PowerRatio result = quantities.Sum(x => x); + + Assert.Equal(expectedValue, result); + Assert.Equal(unit1, result.Unit); + } + + [Theory] + [InlineData(0, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(0, PowerRatioUnit.DecibelWatt, 1, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, -1, PowerRatioUnit.DecibelWatt)] + [InlineData(2, PowerRatioUnit.DecibelMilliwatt, -10, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(2, PowerRatioUnit.DecibelMilliwatt, -2, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(10, PowerRatioUnit.DecibelWatt, 100, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(-10, PowerRatioUnit.DecibelMilliwatt, 20, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(double.NaN, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(double.PositiveInfinity, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(double.NegativeInfinity, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, double.NaN, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, double.PositiveInfinity, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, double.NegativeInfinity, PowerRatioUnit.DecibelWatt)] + public void Sum_WithSelectorAndUnit_ReturnsCorrectSum(double value1, PowerRatioUnit unit1, double value2, PowerRatioUnit unit2) + { + var quantity1 = new PowerRatio(value1, unit1); + var quantity2 = new PowerRatio(value2, unit2); + IEnumerable quantities = new List { quantity1, quantity2 }; + PowerRatio expectedValue = quantity1 + quantity2; + + PowerRatio result = quantities.Sum(x => x, unit1); + + Assert.Equal(expectedValue, result); + Assert.Equal(unit1, result.Unit); + } + + [Fact] + public void ArithmeticMean_ThrowsOnEmptyCollection() + { + PowerRatio[] quantities = []; + + Assert.Throws(() => quantities.ArithmeticMean(15)); + } + + [Fact] + public void ArithmeticMean_WithSelector_ThrowsOnEmptyCollection() + { + PowerRatio[] quantities = []; + + Assert.Throws(() => quantities.ArithmeticMean(x => x)); + } + + [Fact] + public void ArithmeticMean_WithSelectorAndUnit_ThrowsOnEmptyCollection() + { + PowerRatio[] quantities = []; + + Assert.Throws(() => quantities.ArithmeticMean(x => x, PowerRatioUnit.DecibelWatt)); + } + + [Fact] + public void ArithmeticMean_WithNullSequence_ThrowsArgumentNullException() + { + PowerRatio[] quantities = null!; + + Assert.Throws(() => quantities.ArithmeticMean(15)); + } + + [Fact] + public void ArithmeticMean_WithNullSequenceAndUnit_ThrowsArgumentNullException() + { + PowerRatio[] quantities = null!; + + Assert.Throws(() => quantities.ArithmeticMean(PowerRatioUnit.DecibelWatt, 15)); + } + + [Fact] + public void ArithmeticMean_WithNullSelector_ThrowsArgumentNullException() + { + PowerRatio[] quantities = null!; + + Assert.Throws(() => quantities.ArithmeticMean(x => x, PowerRatioUnit.DecibelWatt)); + } + + [Theory] + [InlineData(0, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(1, PowerRatioUnit.DecibelWatt)] + [InlineData(double.NaN, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(double.PositiveInfinity, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(double.NegativeInfinity, PowerRatioUnit.DecibelMilliwatt)] + public void ArithmeticMean_SingleQuantity_ReturnsCorrectMean(double value, PowerRatioUnit unit) + { + var quantity = new PowerRatio(value, unit); + IEnumerable quantities = new List { quantity }; + + PowerRatio result = quantities.ArithmeticMean(15); + + Assert.Equal(quantity.Value, result.Value); + Assert.Equal(quantity.Unit, result.Unit); + } + + [Theory] + [InlineData(0, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(1, PowerRatioUnit.DecibelWatt)] + [InlineData(double.NaN, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(double.PositiveInfinity, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(double.NegativeInfinity, PowerRatioUnit.DecibelMilliwatt)] + public void ArithmeticMean_SingleQuantity_WithSelector_ReturnsCorrectMean(double value, PowerRatioUnit unit) + { + var quantity = new PowerRatio(value, unit); + IEnumerable quantities = new List { quantity }; + + PowerRatio result = quantities.ArithmeticMean(x => x); + + Assert.Equal(quantity.Value, result.Value); + Assert.Equal(quantity.Unit, result.Unit); + } + + [Theory] + [InlineData(0, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(0, PowerRatioUnit.DecibelWatt, 1, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, -1, PowerRatioUnit.DecibelWatt)] + [InlineData(2, PowerRatioUnit.DecibelMilliwatt, -10, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(2, PowerRatioUnit.DecibelMilliwatt, -2, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(10, PowerRatioUnit.DecibelWatt, 100, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(-10, PowerRatioUnit.DecibelMilliwatt, 20, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(double.NaN, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(double.PositiveInfinity, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(double.NegativeInfinity, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, double.NaN, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, double.PositiveInfinity, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, double.NegativeInfinity, PowerRatioUnit.DecibelWatt)] + public void ArithmeticMean_ReturnsCorrectMean(double value1, PowerRatioUnit unit1, double value2, PowerRatioUnit unit2) + { + var quantity1 = new PowerRatio(value1, unit1); + var quantity2 = new PowerRatio(value2, unit2); + IEnumerable quantities = new List { quantity1, quantity2 }; + QuantityValue scalingFactor = PowerRatio.LogarithmicScalingFactor; + QuantityValue expectedValue = + ((quantity1.Value.ToLinearSpace(scalingFactor) + quantity2.As(unit1).ToLinearSpace(scalingFactor)) / 2).ToLogSpace(scalingFactor); + + PowerRatio result = quantities.ArithmeticMean(15); + + Assert.Equal(expectedValue, result.Value); + Assert.Equal(unit1, result.Unit); + } + + [Theory] + [InlineData(0, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(0, PowerRatioUnit.DecibelWatt, 1, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, -1, PowerRatioUnit.DecibelWatt)] + [InlineData(2, PowerRatioUnit.DecibelMilliwatt, -10, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(2, PowerRatioUnit.DecibelMilliwatt, -2, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(10, PowerRatioUnit.DecibelWatt, 100, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(-10, PowerRatioUnit.DecibelMilliwatt, 20, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(double.NaN, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(double.PositiveInfinity, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(double.NegativeInfinity, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, double.NaN, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, double.PositiveInfinity, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, double.NegativeInfinity, PowerRatioUnit.DecibelWatt)] + public void ArithmeticMean_WithSelector_ReturnsCorrectMean(double value1, PowerRatioUnit unit1, double value2, PowerRatioUnit unit2) + { + var quantity1 = new PowerRatio(value1, unit1); + var quantity2 = new PowerRatio(value2, unit2); + IEnumerable quantities = new List { quantity1, quantity2 }; + 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); + Assert.Equal(unit1, result.Unit); + } + + [Theory] + [InlineData(0, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(0, PowerRatioUnit.DecibelWatt, 1, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, -1, PowerRatioUnit.DecibelWatt)] + [InlineData(2, PowerRatioUnit.DecibelMilliwatt, -10, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(2, PowerRatioUnit.DecibelMilliwatt, -2, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(10, PowerRatioUnit.DecibelWatt, 100, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(-10, PowerRatioUnit.DecibelMilliwatt, 20, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(double.NaN, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(double.PositiveInfinity, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(double.NegativeInfinity, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, double.NaN, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, double.PositiveInfinity, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, double.NegativeInfinity, PowerRatioUnit.DecibelWatt)] + public void ArithmeticMean_WithSelectorAndUnit_ReturnsCorrectMean(double value1, PowerRatioUnit unit1, double value2, PowerRatioUnit unit2) + { + var quantity1 = new PowerRatio(value1, unit1); + var quantity2 = new PowerRatio(value2, unit2); + IEnumerable quantities = new List { quantity1, quantity2 }; + 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); + Assert.Equal(unit1, result.Unit); + } + + [Fact] + public void GeometricMean_ThrowsOnEmptyCollection() + { + PowerRatio[] quantities = []; + + Assert.Throws(() => quantities.GeometricMean()); + } + + [Fact] + public void GeometricMean_WithSelector_ThrowsOnEmptyCollection() + { + PowerRatio[] quantities = []; + + Assert.Throws(() => quantities.GeometricMean(x => x)); + } + + [Fact] + public void GeometricMean_WithUnitAndSelector_ThrowsOnEmptyCollection() + { + PowerRatio[] quantities = []; + + Assert.Throws(() => quantities.GeometricMean(x => x, PowerRatioUnit.DecibelWatt)); + } + + [Fact] + public void GeometricMean_WithNullSequence_ThrowsArgumentNullException() + { + PowerRatio[] quantities = null!; + + Assert.Throws(() => quantities.GeometricMean()); + } + + [Fact] + public void GeometricMean_WithNullSequenceAndUnit_ThrowsArgumentNullException() + { + PowerRatio[] quantities = null!; + + Assert.Throws(() => quantities.GeometricMean(PowerRatioUnit.DecibelWatt)); + } + + [Fact] + public void GeometricMean_WithNullSelector_ThrowsArgumentNullException() + { + PowerRatio[] quantities = null!; + + Assert.Throws(() => quantities.GeometricMean(x => x, PowerRatioUnit.DecibelWatt)); + } + + [Theory] + [InlineData(0, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(1, PowerRatioUnit.DecibelWatt)] + [InlineData(double.NaN, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(double.PositiveInfinity, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(double.NegativeInfinity, PowerRatioUnit.DecibelMilliwatt)] + public void GeometricMean_SingleQuantity_ReturnsCorrectMean(double value, PowerRatioUnit unit) + { + var quantity = new PowerRatio(value, unit); + IEnumerable quantities = new List { quantity }; + + PowerRatio result = quantities.GeometricMean(); + + Assert.Equal(quantity.Value, result.Value); + Assert.Equal(quantity.Unit, result.Unit); + } + + [Theory] + [InlineData(0, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(1, PowerRatioUnit.DecibelWatt)] + [InlineData(double.NaN, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(double.PositiveInfinity, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(double.NegativeInfinity, PowerRatioUnit.DecibelMilliwatt)] + public void GeometricMean_SingleQuantity_WithSelector_ReturnsCorrectMean(double value, PowerRatioUnit unit) + { + var quantity = new PowerRatio(value, unit); + IEnumerable quantities = new List { quantity }; + + PowerRatio result = quantities.GeometricMean(x => x); + + Assert.Equal(quantity.Value, result.Value); + Assert.Equal(quantity.Unit, result.Unit); + } + + [Theory] + [InlineData(0, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(0, PowerRatioUnit.DecibelWatt, 1, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, -1, PowerRatioUnit.DecibelWatt)] + [InlineData(2, PowerRatioUnit.DecibelMilliwatt, -10, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(2, PowerRatioUnit.DecibelMilliwatt, -2, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(10, PowerRatioUnit.DecibelWatt, 100, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(-10, PowerRatioUnit.DecibelMilliwatt, 20, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(double.NaN, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(double.PositiveInfinity, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(double.NegativeInfinity, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, double.NaN, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, double.PositiveInfinity, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, double.NegativeInfinity, PowerRatioUnit.DecibelWatt)] + public void GeometricMean_ReturnsCorrectMean(double value1, PowerRatioUnit unit1, double value2, PowerRatioUnit unit2) + { + var quantity1 = new PowerRatio(value1, unit1); + var quantity2 = new PowerRatio(value2, unit2); + IEnumerable quantities = new List { quantity1, quantity2 }; + var expectedValue = QuantityValue.RootN(quantity1.Value + quantity2.As(unit1), 2); + + PowerRatio result = quantities.GeometricMean(); + + Assert.Equal(expectedValue, result.Value); + Assert.Equal(unit1, result.Unit); + } + + [Theory] + [InlineData(0, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(0, PowerRatioUnit.DecibelWatt, 1, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, -1, PowerRatioUnit.DecibelWatt)] + [InlineData(2, PowerRatioUnit.DecibelMilliwatt, -10, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(2, PowerRatioUnit.DecibelMilliwatt, -2, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(10, PowerRatioUnit.DecibelWatt, 100, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(-10, PowerRatioUnit.DecibelMilliwatt, 20, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(double.NaN, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(double.PositiveInfinity, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(double.NegativeInfinity, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, double.NaN, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, double.PositiveInfinity, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, double.NegativeInfinity, PowerRatioUnit.DecibelWatt)] + public void GeometricMean_WithSelector_ReturnsCorrectMean(double value1, PowerRatioUnit unit1, double value2, PowerRatioUnit unit2) + { + var quantity1 = new PowerRatio(value1, unit1); + var quantity2 = new PowerRatio(value2, unit2); + IEnumerable quantities = new List { quantity1, quantity2 }; + var expectedValue = QuantityValue.RootN(quantity1.Value + quantity2.As(unit1), 2); + + PowerRatio result = quantities.GeometricMean(x => x); + + Assert.Equal(expectedValue, result.Value); + Assert.Equal(unit1, result.Unit); + } + + [Theory] + [InlineData(0, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(0, PowerRatioUnit.DecibelWatt, 1, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, -1, PowerRatioUnit.DecibelWatt)] + [InlineData(2, PowerRatioUnit.DecibelMilliwatt, -10, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(2, PowerRatioUnit.DecibelMilliwatt, -2, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(10, PowerRatioUnit.DecibelWatt, 100, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(-10, PowerRatioUnit.DecibelMilliwatt, 20, PowerRatioUnit.DecibelMilliwatt)] + [InlineData(double.NaN, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(double.PositiveInfinity, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(double.NegativeInfinity, PowerRatioUnit.DecibelMilliwatt, 1, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, double.NaN, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, double.PositiveInfinity, PowerRatioUnit.DecibelWatt)] + [InlineData(1, PowerRatioUnit.DecibelMilliwatt, double.NegativeInfinity, PowerRatioUnit.DecibelWatt)] + public void GeometricMean_WithUnitAndSelector_ReturnsCorrectMean(double value1, PowerRatioUnit unit1, double value2, PowerRatioUnit unit2) + { + var quantity1 = new PowerRatio(value1, unit1); + var quantity2 = new PowerRatio(value2, unit2); + IEnumerable quantities = new List { quantity1, quantity2 }; + var expectedValue = QuantityValue.RootN(quantity1.Value + quantity2.As(unit1), 2); + + PowerRatio result = quantities.GeometricMean(x => x, unit1); + + 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..e6ecb74ab8 --- /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.Provider.DefaultConversions; + + 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.Provider.DefaultConversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.QuantityInfoLookup; + + 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.Provider.DefaultConversions; + + IEnumerable conversions = UnitsNetSetup.Default.QuantityInfoLookup.GetQuantityConversions(conversionMappings); + + Assert.Empty(conversions.GetConversionFunctions(ConversionCachingMode.None, reduceConstants)); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void BaseOnlyCaching_ReturnsBaseUnitConversions(bool reduceConstants) + { + IReadOnlyCollection conversionMappings = Quantity.Provider.DefaultConversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.QuantityInfoLookup; + 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(toQuantityInfo.UnitInfos.GetUnitInfosFor(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.Provider.DefaultConversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.QuantityInfoLookup; + 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.Provider.DefaultConversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.QuantityInfoLookup; + 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.Provider.DefaultConversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.QuantityInfoLookup; + 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.Provider.DefaultConversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.QuantityInfoLookup; + 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.Provider.DefaultConversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.QuantityInfoLookup; + 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.Provider.DefaultConversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.QuantityInfoLookup; + 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.Provider.DefaultConversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.QuantityInfoLookup; + 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.Provider.DefaultConversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.QuantityInfoLookup; + 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.Provider.DefaultConversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.QuantityInfoLookup; + 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.Provider.DefaultConversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.QuantityInfoLookup; + 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.Provider.DefaultConversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.QuantityInfoLookup; + 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.Provider.DefaultConversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.QuantityInfoLookup; + 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.QuantityInfoLookup.GetQuantityConversions(Quantity.Provider.DefaultConversions); + + // 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.QuantityInfoLookup.GetQuantityConversions(Quantity.Provider.DefaultConversions); + 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.QuantityInfoLookup.GetQuantityConversions(Quantity.Provider.DefaultConversions); + 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.QuantityInfoLookup; + IEnumerable defaultConversionMappings = Quantity.Provider.DefaultConversions; + 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.QuantityInfoLookup; + IEnumerable defaultConversionMappings = Quantity.Provider.DefaultConversions; + 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.Provider.DefaultConversions; + // 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.QuantityInfoLookup; + IReadOnlyCollection conversionMappings = Quantity.Provider.DefaultConversions; + 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.Provider.DefaultConversions; + // 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.Provider.DefaultConversions; + // 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/QuantityFormatterTests.cs b/UnitsNet.Tests/QuantityFormatterTests.cs index 721ccaa966..4e4ffe7fe8 100644 --- a/UnitsNet.Tests/QuantityFormatterTests.cs +++ b/UnitsNet.Tests/QuantityFormatterTests.cs @@ -3,6 +3,7 @@ using System; using System.Globalization; +using UnitsNet.Tests.Helpers; using Xunit; namespace UnitsNet.Tests @@ -95,7 +96,7 @@ public static void StandardNumericFormatStrings_Equals_ValueWithFormatStringAndA var length = Length.FromMeters(123456789.987654321); var expected = string.Format(CultureInfo.CurrentCulture, $"{{0:{format}}} {{1:a}}", length.Value, length); - Assert.Equal(expected, QuantityFormatter.Format(length, format)); + Assert.Equal(expected, QuantityFormatter.Default.Format(length, format)); } [Theory] @@ -140,9 +141,9 @@ public static void StandardNumericFormatStrings_Equals_ValueWithFormatStringAndA public static void Format_WithUnsupportedFormatString_ThrowsFormatException(string format) { var length = Length.FromMeters(123456789.987654321); - Assert.Throws(() => QuantityFormatter.Format(length, format)); + Assert.Throws(() => QuantityFormatter.Default.Format(length, format)); } - + [Fact] public static void StandardNumericFormatStringsAsPartOfLongerFormatStringsWork() { @@ -173,7 +174,27 @@ public static void CustomNumericFormatStrings_Equals_ValueWithFormatStringAndAbb var length = Length.FromMeters(123456789.987654321); var expected = string.Format(CultureInfo.CurrentCulture, $"{{0:{format}}} {{1:a}}", length.Value, length); - Assert.Equal(expected, QuantityFormatter.Format(length, format)); + Assert.Equal(expected, QuantityFormatter.Default.Format(length, format)); + } + + [Fact] + public void Format_WithoutFormatParameter_FormatsWithGeneralFormatWithCurrentCulture() + { + using var cultureScope = new CultureScope(CultureInfo.InvariantCulture); + var length = Length.FromMeters(123.321); + var expected = "123.321 m"; + var actual = QuantityFormatter.Default.Format(length); + Assert.Equal(expected, actual); + } + + [Fact] + public void Format_WithFormatParameter_FormatsWithCurrentCulture() + { + using var cultureScope = new CultureScope(CultureInfo.InvariantCulture); + var length = Length.FromMeters(123.321); + var expected = "123.321 m"; + var actual = QuantityFormatter.Format(length, "G"); + Assert.Equal(expected, actual); } } } diff --git a/UnitsNet.Tests/QuantityIConvertibleTests.cs b/UnitsNet.Tests/QuantityIConvertibleTests.cs deleted file mode 100644 index a5949444c9..0000000000 --- a/UnitsNet.Tests/QuantityIConvertibleTests.cs +++ /dev/null @@ -1,180 +0,0 @@ -using System; -using System.Globalization; -using UnitsNet.Units; -using Xunit; - -namespace UnitsNet.Tests -{ - public class QuantityIConvertibleTests - { - private static Length _length = Length.FromMeters(3.0); - private static readonly IConvertible LengthAsIConvertible = Length.FromMeters(3.0); - - [Fact] - public void GetTypeCodeTest() - { - Assert.Equal(TypeCode.Object, LengthAsIConvertible.GetTypeCode()); - Assert.Equal(TypeCode.Object, Convert.GetTypeCode(_length)); - } - - [Fact] - public void ToBooleanTest() - { - Assert.Throws(() => LengthAsIConvertible.ToBoolean(null)); - Assert.Throws(() => Convert.ToBoolean(_length)); - Assert.Throws(() => Convert.ChangeType(_length, typeof(bool))); - } - - [Fact] - public void ToByteTest() - { - byte expected = 3; - Assert.Equal(expected, LengthAsIConvertible.ToByte(null)); - Assert.Equal(expected, Convert.ToByte(_length)); - Assert.Equal(expected, Convert.ChangeType(_length, typeof(byte))); - } - - [Fact] - public void ToCharTest() - { - Assert.Throws(() => LengthAsIConvertible.ToChar(null)); - Assert.Throws(() => Convert.ToChar(_length)); - Assert.Throws(() => Convert.ChangeType(_length, typeof(char))); - } - - [Fact] - public void ToDateTimeTest() - { - Assert.Throws(() => LengthAsIConvertible.ToDateTime(null)); - Assert.Throws(() => Convert.ToDateTime(_length)); - Assert.Throws(() => Convert.ChangeType(_length, typeof(DateTime))); - } - - [Fact] - public void ToDecimalTest() - { - decimal expected = 3; - Assert.Equal(expected, LengthAsIConvertible.ToDecimal(null)); - Assert.Equal(expected, Convert.ToDecimal(_length)); - Assert.Equal(expected, Convert.ChangeType(_length, typeof(decimal))); - } - - [Fact] - public void ToDoubleTest() - { - double expected = 3.0; - Assert.Equal(expected, LengthAsIConvertible.ToDouble(null)); - Assert.Equal(expected, Convert.ToDouble(_length)); - Assert.Equal(expected, Convert.ChangeType(_length, typeof(double))); - } - - [Fact] - public void ToInt16Test() - { - short expected = 3; - Assert.Equal(expected, LengthAsIConvertible.ToInt16(null)); - Assert.Equal(expected, Convert.ToInt16(_length)); - Assert.Equal(expected, Convert.ChangeType(_length, typeof(short))); - } - - [Fact] - public void ToInt32Test() - { - int expected = 3; - Assert.Equal(expected, LengthAsIConvertible.ToInt32(null)); - Assert.Equal(expected, Convert.ToInt32(_length)); - Assert.Equal(expected, Convert.ChangeType(_length, typeof(int))); - } - - [Fact] - public void ToInt64Test() - { - long expected = 3; - Assert.Equal(expected, LengthAsIConvertible.ToInt64(null)); - Assert.Equal(expected, Convert.ToInt64(_length)); - Assert.Equal(expected, Convert.ChangeType(_length, typeof(long))); - } - - [Fact] - public void ToSByteTest() - { - sbyte expected = 3; - Assert.Equal(expected, LengthAsIConvertible.ToSByte(null)); - Assert.Equal(expected, Convert.ToSByte(_length)); - Assert.Equal(expected, Convert.ChangeType(_length, typeof(sbyte))); - } - - [Fact] - public void ToSingleTest() - { - float expected = 3; - Assert.Equal(expected, LengthAsIConvertible.ToSingle(null)); - Assert.Equal(expected, Convert.ToSingle(_length)); - Assert.Equal(expected, Convert.ChangeType(_length, typeof(float))); - } - - [Fact] - public void ToStringTest() - { - string expected = _length.ToString(CultureInfo.CurrentCulture); - Assert.Equal(expected, LengthAsIConvertible.ToString(CultureInfo.CurrentCulture)); - Assert.Equal(expected, Convert.ToString(_length, CultureInfo.CurrentCulture)); - Assert.Equal(expected, Convert.ChangeType(_length, typeof(string), CultureInfo.CurrentCulture)); - } - - [Fact] - public void ToTypeTest() - { - // Same quantity type - Assert.Equal(_length, LengthAsIConvertible.ToType(typeof(Length), null)); - Assert.Equal(_length, Convert.ChangeType(_length, typeof(Length))); - - // Same unit type - Assert.Equal(_length.Unit, LengthAsIConvertible.ToType(typeof(LengthUnit), null)); - Assert.Equal(_length.Unit, Convert.ChangeType(_length, typeof(LengthUnit))); - - // Different type - Assert.Throws(() => LengthAsIConvertible.ToType(typeof(Duration), null)); - Assert.Throws(() => Convert.ChangeType(_length, typeof(Duration))); - - // Different unit type - Assert.Throws(() => LengthAsIConvertible.ToType(typeof(DurationUnit), null)); - Assert.Throws(() => Convert.ChangeType(_length, typeof(DurationUnit))); - - // QuantityInfo - Assert.Equal(Length.Info, LengthAsIConvertible.ToType(typeof(QuantityInfo), null)); - Assert.Equal(Length.Info, Convert.ChangeType(_length, typeof(QuantityInfo))); - - // BaseDimensions - Assert.Equal(Length.BaseDimensions, LengthAsIConvertible.ToType(typeof(BaseDimensions), null)); - Assert.Equal(Length.BaseDimensions, Convert.ChangeType(_length, typeof(BaseDimensions))); - } - - [Fact] - public void ToUInt16Test() - { - ushort expected = 3; - Assert.Equal(expected, LengthAsIConvertible.ToUInt16(null)); - Assert.Equal(expected, Convert.ToUInt16(_length)); - Assert.Equal(expected, Convert.ChangeType(_length, typeof(ushort))); - } - - [Fact] - public void ToUInt32Test() - { - uint expected = 3; - Assert.Equal(expected, LengthAsIConvertible.ToUInt32(null)); - Assert.Equal(expected, Convert.ToUInt32(_length)); - Assert.Equal(expected, Convert.ChangeType(_length, typeof(uint))); - } - - [Fact] - public void ToUInt64Test() - { - ulong expected = 3; - Assert.Equal(expected, LengthAsIConvertible.ToUInt64(null)); - Assert.Equal(expected, Convert.ToUInt64(_length)); - Assert.Equal(expected, Convert.ChangeType(_length, typeof(ulong))); - } - } -} 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 420f726fcf..ac631076e0 100644 --- a/UnitsNet.Tests/QuantityInfoTest.cs +++ b/UnitsNet.Tests/QuantityInfoTest.cs @@ -1,264 +1,688 @@ // 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.CodeAnalysis; -using System.Linq; +using System.Resources; using UnitsNet.Tests.CustomQuantities; -using UnitsNet.Units; -using Xunit; -namespace UnitsNet.Tests +namespace UnitsNet.Tests; + +public class QuantityInfoTest { - public class QuantityInfoTest - { - private UnitInfo[] _lengthUnitInfos = Length.Info.UnitInfos.Cast().ToArray(); - - [Fact] - public void Constructor_AssignsProperties() - { - var expectedZero = Length.FromCentimeters(10); - UnitInfo[] expectedUnitInfos = { - new(LengthUnit.Centimeter, "Centimeters", new BaseUnits(LengthUnit.Centimeter), nameof(Length)), - new(LengthUnit.Kilometer, "Kilometers", new BaseUnits(LengthUnit.Kilometer), nameof(Length)) - }; - var expectedBaseUnit = LengthUnit.Centimeter; - var expectedBaseDimensions = Length.BaseDimensions; - - var info = new QuantityInfo(nameof(Length), typeof(LengthUnit), expectedUnitInfos, - expectedBaseUnit, expectedZero, expectedBaseDimensions); - - Assert.Equal(expectedZero, info.Zero); - Assert.Equal("Length", info.Name); - Assert.Equal(expectedUnitInfos, info.UnitInfos); - Assert.Equal(expectedBaseDimensions, info.BaseDimensions); - } - - [Fact] - public void Constructor_AssignsPropertiesForCustomQuantity() - { - var expectedZero = new HowMuch(10, HowMuchUnit.Some); - UnitInfo[] expectedUnitInfos = { - new(HowMuchUnit.Some, "Some", BaseUnits.Undefined, nameof(HowMuch)), - new(HowMuchUnit.ATon, "Tons", BaseUnits.Undefined, nameof(HowMuch)), - new(HowMuchUnit.AShitTon, "ShitTons", BaseUnits.Undefined, nameof(HowMuch)) - }; - var expectedBaseUnit = HowMuchUnit.Some; - var expectedBaseDimensions = BaseDimensions.Dimensionless; - - var info = new QuantityInfo(nameof(HowMuch), typeof(HowMuchUnit), expectedUnitInfos, - expectedBaseUnit, expectedZero, expectedBaseDimensions); - - Assert.Equal(expectedZero, info.Zero); - Assert.Equal(nameof(HowMuch), info.Name); - Assert.Equal(expectedUnitInfos, info.UnitInfos); - Assert.Equal(expectedBaseDimensions, info.BaseDimensions); - } - - [Fact] - public void GenericsConstructor_AssignsProperties() - { - var expectedZero = Length.FromCentimeters(10); - UnitInfo[] expectedUnitInfos = { - new(LengthUnit.Centimeter, "Centimeters", new BaseUnits(LengthUnit.Centimeter), nameof(Length)), - new(LengthUnit.Kilometer,"Kilometers", new BaseUnits(LengthUnit.Kilometer), nameof(Length)) - }; - var expectedBaseUnit = LengthUnit.Centimeter; - var expectedBaseDimensions = Length.BaseDimensions; - - var info = new QuantityInfo(nameof(Length), expectedUnitInfos, expectedBaseUnit, expectedZero, expectedBaseDimensions); - Assert.Equal(expectedZero, info.Zero); - Assert.Equal("Length", info.Name); - Assert.Equal(expectedUnitInfos, info.UnitInfos); - Assert.Equal(expectedBaseDimensions, info.BaseDimensions); - } - - [Fact] - [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] - public void Constructor_GivenNullAsUnitInfos_ThrowsArgumentNullException() - { - Assert.Throws(() => new QuantityInfo(nameof(Length), typeof(LengthUnit), - null!, Length.BaseUnit, Length.Zero, Length.BaseDimensions)); - } - - [Fact] - [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] - public void GenericsConstructor_GivenNullAsUnitInfos_ThrowsArgumentNullException() - { - Assert.Throws(() => new QuantityInfo(nameof(Length), - null!, Length.BaseUnit, Length.Zero, Length.BaseDimensions)); - } - - [Fact] - [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] - public void Constructor_GivenNullAsBaseUnit_ThrowsArgumentNullException() - { - Assert.Throws(() => new QuantityInfo(nameof(Length), typeof(LengthUnit), - _lengthUnitInfos, null!, Length.Zero, Length.BaseDimensions)); - } - - [Fact] - [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] - public void Constructor_GivenNullAsZero_ThrowsArgumentNullException() - { - Assert.Throws(() => new QuantityInfo(nameof(Length), typeof(LengthUnit), - _lengthUnitInfos, Length.BaseUnit, null!, Length.BaseDimensions)); - } - - [Fact] - [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] - public void GenericsConstructor_GivenNullAsZero_ThrowsArgumentNullException() - { - Assert.Throws(() => new QuantityInfo(nameof(Length), - Length.Info.UnitInfos, Length.BaseUnit, null!, Length.BaseDimensions)); - } - - [Fact] - [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] - public void Constructor_GivenNullAsBaseDimensions_ThrowsArgumentNullException() - { - Assert.Throws(() => new QuantityInfo(nameof(Length), typeof(LengthUnit), - _lengthUnitInfos, Length.BaseUnit, Length.Zero, null!)); - } - - [Fact] - [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] - public void GenericsConstructor_GivenNullAsBaseDimensions_ThrowsArgumentNullException() - { - Assert.Throws(() => new QuantityInfo(nameof(Length), - Length.Info.UnitInfos, Length.BaseUnit, Length.Zero, null!)); - } - [Fact] - [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] - public void Constructor2_GivenNullAsUnitInfos_ThrowsArgumentNullException() - { - Assert.Throws(() => new QuantityInfo(Length.Info.Name, typeof(LengthUnit), - null!, Length.BaseUnit, Length.Zero, Length.BaseDimensions)); - } - - [Fact] - [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] - public void GenericsConstructor2_GivenNullAsUnitInfos_ThrowsArgumentNullException() - { - Assert.Throws(() => new QuantityInfo(Length.Info.Name, - null!, Length.BaseUnit, Length.Zero, Length.BaseDimensions)); - } - - [Fact] - [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] - public void Constructor2_GivenNullAsBaseUnit_ThrowsArgumentNullException() - { - Assert.Throws(() => new QuantityInfo(Length.Info.Name, typeof(LengthUnit), - _lengthUnitInfos, null!, Length.Zero, Length.BaseDimensions)); - } - - [Fact] - [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] - public void Constructor2_GivenNullAsZero_ThrowsArgumentNullException() - { - Assert.Throws(() => new QuantityInfo(Length.Info.Name, typeof(LengthUnit), - _lengthUnitInfos, Length.BaseUnit, null!, Length.BaseDimensions)); - } - - [Fact] - [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] - public void GenericsConstructor2_GivenNullAsZero_ThrowsArgumentNullException() + [Fact] + [SuppressMessage("ReSharper", "ParameterOnlyUsedForPreconditionCheck.Local")] + public void Constructor_AssignsProperties() + { + UnitDefinition[] expectedUnitInfos = + [ + new(LengthUnit.Centimeter, "Centimeters", new BaseUnits(LengthUnit.Centimeter)), + new(LengthUnit.Kilometer, "Kilometers", new BaseUnits(LengthUnit.Kilometer), 100) + ]; + const LengthUnit expectedBaseUnit = LengthUnit.Centimeter; + var expectedZero = Length.FromCentimeters(10); + BaseDimensions expectedBaseDimensions = Length.BaseDimensions; + var abbreviations = new ResourceManager("UnitsNet.GeneratedCode.Resources.Length", typeof(Length).Assembly); + + var quantityInfo = new QuantityInfo(nameof(Length), expectedBaseUnit, expectedUnitInfos, expectedZero, expectedBaseDimensions, + Length.From, abbreviations); + + Assert.Equal(nameof(Length), quantityInfo.Name); + Assert.Equal(typeof(Length), quantityInfo.QuantityType); + Assert.Equal(typeof(LengthUnit), quantityInfo.UnitType); + + // BaseUnitInfo + Assert.Multiple(() => + { + UnitInfo baseUnitInfo = quantityInfo.BaseUnitInfo; + Assert.Equal(expectedBaseUnit, baseUnitInfo.Value); + }, () => + { + QuantityInfo genericQuantityInfo = quantityInfo; + UnitInfo unitInfos = genericQuantityInfo.BaseUnitInfo; + Assert.Equal(quantityInfo.BaseUnitInfo, unitInfos); + }, () => + { + QuantityInfo genericQuantityInfo = quantityInfo; + UnitInfo unitInfos = genericQuantityInfo.BaseUnitInfo; + Assert.Equal(quantityInfo.BaseUnitInfo, unitInfos); + }); + + // UnitInfos + Assert.Multiple(() => + { + Assert.Collection(quantityInfo.UnitInfos, firstUnitInfo => + { + Assert.Equal(LengthUnit.Centimeter, firstUnitInfo.Value); + 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 => + { + Assert.Equal(LengthUnit.Kilometer, secondUnitInfo.Value); + 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); + }); + }, () => + { + QuantityInfo genericQuantityInfo = quantityInfo; + IReadOnlyCollection> unitInfos = genericQuantityInfo.UnitInfos; + Assert.Equal(quantityInfo.UnitInfos, unitInfos); + }, () => + { + QuantityInfo genericQuantityInfo = quantityInfo; + IReadOnlyCollection unitInfos = genericQuantityInfo.UnitInfos; + Assert.Equal(quantityInfo.UnitInfos, unitInfos); + }); + + // Zero + Assert.Multiple(() => + { + Length zero = quantityInfo.Zero; + Assert.Equal(expectedZero, zero); + }, () => + { + QuantityInfo genericQuantityInfo = quantityInfo; + IQuantity zero = genericQuantityInfo.Zero; + Assert.Equal(expectedZero, zero); + }, () => + { + QuantityInfo genericQuantityInfo = quantityInfo; + IQuantity zero = genericQuantityInfo.Zero; + Assert.Equal(expectedZero, zero); + }); + + Assert.Equal(expectedBaseDimensions, quantityInfo.BaseDimensions); + Assert.Equal(abbreviations, quantityInfo.UnitAbbreviations); + } + + [Fact] + [SuppressMessage("ReSharper", "ParameterOnlyUsedForPreconditionCheck.Local")] + public void Constructor_AssignsPropertiesForCustomQuantity() + { + UnitDefinition[] expectedUnitInfos = + [ + new(HowMuchUnit.Some, "Some", 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); + BaseDimensions expectedBaseDimensions = BaseDimensions.Dimensionless; + + var quantityInfo = new QuantityInfo(nameof(HowMuch), expectedBaseUnit, + expectedUnitInfos, expectedZero, expectedBaseDimensions, HowMuch.From); + + Assert.Equal(nameof(HowMuch), quantityInfo.Name); + Assert.Equal(typeof(HowMuch), quantityInfo.QuantityType); + Assert.Equal(typeof(HowMuchUnit), quantityInfo.UnitType); + Assert.Equal(expectedBaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Collection(quantityInfo.UnitInfos, firstUnitInfo => + { + Assert.Equal(HowMuchUnit.Some, firstUnitInfo.Value); + 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 => + { + Assert.Equal(HowMuchUnit.ATon, secondUnitInfo.Value); + 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 => + { + Assert.Equal(HowMuchUnit.AShitTon, thirdUnitInfo.Value); + 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); + Assert.Equal(expectedBaseDimensions, quantityInfo.BaseDimensions); + Assert.Null(quantityInfo.UnitAbbreviations); + } + + [Fact] + public void Constructor_WithoutZero_UsesZeroBaseUnit() + { + UnitDefinition[] expectedUnitInfos = + [ + new(HowMuchUnit.Some, "Some", BaseUnits.Undefined) + ]; + const HowMuchUnit expectedBaseUnit = HowMuchUnit.Some; + BaseDimensions expectedBaseDimensions = BaseDimensions.Dimensionless; + var expectedZero = new HowMuch(0, HowMuchUnit.Some); + + var quantityInfo = new QuantityInfo(nameof(HowMuch), expectedBaseUnit, + expectedUnitInfos, expectedBaseDimensions, HowMuch.From); + + Assert.Equal(expectedZero, quantityInfo.Zero); + Assert.Equal(nameof(HowMuch), quantityInfo.Name); + Assert.Equal(expectedBaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Single(quantityInfo.UnitInfos, unitInfo => + expectedBaseUnit == unitInfo.Value && + expectedUnitInfos[0].Name == unitInfo.Name && + expectedUnitInfos[0].PluralName == unitInfo.PluralName && + expectedUnitInfos[0].BaseUnits == unitInfo.BaseUnits && + expectedUnitInfos[0].ConversionFromBase == unitInfo.ConversionFromBase && + expectedUnitInfos[0].ConversionToBase == unitInfo.ConversionToBase + ); + Assert.Equal(expectedBaseDimensions, quantityInfo.BaseDimensions); + Assert.Null(quantityInfo.UnitAbbreviations); + } + + [Fact] + public void Constructor_WithoutName_UsesDefaultQuantityTypeName() + { + UnitDefinition[] expectedUnitInfos = + [ + new(HowMuchUnit.Some, "Some", BaseUnits.Undefined) + ]; + const HowMuchUnit expectedBaseUnit = HowMuchUnit.Some; + var expectedZero = new HowMuch(0, HowMuchUnit.Some); + BaseDimensions expectedBaseDimensions = BaseDimensions.Dimensionless; + var abbreviations = new ResourceManager("UnitsNet.GeneratedCode.Resources.Length", typeof(Length).Assembly); + + var quantityInfo = + new QuantityInfo(expectedBaseUnit, expectedUnitInfos, expectedBaseDimensions, HowMuch.From, abbreviations); + + Assert.Equal(expectedZero, quantityInfo.Zero); + Assert.Equal(nameof(HowMuch), quantityInfo.Name); + Assert.Equal(expectedBaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Single(quantityInfo.UnitInfos, firstUnitInfo => + expectedBaseUnit == firstUnitInfo.Value && + expectedUnitInfos[0].Name == firstUnitInfo.Name && + expectedUnitInfos[0].PluralName == firstUnitInfo.PluralName && + 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); + } + + [Fact] + [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] + public void Constructor_GivenNullAsQuantityName_ThrowsArgumentNullException() + { + Assert.Throws(() => new QuantityInfo(null!, + LengthUnit.Meter, Length.Info.UnitInfos, Length.BaseDimensions, Length.From)); + } + + [Fact] + [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] + public void Constructor_GivenNullAsUnitInfos_ThrowsArgumentNullException() + { + IEnumerable> nullCollection = null!; + Assert.Throws(() => new QuantityInfo(nameof(Length), + LengthUnit.Meter, nullCollection, Length.BaseDimensions, Length.From)); + } + + [Fact] + [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] + public void Constructor_GivenANullUnitInfo_ThrowsArgumentNullException() + { + IEnumerable> collectionContainingANull = [null!]; +#if NET + 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)); +#endif + } + + [Fact] + [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] + public void Constructor_GivenNullAsBaseDimensions_ThrowsArgumentNullException() + { + Assert.Throws(() => new QuantityInfo(nameof(Length), + LengthUnit.Meter, Length.Info.UnitInfos, null!, Length.From)); + } + + [Fact] + public void Constructor_GivenAMissingBaseUnitDefinition_ThrowsUnitNotFoundException() + { + Assert.Throws(() => + new QuantityInfo(Length.BaseUnit, [], Length.BaseDimensions, Length.From)); + } + + [Fact] + public void GetUnitInfoFor_GivenNullAsBaseUnits_ThrowsArgumentNullException() + { + Assert.Multiple(() => { - Assert.Throws(() => new QuantityInfo(Length.Info.Name, - Length.Info.UnitInfos, Length.BaseUnit, null!, Length.BaseDimensions)); - } + QuantityInfo quantityInfo = Length.Info; + Assert.Throws(() => quantityInfo.GetUnitInfoFor(null!)); + }, () => + { + QuantityInfo quantityInfo = Length.Info; + Assert.Throws(() => quantityInfo.GetUnitInfoFor(null!)); + }, () => + { + QuantityInfo quantityInfo = Length.Info; + Assert.Throws(() => quantityInfo.GetUnitInfoFor(null!)); + }); + } - [Fact] - [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] - public void Constructor2_GivenNullAsBaseDimensions_ThrowsArgumentNullException() + [Fact] + public void GetUnitInfoFor_GivenBaseUnitsWithNoMatch_ThrowsInvalidOperationException() + { + var baseUnitsWithNoMatch = new BaseUnits(mass: MassUnit.Kilogram); + Assert.Multiple(() => + { + QuantityInfo quantityInfo = Length.Info; + Assert.Throws(() => quantityInfo.GetUnitInfoFor(baseUnitsWithNoMatch)); + }, () => + { + QuantityInfo quantityInfo = Length.Info; + Assert.Throws(() => quantityInfo.GetUnitInfoFor(baseUnitsWithNoMatch)); + }, () => { - Assert.Throws(() => new QuantityInfo(Length.Info.Name, typeof(LengthUnit), - _lengthUnitInfos, Length.BaseUnit, Length.Zero, null!)); - } + QuantityInfo quantityInfo = Length.Info; + Assert.Throws(() => quantityInfo.GetUnitInfoFor(baseUnitsWithNoMatch)); + }); + } - [Fact] - [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] - public void GenericsConstructor2_GivenNullAsBaseDimensions_ThrowsArgumentNullException() + [Fact] + public void GetUnitInfoFor_GivenBaseUnitsWithMultipleMatches_ThrowsInvalidOperationException() + { + var baseUnits = new BaseUnits(LengthUnit.Meter); + UnitDefinition[] duplicateBaseUnits = + [ + new(LengthUnit.Meter, "Meters", baseUnits), + new(LengthUnit.Foot, "Feet", baseUnits) + ]; + BaseDimensions dimensions = Length.BaseDimensions; + Assert.Multiple(() => + { + var quantityInfo = new QuantityInfo(LengthUnit.Meter, duplicateBaseUnits, dimensions, Length.From); + Assert.Throws(() => quantityInfo.GetUnitInfoFor(baseUnits)); + }, () => + { + QuantityInfo genericQuantityInfo = new QuantityInfo(LengthUnit.Meter, duplicateBaseUnits, dimensions, Length.From); + Assert.Throws(() => genericQuantityInfo.GetUnitInfoFor(baseUnits)); + }, () => { - Assert.Throws(() => new QuantityInfo(Length.Info.Name, - Length.Info.UnitInfos, Length.BaseUnit, Length.Zero, null!)); - } + QuantityInfo genericQuantityInfo = new QuantityInfo(LengthUnit.Meter, duplicateBaseUnits, dimensions, Length.From); + Assert.Throws(() => genericQuantityInfo.GetUnitInfoFor(baseUnits)); + }); + } + + [Fact] + public void GetUnitInfoFor_GivenBaseUnitsWithOneMatch_ReturnsTheMatch() + { + var baseUnitsWithOneMatch = new BaseUnits(LengthUnit.Foot); + UnitInfo expectedUnitInfo = Length.Info[LengthUnit.Foot]; - [Fact] - public void GetUnitInfoFor_GivenNullAsBaseUnits_ThrowsArgumentNullException() + Assert.Multiple(() => { - Assert.Throws(() => Length.Info.GetUnitInfoFor(null!)); - } + QuantityInfo quantityInfo = Length.Info; - [Fact] - public void GetUnitInfoFor_GivenBaseUnitsWithNoMatch_ThrowsInvalidOperationException() + UnitInfo result = quantityInfo.GetUnitInfoFor(baseUnitsWithOneMatch); + + Assert.Equal(expectedUnitInfo, result); + }, () => { - var baseUnitsWithNoMatch = new BaseUnits(mass: MassUnit.Kilogram); - Assert.Throws(() => Length.Info.GetUnitInfoFor(baseUnitsWithNoMatch)); - } + QuantityInfo quantityInfo = Length.Info; + + UnitInfo result = quantityInfo.GetUnitInfoFor(baseUnitsWithOneMatch); - [Fact] - public void GetUnitInfoFor_GivenBaseUnitsWithMultipleMatches_ThrowsInvalidOperationException() + Assert.Equal(expectedUnitInfo, result); + }, () => { - var baseUnits = new BaseUnits(LengthUnit.Meter); + QuantityInfo quantityInfo = Length.Info; - var quantityInfo = new QuantityInfo(Length.Info.Name, - new UnitInfo[] { - new(LengthUnit.Meter, "Meters", baseUnits, nameof(Length)), - new(LengthUnit.Foot, "Feet", baseUnits, nameof(Length)) - }, - LengthUnit.Meter, Length.Zero, Length.BaseDimensions); + UnitInfo result = quantityInfo.GetUnitInfoFor(baseUnitsWithOneMatch); - Assert.Throws(() => quantityInfo.GetUnitInfoFor(baseUnits)); - } + Assert.Equal(expectedUnitInfo, result); + }); + } - [Fact] - public void GetUnitInfosFor_GivenNullAsBaseUnits_ThrowsArgumentNullException() + [Fact] + public void GetUnitInfosFor_GivenNullAsBaseUnits_ThrowsArgumentNullException() + { + Assert.Multiple(() => + { + QuantityInfo quantityInfo = Length.Info; + Assert.Throws(() => quantityInfo.GetUnitInfosFor(null!)); + }, () => { - Assert.Throws(() => Length.Info.GetUnitInfosFor(null!)); - } + QuantityInfo quantityInfo = Length.Info; + Assert.Throws(() => quantityInfo.GetUnitInfosFor(null!)); + }, () => + { + QuantityInfo quantityInfo = Length.Info; + Assert.Throws(() => quantityInfo.GetUnitInfosFor(null!)); + }); + } - [Fact] - public void GetUnitInfosFor_GivenBaseUnitsWithNoMatch_ReturnsEmpty() + [Fact] + public void GetUnitInfosFor_GivenBaseUnitsWithNoMatch_ReturnsEmpty() + { + var baseUnitsWithNoMatch = new BaseUnits(mass: MassUnit.Kilogram); + Assert.Multiple(() => + { + QuantityInfo quantityInfo = Length.Info; + + IEnumerable> result = quantityInfo.GetUnitInfosFor(baseUnitsWithNoMatch); + + Assert.Empty(result); + }, () => { - var baseUnitsWithNoMatch = new BaseUnits(mass: MassUnit.Kilogram); - var result = Length.Info.GetUnitInfosFor(baseUnitsWithNoMatch); + QuantityInfo quantityInfo = Length.Info; + + IEnumerable> result = quantityInfo.GetUnitInfosFor(baseUnitsWithNoMatch); + + Assert.Empty(result); + }, () => + { + QuantityInfo quantityInfo = Length.Info; + + IEnumerable result = quantityInfo.GetUnitInfosFor(baseUnitsWithNoMatch); + Assert.Empty(result); - } - - [Fact] - public void GetUnitInfosFor_GivenBaseUnitsWithOneMatch_ReturnsOneMatch() - { - var baseUnitsWithOneMatch = new BaseUnits(LengthUnit.Foot); - var result = Length.Info.GetUnitInfosFor(baseUnitsWithOneMatch); - Assert.Collection(result, element1 => Assert.Equal(LengthUnit.Foot, element1.Value)); - } - - [Fact] - [SuppressMessage("ReSharper", "ParameterOnlyUsedForPreconditionCheck.Local")] - public void GetUnitInfosFor_GivenBaseUnitsWithMultipleMatches_ReturnsMultipleMatches() - { - var baseUnits = new BaseUnits(LengthUnit.Meter); - - var quantityInfo = new QuantityInfo(Length.Info.Name, - new UnitInfo[] { - new(LengthUnit.Meter, "Meters", baseUnits, nameof(Length)), - new(LengthUnit.Foot, "Feet", baseUnits, nameof(Length)) }, - LengthUnit.Meter, Length.Zero, Length.BaseDimensions); - - var result = quantityInfo.GetUnitInfosFor(baseUnits); - - Assert.Collection(result, - element1 => - { - Assert.Equal(LengthUnit.Meter, element1.Value); - Assert.Equal(baseUnits, element1.BaseUnits); - }, - element2 => - { - Assert.Equal(LengthUnit.Foot, element2.Value); - Assert.Equal(baseUnits, element2.BaseUnits); - } ); - } + }); } + + [Fact] + public void GetUnitInfosFor_GivenBaseUnitsWithOneMatch_ReturnsOneMatch() + { + var baseUnitsWithOneMatch = new BaseUnits(LengthUnit.Foot); + IEnumerable> result = Length.Info.GetUnitInfosFor(baseUnitsWithOneMatch); + Assert.Collection(result, element1 => Assert.Equal(LengthUnit.Foot, element1.Value)); + } + + [Fact] + public void GetUnitInfosFor_GivenBaseUnitsWithMultipleMatches_ReturnsMultipleMatches() + { + var baseUnits = new BaseUnits(LengthUnit.Meter); + + var quantityInfo = new QuantityInfo(Length.Info.Name, + LengthUnit.Meter, new UnitDefinition[] { new(LengthUnit.Meter, "Meters", baseUnits), new(LengthUnit.Foot, "Feet", baseUnits) }, + Length.BaseDimensions, Length.From); + + var result = quantityInfo.GetUnitInfosFor(baseUnits).ToList(); + + Assert.Equal(2, result.Count); + Assert.Contains(result, info => info.Value == LengthUnit.Meter && info.BaseUnits == baseUnits); + Assert.Contains(result, info => info.Value == LengthUnit.Foot && info.BaseUnits == baseUnits); + } + + // [Fact] + // public void TryGetUnitInfo_WithEnum_ReturnsTheExpectedResult() + // { + // QuantityInfo quantityInfo = HowMuch.Info; + // + // var success = quantityInfo.TryGetUnitInfo(HowMuchUnit.ATon, out UnitInfo? unitInfo); + // + // Assert.True(success); + // Assert.Equal(HowMuchUnit.ATon, unitInfo!.Value); + // } + // + // [Fact] + // public void TryGetUnitInfo_WithInvalidEnum_ReturnsTheExpectedResult() + // { + // QuantityInfo quantityInfo = HowMuch.Info; + // + // var success = quantityInfo.TryGetUnitInfo(LengthUnit.Meter, out UnitInfo? unitInfo); + // + // Assert.False(success); + // Assert.Null(unitInfo); + // } + + [Fact] + public void TryGetUnitInfo_WithUnit_ReturnsTheExpectedResult() + { + QuantityInfo quantityInfo = Mass.Info; + + var success = quantityInfo.TryGetUnitInfo(MassUnit.Milligram, out UnitInfo? unitInfo); + + Assert.True(success); + Assert.Equal(MassUnit.Milligram, unitInfo!.Value); + } + + [Fact] + public void TryGetUnitInfo_WithInvalidUnit_ReturnsTheExpectedResult() + { + QuantityInfo quantityInfo = Mass.Info; + + var success = quantityInfo.TryGetUnitInfo((MassUnit)(-1), out UnitInfo? unitInfo); + + Assert.False(success); + Assert.Null(unitInfo); + } + + [Fact] + public void Indexer_WithValidEnum_ReturnsTheTargetUnitInfo() + { + QuantityInfo quantityInfo = HowMuch.Info; + + UnitInfo unitInfo = quantityInfo[HowMuchUnit.ATon]; + + Assert.Equal(HowMuchUnit.ATon, unitInfo.Value); + } + + [Fact] + public void Indexer_WithInvalidEnum_ThrowsKeyNotFoundException() + { + QuantityInfo quantityInfo = HowMuch.Info; + + Assert.Throws(() => quantityInfo[(HowMuchUnit)(-1)]); + } + + [Fact] + public void Indexer_WithValidUnit_ReturnsTheTargetUnitInfo() + { + QuantityInfo quantityInfo = Mass.Info; + + UnitInfo unitInfo = quantityInfo[MassUnit.Milligram]; + + Assert.Equal(MassUnit.Milligram, unitInfo.Value); + } + + [Fact] + public void Indexer_WithInvalidUnit_ThrowsKeyNotFoundException() + { + QuantityInfo quantityInfo = Mass.Info; + + Assert.Throws(() => quantityInfo[(MassUnit)(-1)]); + } + + [Fact] + public void Indexer_WithValidUnitKey_ReturnsTheTargetUnitInfo() + { + QuantityInfo quantityInfo = Mass.Info; + var unitKey = UnitKey.ForUnit(MassUnit.Milligram); + + UnitInfo unitInfo = quantityInfo[unitKey]; + + Assert.Equal(MassUnit.Milligram, unitInfo.Value); + } + + [Fact] + public void Indexer_WithInvalidUnitKeyType_ThrowsInvalidOperationException() + { + QuantityInfo quantityInfo = Mass.Info; + var unitKey = UnitKey.ForUnit(LengthUnit.Meter); + + Assert.Throws(() => quantityInfo[unitKey]); + } + + [Fact] + public void Indexer_WithUnknownUnitKeyValue_ThrowsInvalidOperationException() + { + QuantityInfo quantityInfo = Mass.Info; + var unitKey = new UnitKey(typeof(MassUnit), -1); + + Assert.Throws(() => quantityInfo[unitKey]); + } + + [Fact] + public void UntypedIndexer_WithUnknownUnitKeyValue_ThrowsInvalidOperationException() + { + QuantityInfo quantityInfo = Mass.Info; + var unitKey = new UnitKey(typeof(MassUnit), -1); + + Assert.Throws(() => quantityInfo[unitKey]); + } + + [Theory] + [InlineData(1, MassUnit.Kilogram)] + [InlineData(2, MassUnit.Milligram)] + public void From_ValueAndUnit_ReturnsTheExpectedQuantity(double value, MassUnit unit) + { + Assert.Multiple(() => + { + QuantityInfo quantityInfo = Mass.Info; + + Mass quantity = quantityInfo.From(value, unit); + + Assert.Equal(value, quantity.Value); + Assert.Equal(unit, quantity.Unit); + }, () => + { + QuantityInfo quantityInfo = Mass.Info; + + IQuantity quantity = quantityInfo.From(value, unit); + + Assert.Equal(value, quantity.Value); + Assert.Equal(unit, quantity.Unit); + }, () => + { + QuantityInfo quantityInfo = Mass.Info; + + IQuantity quantity = quantityInfo.From(value, unit); + + Assert.Equal(value, quantity.Value); + Assert.Equal(unit, quantity.Unit); + }); + } + + [Theory] + [InlineData(1, MassUnit.Kilogram)] + [InlineData(2, MassUnit.Milligram)] + public void From_ValueAndUnitKey_WithSameUnitType_ReturnsTheExpectedQuantity(double value, MassUnit unit) + { + IQuantityInstanceInfo quantityInfo = Mass.Info; + + Mass quantity = quantityInfo.Create(value, UnitKey.ForUnit(unit)); + + Assert.Equal(value, quantity.Value); + Assert.Equal(unit, quantity.Unit); + } + + [Theory] + [InlineData(1, MassUnit.Kilogram)] + [InlineData(2, MassUnit.Milligram)] + public void From_ValueAnEnum_WithSameUnitType_ReturnsTheExpectedQuantity(double value, Enum unit) + { + QuantityInfo quantityInfo = Mass.Info; + + IQuantity quantity = quantityInfo.From(value, unit); + + Assert.Equal(value, quantity.Value); + Assert.Equal(unit, quantity.Unit); + } + + [Fact] + public void From_ValueAndUnitKey_WIthDifferentUnitType_ThrowsArgumentException() + { + IQuantityInstanceInfo quantityInfo = Mass.Info; + var unitKey = UnitKey.ForUnit(LengthUnit.Meter); + + Assert.Throws(() => quantityInfo.Create(1, unitKey)); + } + + [Fact] + public void From_ValueAndEnum_WIthDifferentUnitType_ThrowsInvalidOperationException() + { + QuantityInfo quantityInfo = Mass.Info; + + Assert.Throws(() => quantityInfo.From(1, LengthUnit.Meter)); + } + + [Fact] + public void ToString_ReturnsTheQuantityName() + { + QuantityInfo quantityInfo = Mass.Info; + + Assert.Equal(quantityInfo.Name, quantityInfo.ToString()); + } + +#if NET + [Fact] + public void Constructor_WithoutDelegate_UsesTheDefaultQuantityFrom() + { + UnitDefinition[] expectedUnitInfos = + [ + new(HowMuchUnit.Some, "Some", BaseUnits.Undefined) + ]; + const string quantityName = "How Much?"; + const HowMuchUnit expectedBaseUnit = HowMuchUnit.Some; + var expectedZero = new HowMuch(0, HowMuchUnit.Some); + BaseDimensions expectedBaseDimensions = BaseDimensions.Dimensionless; + var abbreviations = new ResourceManager("UnitsNet.GeneratedCode.Resources.Length", typeof(Length).Assembly); + + var quantityInfo = new QuantityInfo(quantityName, expectedBaseUnit, expectedUnitInfos, expectedBaseDimensions, abbreviations); + + Assert.Equal(quantityName, quantityInfo.Name); + Assert.Equal(expectedZero, quantityInfo.Zero); + Assert.Equal(expectedBaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Single(quantityInfo.UnitInfos, firstUnitInfo => + expectedBaseUnit == firstUnitInfo.Value && + expectedUnitInfos[0].Name == firstUnitInfo.Name && + expectedUnitInfos[0].PluralName == firstUnitInfo.PluralName && + 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); + } + + [Fact] + public void Constructor_WithoutNameOrDelegate_UsesTheDefaultQuantityNameAndFrom() + { + UnitDefinition[] expectedUnitInfos = + [ + new(HowMuchUnit.Some, "Some", BaseUnits.Undefined) + ]; + const HowMuchUnit expectedBaseUnit = HowMuchUnit.Some; + var expectedZero = new HowMuch(0, HowMuchUnit.Some); + BaseDimensions expectedBaseDimensions = BaseDimensions.Dimensionless; + var abbreviations = new ResourceManager("UnitsNet.GeneratedCode.Resources.Length", typeof(Length).Assembly); + + var quantityInfo = new QuantityInfo(expectedBaseUnit, expectedUnitInfos, expectedBaseDimensions, abbreviations); + + Assert.Equal(expectedZero, quantityInfo.Zero); + Assert.Equal(nameof(HowMuch), quantityInfo.Name); + Assert.Equal(expectedBaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Single(quantityInfo.UnitInfos, firstUnitInfo => + expectedBaseUnit == firstUnitInfo.Value && + expectedUnitInfos[0].Name == firstUnitInfo.Name && + expectedUnitInfos[0].PluralName == firstUnitInfo.PluralName && + 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); + } + +#endif } diff --git a/UnitsNet.Tests/QuantityParserTests.cs b/UnitsNet.Tests/QuantityParserTests.cs index b56fa10d90..e63f29fdb7 100644 --- a/UnitsNet.Tests/QuantityParserTests.cs +++ b/UnitsNet.Tests/QuantityParserTests.cs @@ -13,13 +13,13 @@ public class QuantityParserTests [Fact] public void Parse_WithSingleCaseInsensitiveMatch_ParsesWithMatchedUnit() { - var unitAbbreviationsCache = new UnitAbbreviationsCache(); + var unitAbbreviationsCache = new UnitAbbreviationsCache([HowMuch.Info]); unitAbbreviationsCache.MapUnitToAbbreviation(HowMuchUnit.Some, "foo"); var quantityParser = new QuantityParser(unitAbbreviationsCache); HowMuch q = quantityParser.Parse("1 FOO", null, - (value, unit) => new HowMuch((double) value, unit)); + (value, unit) => new HowMuch(value, unit)); Assert.Equal(HowMuchUnit.Some, q.Unit); Assert.Equal(1, q.Value); @@ -28,14 +28,14 @@ public void Parse_WithSingleCaseInsensitiveMatch_ParsesWithMatchedUnit() [Fact] public void Parse_WithOneCaseInsensitiveMatchAndOneExactMatch_ParsesWithTheExactMatchUnit() { - var unitAbbreviationsCache = new UnitAbbreviationsCache(); + var unitAbbreviationsCache = new UnitAbbreviationsCache([HowMuch.Info]); unitAbbreviationsCache.MapUnitToAbbreviation(HowMuchUnit.Some, "foo"); unitAbbreviationsCache.MapUnitToAbbreviation(HowMuchUnit.ATon, "FOO"); var quantityParser = new QuantityParser(unitAbbreviationsCache); HowMuch q = quantityParser.Parse("1 FOO", null, - (value, unit) => new HowMuch((double) value, unit)); + (value, unit) => new HowMuch(value, unit)); Assert.Equal(HowMuchUnit.ATon, q.Unit); Assert.Equal(1, q.Value); @@ -44,14 +44,14 @@ public void Parse_WithOneCaseInsensitiveMatchAndOneExactMatch_ParsesWithTheExact [Fact] public void Parse_WithMultipleCaseInsensitiveMatchesButNoExactMatches_ThrowsAmbiguousUnitParseException() { - var unitAbbreviationsCache = new UnitAbbreviationsCache(); + var unitAbbreviationsCache = new UnitAbbreviationsCache([HowMuch.Info]); unitAbbreviationsCache.MapUnitToAbbreviation(HowMuchUnit.Some, "foo"); unitAbbreviationsCache.MapUnitToAbbreviation(HowMuchUnit.ATon, "FOO"); var quantityParser = new QuantityParser(unitAbbreviationsCache); void Act() { - quantityParser.Parse("1 Foo", null, (value, unit) => new HowMuch((double) value, unit)); + quantityParser.Parse("1 Foo", null, (value, unit) => new HowMuch(value, unit)); } var ex = Assert.Throws(Act); @@ -61,13 +61,13 @@ void Act() [Fact] public void Parse_MappedCustomUnit() { - var unitAbbreviationsCache = new UnitAbbreviationsCache(); + var unitAbbreviationsCache = new UnitAbbreviationsCache([HowMuch.Info]); unitAbbreviationsCache.MapUnitToAbbreviation(HowMuchUnit.Some, "fooh"); var quantityParser = new QuantityParser(unitAbbreviationsCache); HowMuch q = quantityParser.Parse("1 fooh", null, - (value, unit) => new HowMuch((double) value, unit)); + (value, unit) => new HowMuch(value, unit)); Assert.Equal(HowMuchUnit.Some, q.Unit); Assert.Equal(1, q.Value); @@ -76,13 +76,13 @@ public void Parse_MappedCustomUnit() [Fact] public void TryParse_MappedCustomUnit() { - var unitAbbreviationsCache = new UnitAbbreviationsCache(); + var unitAbbreviationsCache = new UnitAbbreviationsCache([HowMuch.Info]); unitAbbreviationsCache.MapUnitToAbbreviation(HowMuchUnit.Some, "fooh"); var quantityParser = new QuantityParser(unitAbbreviationsCache); bool success = quantityParser.TryParse("1 fooh", null, - (value, unit) => new HowMuch((double) value, unit), + (value, unit) => new HowMuch(value, unit), out HowMuch q); Assert.True(success); diff --git a/UnitsNet.Tests/QuantityTest.cs b/UnitsNet.Tests/QuantityTest.cs index 0f47fd13c4..94b3e49926 100644 --- a/UnitsNet.Tests/QuantityTest.cs +++ b/UnitsNet.Tests/QuantityTest.cs @@ -1,12 +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 System.Collections.Generic; using System.Globalization; -using System.Linq; -using UnitsNet.Units; -using Xunit; using static System.Globalization.CultureInfo; namespace UnitsNet.Tests @@ -20,7 +15,7 @@ public class QuantityTest [InlineData(double.NaN)] [InlineData(double.PositiveInfinity)] [InlineData(double.NegativeInfinity)] - public void From_GivenNaNOrInfinity_DoNotThrowsArgumentException(double value) + public void From_GivenNaNOrInfinity_DoesNotThrowArgumentException(double value) { var exception = Record.Exception(() => Quantity.From(value, LengthUnit.Centimeter)); @@ -43,6 +38,12 @@ public void TryFrom_GivenNullUnit_ReturnsFalse() Enum? nullUnit = null; Assert.False(Quantity.TryFrom(1, nullUnit, out IQuantity? _)); } + + [Fact] + public void TryFrom_GivenUnknownUnitType_ReturnsFalse() + { + Assert.False(Quantity.TryFrom(1, ConsoleColor.Red, out IQuantity? _)); + } [Fact] public void From_GivenValueAndUnit_ReturnsQuantity() @@ -52,6 +53,14 @@ public void From_GivenValueAndUnit_ReturnsQuantity() Assert.Equal(Pressure.FromMegabars(3), Quantity.From(3, PressureUnit.Megabar)); } + [Fact] + public void FromQuantityInfo_ReturnsQuantityWithBaseUnit() + { + IQuantity quantity = Quantity.FromQuantityInfo(Length.Info, 1); + Assert.Equal(1, quantity.Value); + Assert.Equal(Length.BaseUnit, quantity.Unit); + } + [Fact] public void ByName_GivenLength_ReturnsQuantityInfoForLength() { @@ -180,7 +189,7 @@ public void TryFrom_GivenValueAndUnit_ReturnsQuantity() [Fact] public void TryParse_GivenInvalidQuantityType_ReturnsFalseAndNullQuantity() { - Assert.False(Quantity.TryParse(InvariantCulture, typeof(DummyIQuantity), "3.0 cm", out IQuantity? parsedLength)); + Assert.False(Quantity.TryParse(InvariantCulture, typeof(DateTime), "3.0 cm", out IQuantity? parsedLength)); Assert.Null(parsedLength); } @@ -215,7 +224,7 @@ public void Types_ReturnsKnownQuantityTypes() { var knownQuantities = new List { Length.Info, Force.Info, Mass.Info }; - ICollection types = Quantity.ByName.Values; + IEnumerable types = Quantity.ByName.Values; Assert.Superset(knownQuantities.ToHashSet(), types.ToHashSet()); } diff --git a/UnitsNet.Tests/QuantityTests.cs b/UnitsNet.Tests/QuantityTests.cs index 22154965fb..89685059e1 100644 --- a/UnitsNet.Tests/QuantityTests.cs +++ b/UnitsNet.Tests/QuantityTests.cs @@ -1,10 +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 System.Globalization; -using UnitsNet.Units; -using Xunit; namespace UnitsNet.Tests { @@ -21,79 +18,79 @@ 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)); - } + // [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() @@ -153,7 +150,7 @@ public void From_InvalidUnitName_ThrowsUnitNotFoundException() [Fact] public void FromUnitAbbreviation_ReturnsQuantity() { - IQuantity q = Quantity.FromUnitAbbreviation(5, "cm"); + IQuantity q = Quantity.FromUnitAbbreviation(CultureInfo.InvariantCulture, 5, "cm"); Assert.Equal(5, q.Value); Assert.Equal(LengthUnit.Centimeter, q.Unit); } @@ -161,34 +158,36 @@ public void FromUnitAbbreviation_ReturnsQuantity() [Fact] public void TryFromUnitAbbreviation_ReturnsQuantity() { - Assert.True(Quantity.TryFromUnitAbbreviation(5, "cm", out IQuantity? q)); - Assert.Equal(LengthUnit.Centimeter, q!.Unit); + Assert.True(Quantity.TryFromUnitAbbreviation(5, "cm", out IQuantity? quantity)); + Assert.Equal(LengthUnit.Centimeter, quantity!.Unit); } [Fact] public void FromUnitAbbreviation_MatchingCulture_ReturnsQuantity() { - IQuantity q = Quantity.FromUnitAbbreviation(Russian, 5, "см"); - Assert.Equal(5, q.Value); - Assert.Equal(LengthUnit.Centimeter, q.Unit); + IQuantity quantity = Quantity.FromUnitAbbreviation(Russian, 5, "см"); + Assert.Equal(5, quantity.Value); + Assert.Equal(LengthUnit.Centimeter, quantity.Unit); } [Fact] - public void TryFromUnitAbbreviation_MatchingCulture_ReturnsQuantity() + public void FromUnitAbbreviation_MatchingFallbackCulture_ReturnsQuantity() { - Assert.False(Quantity.TryFromUnitAbbreviation(Russian, 5, "cm", out IQuantity? q)); + // The localized abbreviation is "см" + IQuantity quantity = Quantity.FromUnitAbbreviation(Russian, 5, "cm"); + Assert.Equal(5, quantity.Value); + Assert.Equal(LengthUnit.Centimeter, quantity.Unit); } [Fact] - public void FromUnitAbbreviation_MismatchingCulture_ThrowsUnitNotFoundException() + public void TryFromUnitAbbreviation_MatchingFallbackCulture_ReturnsQuantity() { - Assert.Throws(() => Quantity.FromUnitAbbreviation(Russian, 5, "cm")); // Expected "см" - } - - [Fact] - public void TryFromUnitAbbreviation_MismatchingCulture_ThrowsUnitNotFoundException() - { - Assert.Throws(() => Quantity.FromUnitAbbreviation(Russian, 5, "cm")); // Expected "см" + // The localized abbreviation is "см" + var success = Quantity.TryFromUnitAbbreviation(Russian, 5, "cm", out IQuantity? quantity); + Assert.True(success); + Assert.NotNull(quantity); + Assert.Equal(5, quantity.Value); + Assert.Equal(LengthUnit.Centimeter, quantity.Unit); } [Fact] @@ -235,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/QuantityTypeConverterTest.cs b/UnitsNet.Tests/QuantityTypeConverterTest.cs index ca15b50c97..13ba43058d 100644 --- a/UnitsNet.Tests/QuantityTypeConverterTest.cs +++ b/UnitsNet.Tests/QuantityTypeConverterTest.cs @@ -1,12 +1,11 @@ // 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.ComponentModel; using System.Globalization; using System.Reflection; +using UnitsNet.Tests.CustomQuantities; using UnitsNet.Tests.Helpers; -using Xunit; namespace UnitsNet.Tests { @@ -122,6 +121,53 @@ public void ConvertFrom_GivenQuantityStringAndContextWithDefaultUnitAndConvertTo Assert.Equal(expectedUnit, convertedValue.Unit); } + [Theory] + [InlineData(1.234)] + [InlineData(-1.234)] + [InlineData(double.NaN)] + [InlineData(double.PositiveInfinity)] + [InlineData(double.NegativeInfinity)] + public void ConvertFrom_GivenQuantityStringAndNullCulture_ReturnsQuantityConvertedToUnit(double expectedValue) + { + var str = expectedValue.ToString(CultureInfo.CurrentCulture) + "mm"; + var converter = new QuantityTypeConverter(); + + var convertedValue = (Length)converter.ConvertFrom(null, null, str)!; + + Assert.Equal(expectedValue, convertedValue.Value); + Assert.Equal(LengthUnit.Millimeter, convertedValue.Unit); + } + + [Fact] + public void ConvertFrom_WithUnknownQuantity_ThrowsQuantityNotFoundException() + { + var converter = new QuantityTypeConverter(); + ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); + + Assert.Throws(() => converter.ConvertFrom(context, Culture, "42 st")); + } + + [Fact] + public void ConvertFrom_WithUnknownUnit_ThrowsUnitNotFoundException() + { + var converter = new QuantityTypeConverter(); + ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] + { + new DefaultUnitAttribute(HowMuchUnit.Some) + }); + + Assert.Throws(() => converter.ConvertFrom(context, Culture, "42")); + } + + [Fact] + public void ConvertFrom_GivenUnsupportedValueType_ThrowsNotSupportedException() + { + var converter = new QuantityTypeConverter(); + ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); + + Assert.Throws(() => converter.ConvertFrom(context, Culture, DateTime.Now)); + } + [Fact] public void ConvertFrom_GivenEmptyString_ThrowsNotSupportedException() { @@ -132,12 +178,12 @@ public void ConvertFrom_GivenEmptyString_ThrowsNotSupportedException() } [Fact] - public void ConvertFrom_GivenWrongQuantity_ThrowsUnitNotFoundException() + public void ConvertFrom_GivenWrongQuantityStringFormat_ThrowsFormatException() { var converter = new QuantityTypeConverter(); ITypeDescriptorContext context = new TypeDescriptorContext("SomeMemberName", new Attribute[] { }); - Assert.Throws(() => converter.ConvertFrom(context, Culture, "1m^2")); + Assert.Throws(() => converter.ConvertFrom(context, Culture, "1 meter")); } [Theory] 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 2d565419c4..45b995c767 100644 --- a/UnitsNet.Tests/UnitAbbreviationsCacheTests.cs +++ b/UnitsNet.Tests/UnitAbbreviationsCacheTests.cs @@ -17,9 +17,63 @@ public class UnitAbbreviationsCacheTests { private static readonly CultureInfo AmericanCulture = CultureInfo.GetCultureInfo("en-US"); private static readonly CultureInfo NorwegianCulture = CultureInfo.GetCultureInfo("nb-NO"); + + [Fact] + public void EmptyConstructor_ReturnsAnAbbreviationCacheWithDefaultQuantityInfoLookup() + { + var unitAbbreviationCache = new UnitAbbreviationsCache(); + + Assert.Equal(UnitsNetSetup.Default.QuantityInfoLookup, unitAbbreviationCache.Quantities); + Assert.Equal("g", unitAbbreviationCache.GetUnitAbbreviations(MassUnit.Gram, AmericanCulture)[0]); + Assert.Throws(() => unitAbbreviationCache.GetUnitAbbreviations(HowMuchUnit.Some)); + } [Fact] - public void UnitAbbreviationsCacheDefaultReturnsUnitsNetSetupDefaultUnitAbbreviations() + public void Constructor_WithQuantities_ReturnsAnAbbreviationCacheWithNewQuantityInfoLookup() + { + var unitAbbreviationCache = new UnitAbbreviationsCache([Mass.Info, HowMuch.Info]); + + Assert.NotEqual(UnitsNetSetup.Default.QuantityInfoLookup, unitAbbreviationCache.Quantities); + Assert.Equal("g", unitAbbreviationCache.GetUnitAbbreviations(MassUnit.Gram, AmericanCulture)[0]); + Assert.Empty(unitAbbreviationCache.GetUnitAbbreviations(HowMuchUnit.Some, AmericanCulture)); + Assert.Throws(() => unitAbbreviationCache.GetUnitAbbreviations(LengthUnit.Meter)); + } + + [Fact] + public void CreateDefault_ReturnsAnAbbreviationCacheWithDefaultQuantityInfoLookup() + { + var unitAbbreviationCache = UnitAbbreviationsCache.CreateDefault(); + + Assert.Equal(UnitsNetSetup.Default.QuantityInfoLookup, unitAbbreviationCache.Quantities); + 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.QuantityInfoLookup, 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.QuantityInfoLookup, 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() { Assert.Equal(UnitsNetSetup.Default.UnitAbbreviations, UnitAbbreviationsCache.Default); } @@ -28,13 +82,13 @@ public void UnitAbbreviationsCacheDefaultReturnsUnitsNetSetupDefaultUnitAbbrevia public void GetUnitAbbreviationsThrowsUnitNotFoundExceptionIfNoneExist() { Assert.Multiple(checks: [ - () => Assert.Throws(() => new UnitAbbreviationsCache().GetUnitAbbreviations(MassUnit.Gram)), - () => Assert.Throws(() => new UnitAbbreviationsCache().GetUnitAbbreviations(typeof(MassUnit), (int)MassUnit.Gram)) + () => Assert.Throws(() => new UnitAbbreviationsCache().GetUnitAbbreviations(HowMuchUnit.AShitTon)), + () => Assert.Throws(() => new UnitAbbreviationsCache().GetUnitAbbreviations(typeof(HowMuchUnit), (int)HowMuchUnit.AShitTon)) ]); } [Fact] - public void GetUnitAbbreviationsReturnsTheExpectedAbbreviationWhenConstructedWithTheSpecificQuantityInfo() + public void GetUnitAbbreviationReturnsTheExpectedAbbreviationWhenConstructedWithTheSpecificQuantityInfo() { Assert.Multiple(checks: [ @@ -43,6 +97,13 @@ public void GetUnitAbbreviationsReturnsTheExpectedAbbreviationWhenConstructedWit ]); } + [Fact] + public void GetUnitAbbreviationsReturnsTheExpectedAbbreviationWhenConstructedWithTheSpecificQuantityInfo() + { + var unitAbbreviationCache = new UnitAbbreviationsCache([Mass.Info]); + Assert.Equal("g", unitAbbreviationCache.GetUnitAbbreviations(MassUnit.Gram, AmericanCulture)[0]); + } + [Fact] public void GetDefaultAbbreviationReturnsTheExpectedAbbreviationWhenConstructedWithTheSpecificQuantityInfo() { @@ -61,7 +122,7 @@ public void GetDefaultAbbreviationFallsBackToUsEnglishCulture() // Zulu (South Africa) var zuluCulture = CultureInfo.GetCultureInfo("zu-ZA"); - var abbreviationsCache = new UnitAbbreviationsCache(); + var abbreviationsCache = new UnitAbbreviationsCache([HowMuch.Info]); abbreviationsCache.MapUnitToAbbreviation(HowMuchUnit.AShitTon, AmericanCulture, "US english abbreviation for Unit1"); // Act @@ -71,19 +132,68 @@ public void GetDefaultAbbreviationFallsBackToUsEnglishCulture() Assert.Equal("US english abbreviation for Unit1", abbreviation); } + [Fact] + public void GetDefaultAbbreviationFallsBackToInvariantCulture() + { + // CurrentCulture affects number formatting, such as comma or dot as decimal separator. + // CurrentCulture also affects localization of unit abbreviations. + // Zulu (South Africa) + var zuluCulture = CultureInfo.GetCultureInfo("zu-ZA"); + + var abbreviationsCache = new UnitAbbreviationsCache([HowMuch.Info]); + abbreviationsCache.MapUnitToAbbreviation(HowMuchUnit.AShitTon, CultureInfo.InvariantCulture, "Invariant abbreviation for Unit1"); + + // Act + string abbreviation = abbreviationsCache.GetDefaultAbbreviation(HowMuchUnit.AShitTon, zuluCulture); + + // Assert + Assert.Equal("Invariant abbreviation for Unit1", abbreviation); + } + + [Fact] + public void GetDefaultAbbreviation_WithNullUnitType_ThrowsArgumentNullException() + { + Assert.Throws(() => UnitAbbreviationsCache.Default.GetDefaultAbbreviation(null!, 1)); + } + [Fact] public void GetDefaultAbbreviationThrowsUnitNotFoundExceptionIfNoneExist() { Assert.Multiple(checks: [ - () => Assert.Throws(() => new UnitAbbreviationsCache().GetDefaultAbbreviation(MassUnit.Gram)), - () => Assert.Throws(() => new UnitAbbreviationsCache().GetDefaultAbbreviation(typeof(MassUnit), (int)MassUnit.Gram)) + () => Assert.Throws(() => new UnitAbbreviationsCache().GetDefaultAbbreviation(HowMuchUnit.AShitTon)), + () => Assert.Throws(() => new UnitAbbreviationsCache().GetDefaultAbbreviation(typeof(HowMuchUnit), (int)HowMuchUnit.AShitTon)) ]); } [Fact] - public void GetAbbreviationsThrowsArgumentNullExceptionWhenGivenANullUnitInfo() + public void GetDefaultAbbreviation_ForUnitWithoutAbbreviations_ThrowsInvalidOperationException() + { + Assert.Throws(() => new UnitAbbreviationsCache([HowMuch.Info]).GetDefaultAbbreviation(HowMuchUnit.AShitTon)); + } + + [Fact] + public void GetAllUnitAbbreviationsForQuantity_WithQuantityWithoutAbbreviations_ReturnsEmpty() { - Assert.Throws(() => new UnitAbbreviationsCache().GetAbbreviations(null!)); + var unitAbbreviationsCache = new UnitAbbreviationsCache([HowMuch.Info]); + Assert.Empty(unitAbbreviationsCache.GetAllUnitAbbreviationsForQuantity(typeof(HowMuchUnit))); + } + + [Fact] + public void GetAllUnitAbbreviationsForQuantity_WithNullUnitType_ThrowsArgumentNullException() + { + Assert.Throws(() => UnitAbbreviationsCache.Default.GetAllUnitAbbreviationsForQuantity(null!)); + } + + [Fact] + public void GetAllUnitAbbreviationsForQuantity_WithInvalidUnitType_ThrowsArgumentException() + { + Assert.Throws(() => UnitAbbreviationsCache.Default.GetAllUnitAbbreviationsForQuantity(typeof(DateTime))); + } + + [Fact] + public void GetAllUnitAbbreviationsForQuantity_WithUnknownUnitType_ThrowsUnitNotFoundException() + { + Assert.Throws(() => UnitAbbreviationsCache.Default.GetAllUnitAbbreviationsForQuantity(typeof(HowMuchUnit))); } [Fact] @@ -113,15 +223,6 @@ public void MapUnitToAbbreviation_AddCustomUnit_DoesNotOverrideDefaultAbbreviati Assert.Equal("m²", cache.GetDefaultAbbreviation(AreaUnit.SquareMeter, AmericanCulture)); } - [Fact] - public void MapUnitToDefaultAbbreviation_GivenUnitAndCulture_SetsDefaultAbbreviationForUnitAndCulture() - { - var cache = new UnitAbbreviationsCache(); - cache.MapUnitToDefaultAbbreviation(AreaUnit.SquareMeter, AmericanCulture, "m^2"); - - Assert.Equal("m^2", cache.GetDefaultAbbreviation(AreaUnit.SquareMeter, AmericanCulture)); - } - [Fact] public void MapUnitToDefaultAbbreviation_GivenUnitAndNoCulture_SetsDefaultAbbreviationForUnitForCurrentCulture() { @@ -135,15 +236,21 @@ public void MapUnitToDefaultAbbreviation_GivenUnitAndNoCulture_SetsDefaultAbbrev } [Fact] - public void MapUnitToDefaultAbbreviation_GivenUnitTypeAndValue_SetsDefaultAbbreviationForUnitForCurrentCulture() + public void MapUnitToDefaultAbbreviation_GivenUnitAndCulture_SetsDefaultAbbreviationForUnitAndCulture() { - using var cultureScope = new CultureScope(NorwegianCulture); - var cache = new UnitAbbreviationsCache([Mass.Info]); + var cache = new UnitAbbreviationsCache([Area.Info]); + cache.MapUnitToDefaultAbbreviation(AreaUnit.SquareMeter, AmericanCulture, "m^2"); - cache.MapUnitToDefaultAbbreviation(typeof(MassUnit), (int)MassUnit.Gram, null, "zz"); + Assert.Equal("m^2", cache.GetDefaultAbbreviation(AreaUnit.SquareMeter, AmericanCulture)); + } - Assert.Equal("zz", cache.GetDefaultAbbreviation(MassUnit.Gram)); - Assert.Equal("g", cache.GetDefaultAbbreviation(MassUnit.Gram, AmericanCulture)); + [Fact] + public void MapUnitToDefaultAbbreviation_GivenUnitTypeValueAndCulture_SetsDefaultAbbreviationForUnitAndCulture() + { + var cache = new UnitAbbreviationsCache([Area.Info]); + cache.MapUnitToDefaultAbbreviation(typeof(AreaUnit), (int)AreaUnit.SquareMeter, AmericanCulture, "m^2"); + + Assert.Equal("m^2", cache.GetDefaultAbbreviation(AreaUnit.SquareMeter, AmericanCulture)); } [Fact] @@ -172,7 +279,7 @@ public void MapUnitToAbbreviation_GivenUnitTypeAndValue_AddsTheAbbreviationForUn [Fact] public void MapUnitToAbbreviation_DoesNotInsertDuplicates() { - var cache = new UnitAbbreviationsCache(); + var cache = new UnitAbbreviationsCache([HowMuch.Info]); cache.MapUnitToAbbreviation(HowMuchUnit.Some, "sm"); cache.MapUnitToAbbreviation(HowMuchUnit.Some, "sm"); @@ -186,7 +293,7 @@ public void MapUnitToAbbreviation_DoesNotInsertDuplicates() [Fact] public void MapUnitToDefaultAbbreviation_Twice_SetsNewDefaultAndKeepsOrderOfExistingAbbreviations() { - var cache = new UnitAbbreviationsCache(); + var cache = new UnitAbbreviationsCache([HowMuch.Info]); cache.MapUnitToAbbreviation(HowMuchUnit.Some, "sm"); cache.MapUnitToDefaultAbbreviation(HowMuchUnit.Some, "1st default"); @@ -204,8 +311,44 @@ public void MapUnitToDefaultAbbreviation_Twice_SetsNewDefaultAndKeepsOrderOfExis [Fact] public void MapAndLookup_WithSpecificEnumType() { - UnitsNetSetup.Default.UnitAbbreviations.MapUnitToDefaultAbbreviation(HowMuchUnit.Some, "sm"); - Assert.Equal("sm", UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(HowMuchUnit.Some)); + var unitAbbreviationsCache = new UnitAbbreviationsCache([HowMuch.Info]); + unitAbbreviationsCache.MapUnitToDefaultAbbreviation(HowMuchUnit.Some, "sm"); + Assert.Equal("sm", unitAbbreviationsCache.GetDefaultAbbreviation(HowMuchUnit.Some)); + } + + /// + [Fact] + public void MapAndLookup_WithEnumType() + { + Enum valueAsEnumType = HowMuchUnit.Some; + var unitAbbreviationsCache = new UnitAbbreviationsCache([HowMuch.Info]); + unitAbbreviationsCache.MapUnitToDefaultAbbreviation(valueAsEnumType, "sm"); + Assert.Equal("sm", unitAbbreviationsCache.GetDefaultAbbreviation(valueAsEnumType)); + } + + /// + [Fact] + public void MapAndLookup_MapWithSpecificEnumType_LookupWithEnumType() + { + var unitAbbreviationsCache = new UnitAbbreviationsCache([HowMuch.Info]); + unitAbbreviationsCache.MapUnitToDefaultAbbreviation(HowMuchUnit.Some, "sm"); + Assert.Equal("sm", unitAbbreviationsCache.GetDefaultAbbreviation((Enum)HowMuchUnit.Some)); + } + + [Fact] + public void MapUnitToAbbreviation_WithUnknownUnit_ThrowsUnitNotFoundException() + { + var unitAbbreviationCache = new UnitAbbreviationsCache([Mass.Info]); + Assert.Throws(() => unitAbbreviationCache.MapUnitToAbbreviation(HowMuchUnit.Some, "nothing")); + Assert.Throws(() => unitAbbreviationCache.MapUnitToAbbreviation(LengthUnit.Centimeter, "nothing")); + } + + [Fact] + public void MapUnitToDefaultAbbreviation_WithUnknownUnit_ThrowsUnitNotFoundException() + { + var unitAbbreviationCache = new UnitAbbreviationsCache([Mass.Info]); + Assert.Throws(() => unitAbbreviationCache.MapUnitToDefaultAbbreviation(HowMuchUnit.Some, "nothing")); + Assert.Throws(() => unitAbbreviationCache.MapUnitToDefaultAbbreviation(LengthUnit.AstronomicalUnit, "nothing")); } } } 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/UnitInfoTests.cs b/UnitsNet.Tests/UnitInfoTests.cs index e05e3a51f9..1b428c442d 100644 --- a/UnitsNet.Tests/UnitInfoTests.cs +++ b/UnitsNet.Tests/UnitInfoTests.cs @@ -1,27 +1,125 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. -using UnitsNet.Units; -using Xunit; +namespace UnitsNet.Tests; -namespace UnitsNet.Tests +public class UnitInfoTests { - public class UnitInfoTests + [Fact] + public void UnitInfo_QuantityInfo_ReturnsTheParentQuantityInfo() { - [Fact] - public void ConstructorTest() + Assert.Multiple(() => { - var unitInfo = new UnitInfo(LengthUnit.Meter, "Meters", new BaseUnits(LengthUnit.Meter), nameof(Length)); - Assert.Equal(LengthUnit.Meter, unitInfo.Value); - Assert.Equal(LengthUnit.Meter.ToString(), unitInfo.Name); - } + UnitInfo unitInfo = Mass.Info.BaseUnitInfo; - [Fact] - public void GenericConstructorTest() + QuantityInfo quantityInfo = unitInfo.QuantityInfo; + + Assert.Equal(Mass.Info, quantityInfo); + }, () => + { + UnitInfo unitInfo = Mass.Info.BaseUnitInfo; + + QuantityInfo quantityInfo = unitInfo.QuantityInfo; + + Assert.Equal(Mass.Info, quantityInfo); + }); + } + + [Fact] + public void UnitInfo_QuantityName_ReturnsTheParentQuantityName() + { + Assert.Equal(Mass.Info.Name, Mass.Info.BaseUnitInfo.QuantityName); + } + + [Fact] + public void UnitInfo_Value_ReturnsTheUnitValue() + { + Assert.Multiple(() => + { + UnitInfo unitInfo = Mass.Info.BaseUnitInfo; + + MassUnit unitInfoValue = unitInfo.Value; + + Assert.Equal(Mass.BaseUnit, unitInfoValue); + }, () => + { + UnitInfo unitInfo = Mass.Info.BaseUnitInfo; + + MassUnit unitInfoValue = unitInfo.Value; + + Assert.Equal(Mass.BaseUnit, unitInfoValue); + }, () => + { + UnitInfo unitInfo = Mass.Info.BaseUnitInfo; + + Enum unitInfoValue = unitInfo.Value; + + Assert.Equal(Mass.BaseUnit, unitInfoValue); + }); + } + + [Fact] + public void UnitInfo_UnitKey_ReturnsTheUnitKey() + { + Assert.Multiple(() => + { + UnitInfo unitInfo = Mass.Info.BaseUnitInfo; + + UnitKey unitInfoValue = unitInfo.UnitKey; + + Assert.Equal(Mass.BaseUnit, unitInfoValue); + }, () => + { + UnitInfo unitInfo = Mass.Info.BaseUnitInfo; + + UnitKey unitInfoValue = unitInfo.UnitKey; + + Assert.Equal(Mass.BaseUnit, unitInfoValue); + }, () => + { + UnitInfo unitInfo = Mass.Info.BaseUnitInfo; + + UnitKey unitInfoValue = unitInfo.UnitKey; + + Assert.Equal(Mass.BaseUnit, unitInfoValue); + }); + } + + [Theory] + [InlineData(1, MassUnit.Kilogram)] + [InlineData(2, MassUnit.Milligram)] + public void UnitInfo_FromValueAndUnit_ReturnsTheExpectedQuantity(double value, MassUnit unit) + { + var expectedQuantity = new Mass(value, unit); + Assert.Multiple(() => + { + UnitInfo unitInfo = Mass.Info[unit]; + + Mass quantity = unitInfo.From(value); + + Assert.Equal(expectedQuantity, quantity); + }, () => + { + UnitInfo unitInfo = Mass.Info[unit]; + + IQuantity quantity = unitInfo.From(value); + + Assert.Equal(expectedQuantity, quantity); + }, () => { - var unitInfo = new UnitInfo(LengthUnit.Meter, "Meters", new BaseUnits(LengthUnit.Meter), nameof(Length)); - Assert.Equal(LengthUnit.Meter, unitInfo.Value); - Assert.Equal(LengthUnit.Meter.ToString(), unitInfo.Name); - } + UnitInfo unitInfo = Mass.Info[unit]; + + IQuantity quantity = unitInfo.From(value); + + Assert.Equal(expectedQuantity, quantity); + }); + } + + [Fact] + public void ToString_ReturnsTheUnitName() + { + UnitInfo unitInfo = Mass.Info.BaseUnitInfo; + + Assert.Equal(unitInfo.Name, unitInfo.ToString()); } } diff --git a/UnitsNet.Tests/UnitKeyTest.cs b/UnitsNet.Tests/UnitKeyTest.cs index 28b78eeb47..469bed03b8 100644 --- a/UnitsNet.Tests/UnitKeyTest.cs +++ b/UnitsNet.Tests/UnitKeyTest.cs @@ -23,16 +23,16 @@ public enum TestUnit public void Constructor_ShouldCreateUnitKey(int unitValue) { var unitKey = new UnitKey(typeof(TestUnit), unitValue); - Assert.Equal(typeof(TestUnit), unitKey.UnitType); - Assert.Equal(unitValue, unitKey.UnitValue); + Assert.Equal(typeof(TestUnit), unitKey.UnitEnumType); + Assert.Equal(unitValue, unitKey.UnitEnumValue); } [Fact] public void Constructor_WithNullType_ShouldNotThrow() { var unitKey = new UnitKey(null!, 0); - Assert.Null(unitKey.UnitType); - Assert.Equal(0, unitKey.UnitValue); + Assert.Null(unitKey.UnitEnumType); + Assert.Equal(0, unitKey.UnitEnumValue); } [Theory] @@ -42,8 +42,8 @@ public void Constructor_WithNullType_ShouldNotThrow() public void ForUnit_ShouldCreateUnitKey(TestUnit unit) { var unitKey = UnitKey.ForUnit(unit); - Assert.Equal(typeof(TestUnit), unitKey.UnitType); - Assert.Equal((int)unit, unitKey.UnitValue); + Assert.Equal(typeof(TestUnit), unitKey.UnitEnumType); + Assert.Equal((int)unit, unitKey.UnitEnumValue); } [Theory] @@ -53,8 +53,31 @@ public void ForUnit_ShouldCreateUnitKey(TestUnit unit) public void Create_ShouldCreateUnitKey(int unitValue) { var unitKey = UnitKey.Create(unitValue); - Assert.Equal(typeof(TestUnit), unitKey.UnitType); - Assert.Equal(unitValue, unitKey.UnitValue); + Assert.Equal(typeof(TestUnit), unitKey.UnitEnumType); + Assert.Equal(unitValue, unitKey.UnitEnumValue); + } + + [Theory] + [InlineData(typeof(TestUnit), 1)] + [InlineData(typeof(TestUnit), 2)] + [InlineData(typeof(TestUnit), 3)] + public void Create_WithUnitTypeAndUnitValue_ShouldCreateUnitKey(Type unitType, int unitValue) + { + var unitKey = UnitKey.Create(unitType, unitValue); + Assert.Equal(unitType, unitKey.UnitEnumType); + Assert.Equal(unitValue, unitKey.UnitEnumValue); + } + + [Fact] + public void Create_WithNullUnitType_ShouldThrowArgumentNullException() + { + Assert.Throws(() => UnitKey.Create(null!, 0)); + } + + [Fact] + public void Create_WithNonEnumType_ShouldThrowArgumentException() + { + Assert.Throws(() => UnitKey.Create(typeof(int), 1)); } [Theory] @@ -64,8 +87,8 @@ public void Create_ShouldCreateUnitKey(int unitValue) public void ImplicitConversion_ShouldCreateUnitKey(TestUnit unit) { UnitKey unitKey = unit; - Assert.Equal(typeof(TestUnit), unitKey.UnitType); - Assert.Equal((int)unit, unitKey.UnitValue); + Assert.Equal(typeof(TestUnit), unitKey.UnitEnumType); + Assert.Equal((int)unit, unitKey.UnitEnumValue); } [Theory] @@ -94,8 +117,8 @@ public void ToUnit_ShouldReturnEnum(TestUnit unit) public void Default_InitializesWithoutAType() { var defaultUnitKey = default(UnitKey); - Assert.Null(defaultUnitKey.UnitType); - Assert.Equal(0, defaultUnitKey.UnitValue); + Assert.Null(defaultUnitKey.UnitEnumType); + Assert.Equal(0, defaultUnitKey.UnitEnumValue); } [Fact] @@ -139,7 +162,7 @@ public void Deconstruct_ShouldReturnTheUnitTypeAndUnitValue() [InlineData(TestUnit.Unit1, "TestUnit.Unit1")] [InlineData(TestUnit.Unit2, "TestUnit.Unit2")] [InlineData(TestUnit.Unit3, "TestUnit.Unit3")] - [InlineData((TestUnit)(-1), "UnitType: UnitsNet.Tests.UnitKeyTest+TestUnit, UnitValue = -1")] + [InlineData((TestUnit)(-1), "UnitEnumType: UnitsNet.Tests.UnitKeyTest+TestUnit, UnitEnumValue = -1")] public void GetDebuggerDisplay_ShouldReturnCorrectString(TestUnit unit, string expectedDisplay) { var unitKey = UnitKey.ForUnit(unit); @@ -154,6 +177,6 @@ public void GetDebuggerDisplayWithDefault_ShouldReturnCorrectString() var defaultUnitKey = default(UnitKey); var display = defaultUnitKey.GetType().GetMethod("GetDebuggerDisplay", BindingFlags.NonPublic | BindingFlags.Instance)! .Invoke(defaultUnitKey, null); - Assert.Equal("UnitType: , UnitValue = 0", display); + Assert.Equal("UnitEnumType: , UnitEnumValue = 0", display); } } 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/UnitParserTests.cs b/UnitsNet.Tests/UnitParserTests.cs index 17b2007e40..de3fa48a26 100644 --- a/UnitsNet.Tests/UnitParserTests.cs +++ b/UnitsNet.Tests/UnitParserTests.cs @@ -1,22 +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.Globalization; using UnitsNet.Tests.CustomQuantities; -using UnitsNet.Units; -using Xunit; namespace UnitsNet.Tests { public class UnitParserTests { + [Fact] + public void Constructor_WithQuantitiesCreatesNewAbbreviationsCacheAndNewQuantityInfoLookup() + { + var unitParser = new UnitParser([Mass.Info]); + Assert.NotNull(unitParser.Abbreviations); + Assert.NotEqual(UnitAbbreviationsCache.Default, unitParser.Abbreviations); + Assert.NotEqual(UnitsNetSetup.Default.QuantityInfoLookup, unitParser.Quantities); + } + + [Fact] + public void Constructor_WithQuantityInfoLookupCreatesNewAbbreviationsCache() + { + var quantities = new QuantityInfoLookup([Mass.Info]); + var unitParser = new UnitParser(quantities); + Assert.NotNull(unitParser.Abbreviations); + Assert.NotEqual(UnitAbbreviationsCache.Default, unitParser.Abbreviations); + Assert.Equal(quantities, unitParser.Quantities); + } + + [Fact] + public void CreateDefault_CreatesNewAbbreviationsCacheWithDefaultQuantities() + { + var unitParser = UnitParser.CreateDefault(); + Assert.NotNull(unitParser.Abbreviations); + Assert.NotEqual(UnitAbbreviationsCache.Default, unitParser.Abbreviations); + Assert.Equal(UnitsNetSetup.Default.QuantityInfoLookup, unitParser.Quantities); + } + [Theory] [InlineData("m^^2", AreaUnit.SquareMeter)] [InlineData("cm^^2", AreaUnit.SquareCentimeter)] public void Parse_ReturnsUnitMappedByCustomAbbreviation(string customAbbreviation, AreaUnit expected) { - var abbrevCache = new UnitAbbreviationsCache(); + var abbrevCache = new UnitAbbreviationsCache([Area.Info]); abbrevCache.MapUnitToAbbreviation(expected, customAbbreviation); var parser = new UnitParser(abbrevCache); @@ -59,9 +84,17 @@ public void Parse_GivenAbbreviationsThatAreAmbiguousWhenLowerCase_ReturnsCorrect [Fact] public void Parse_NullAbbreviation_Throws_ArgumentNullException() { + Assert.Throws(() => UnitsNetSetup.Default.UnitParser.Parse(null!)); + Assert.Throws(() => UnitsNetSetup.Default.UnitParser.Parse(null!, Length.Info.UnitInfos)); Assert.Throws(() => UnitsNetSetup.Default.UnitParser.Parse(null!, typeof(LengthUnit))); } + [Fact] + public void Parse_UnknownUnitTypeThrowsUnitNotFoundException() + { + Assert.Throws(() => UnitsNetSetup.Default.UnitParser.Parse("something")); + } + [Fact] public void Parse_UnknownAbbreviationThrowsUnitNotFoundException() { @@ -129,13 +162,16 @@ public void Parse_AmbiguousUnitsThrowsException() [InlineData("kg", "ru-RU", MassUnit.Kilogram)] // should work with the "FallbackCulture" public void ParseMassUnit_GivenCulture(string str, string cultureName, Enum expectedUnit) { - Assert.Equal(expectedUnit, UnitsNetSetup.Default.UnitParser.Parse(str, CultureInfo.GetCultureInfo(cultureName))); + var formatProvider = CultureInfo.GetCultureInfo(cultureName); + UnitParser unitParser = UnitsNetSetup.Default.UnitParser; + + Assert.Equal(expectedUnit, unitParser.Parse(str, formatProvider)); } - + [Fact] public void Parse_MappedCustomUnit() { - var unitAbbreviationsCache = new UnitAbbreviationsCache(); + var unitAbbreviationsCache = new UnitAbbreviationsCache([HowMuch.Info]); unitAbbreviationsCache.MapUnitToAbbreviation(HowMuchUnit.Some, "fooh"); var unitParser = new UnitParser(unitAbbreviationsCache); @@ -150,7 +186,7 @@ public void Parse_LengthUnit_MM_ThrowsExceptionDescribingTheAmbiguity() var ex = Assert.Throws(() => UnitsNetSetup.Default.UnitParser.Parse("MM")); Assert.Equal("""Cannot parse "MM" since it matches multiple units: Megameter ("Mm"), Millimeter ("mm").""", ex.Message); } - + [Fact] public void TryParse_WithNullAbbreviation_ReturnsFalse() { @@ -163,13 +199,26 @@ public void TryParse_WithNullAbbreviation_ReturnsFalse() { var success = unitParser.TryParse(null, typeof(LengthUnit), out Enum? _); Assert.False(success); + }, () => + { + var success = unitParser.TryParse(null, [], null, out UnitInfo? _); + Assert.False(success); }); } [Fact] - public void TryParse_UnknownAbbreviation_ReturnsFalse() + public void TryParse_UnknownUnitType_ReturnsFalse() { - Assert.False(UnitsNetSetup.Default.UnitParser.TryParse("nonexistingunit", out AreaUnit _)); + Assert.False(UnitsNetSetup.Default.UnitParser.TryParse("something", out StringComparison _)); + } + + [Theory] + [InlineData("")] + [InlineData("z^2")] + [InlineData("nonexistingunit")] + public void TryParse_UnknownAbbreviation_ReturnsFalse(string unknownAreaAbbreviation) + { + Assert.False(UnitsNetSetup.Default.UnitParser.TryParse(unknownAreaAbbreviation, out AreaUnit _)); } [Fact] @@ -177,6 +226,7 @@ public void TryParse_WithAmbiguousUnits_ReturnsFalse() { UnitParser unitParser = UnitsNetSetup.Default.UnitParser; Assert.False(unitParser.TryParse("pt", CultureInfo.InvariantCulture, out LengthUnit _)); + Assert.False(unitParser.TryParse("pt", Length.Info.UnitInfos, CultureInfo.InvariantCulture, out UnitInfo? _)); } [Theory] @@ -197,5 +247,58 @@ public void TryParseMassUnit_GivenCulture(string str, string cultureName, Enum e Assert.True(success); Assert.Equal(expectedUnit, unitParsed); } + + [Fact] + public void TryGetUnitFromAbbreviation_WithLocalizedUnit_MatchingCulture_ReturnsTrue() + { + var formatProvider = CultureInfo.GetCultureInfo("ru-RU"); + UnitParser unitParser = UnitsNetSetup.Default.UnitParser; + + var success = unitParser.TryGetUnitFromAbbreviation("кг", formatProvider, out UnitInfo? unitInfo); + + Assert.True(success); + Assert.Equal(Mass.Info[MassUnit.Kilogram], unitInfo); + } + + [Fact] + public void TryGetUnitFromAbbreviation_MatchingFallbackCulture_ReturnsTrue() + { + var formatProvider = CultureInfo.GetCultureInfo("ru-RU"); + UnitParser unitParser = UnitsNetSetup.Default.UnitParser; + + var success = unitParser.TryGetUnitFromAbbreviation("kg", formatProvider, out UnitInfo? unitInfo); + + Assert.True(success); + Assert.Equal(Mass.Info[MassUnit.Kilogram], unitInfo); + } + + [Fact] + public void TryGetUnitFromAbbreviation_WithNullString_ReturnsFalse() + { + var success = UnitsNetSetup.Default.UnitParser.TryGetUnitFromAbbreviation(null, CultureInfo.InvariantCulture, out UnitInfo? _); + + Assert.False(success); + } + + [Fact] + public void GetUnitFromAbbreviation_GivenAbbreviationsThatAreAmbiguousWhenLowerCase_ReturnsCorrectUnit() + { + Assert.Equal(PressureUnit.Megabar, UnitParser.Default.GetUnitFromAbbreviation("Mbar", CultureInfo.InvariantCulture).Value); + Assert.Equal(PressureUnit.Millibar, UnitParser.Default.GetUnitFromAbbreviation("mbar", CultureInfo.InvariantCulture).Value); + } + + [Fact] + public void GetUnitFromAbbreviation_NullAbbreviation_Throws_ArgumentNullException() + { + Assert.Throws(() => UnitsNetSetup.Default.UnitParser.GetUnitFromAbbreviation(null!, CultureInfo.InvariantCulture)); + } + + [Theory] + [InlineData("z^2")] + [InlineData("nonexistingunit")] + public void GetUnitFromAbbreviation_UnknownAbbreviationThrowsUnitNotFoundException(string unknownAbbreviation) + { + Assert.Throws(() => UnitsNetSetup.Default.UnitParser.GetUnitFromAbbreviation(unknownAbbreviation, CultureInfo.InvariantCulture)); + } } } 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 d23783c60f..7acaa099f4 100644 --- a/UnitsNet.Tests/UnitsNet.Tests.csproj +++ b/UnitsNet.Tests/UnitsNet.Tests.csproj @@ -1,11 +1,13 @@  - net8.0;net9.0 + net48;net8.0;net9.0 latest + enable true CS0618 enable + xunit @@ -29,11 +31,17 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - + + + + + + + diff --git a/UnitsNet.sln b/UnitsNet.sln index 878ab0a2d7..42f441e6e7 100644 --- a/UnitsNet.sln +++ b/UnitsNet.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29609.76 +# Visual Studio Version 17 +VisualStudioVersion = 17.13.35828.75 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitsNet", "UnitsNet\UnitsNet.csproj", "{CBEAD842-07BC-4B08-9D9D-D6659813776F}" EndProject @@ -20,46 +20,46 @@ EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitsNet.NumberExtensions.Tests", "UnitsNet.NumberExtensions.Tests\UnitsNet.NumberExtensions.Tests.csproj", "{B4996AF5-9A8B-481A-9018-EC7F5B1605FF}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_Files", "_Files", "{B92B01BE-243E-4CCB-B5E5-AF469ADB1F54}" -ProjectSection(SolutionItems) = preProject - .editorconfig = .editorconfig - .gitattributes = .gitattributes - .gitignore = .gitignore - build.bat = build.bat - build-all-targets.bat = build-all-targets.bat - clean.bat = clean.bat - CODE_OF_CONDUCT.md = CODE_OF_CONDUCT.md - CONTRIBUTING.md = CONTRIBUTING.md - Directory.Build.props = Directory.Build.props - generate-code.bat = generate-code.bat - init.bat = init.bat - LICENSE = LICENSE - nuget.config = nuget.config - publish-unitsnet.bat = publish-unitsnet.bat - README.md = README.md - test.bat = test.bat - UnitsNet.sln.DotSettings = UnitsNet.sln.DotSettings - UnitsNet.snk = UnitsNet.snk - azure-pipelines.yml = azure-pipelines.yml - Directory.Packages.props = Directory.Packages.props -EndProjectSection + ProjectSection(SolutionItems) = preProject + .editorconfig = .editorconfig + .gitattributes = .gitattributes + .gitignore = .gitignore + azure-pipelines.yml = azure-pipelines.yml + build-all-targets.bat = build-all-targets.bat + build.bat = build.bat + clean.bat = clean.bat + CODE_OF_CONDUCT.md = CODE_OF_CONDUCT.md + CONTRIBUTING.md = CONTRIBUTING.md + Directory.Build.props = Directory.Build.props + Directory.Packages.props = Directory.Packages.props + generate-code.bat = generate-code.bat + init.bat = init.bat + LICENSE = LICENSE + nuget.config = nuget.config + publish-unitsnet.bat = publish-unitsnet.bat + README.md = README.md + test.bat = test.bat + UnitsNet.sln.DotSettings = UnitsNet.sln.DotSettings + UnitsNet.snk = UnitsNet.snk + EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Build", "Build", "{71C6EF60-7E52-4DF4-BA93-5FAF6D89AEC6}" ProjectSection(SolutionItems) = preProject - Build\build.ps1 = Build\build.ps1 Build\build-functions.psm1 = Build\build-functions.psm1 Build\build-pack-nano-nugets.psm1 = Build\build-pack-nano-nugets.psm1 - Build\init.ps1 = Build\init.ps1 - Build\clean.ps1 = Build\clean.ps1 - Build\bump-version.bat = Build\bump-version.bat - Build\bump-version.sh = Build\bump-version.sh + Build\build.ps1 = Build\build.ps1 Build\bump-version-json.bat = Build\bump-version-json.bat Build\bump-version-json.sh = Build\bump-version-json.sh + Build\bump-version.bat = Build\bump-version.bat + Build\bump-version.sh = Build\bump-version.sh + Build\clean.ps1 = Build\clean.ps1 Build\codecov.sh = Build\codecov.sh - Build\set-version.psm1 = Build\set-version.psm1 - Build\set-version.sh = Build\set-version.sh + Build\init.ps1 = Build\init.ps1 Build\set-version-json.sh = Build\set-version-json.sh Build\set-version-UnitsNet.ps1 = Build\set-version-UnitsNet.ps1 Build\set-version-UnitsNet.Serialization.JsonNet.ps1 = Build\set-version-UnitsNet.Serialization.JsonNet.ps1 + Build\set-version.psm1 = Build\set-version.psm1 + Build\set-version.sh = Build\set-version.sh EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PerfTest_Startup", "PerfTests\PerfTest_Startup\PerfTest_Startup.csproj", "{BFF3DD22-0F58-4E79-86CD-662D1A174224}" @@ -70,6 +70,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "PerfTests", "PerfTests", "{ EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PerfTest_Startup_v4_72_0", "PerfTests\PerfTest_Startup_v4_72_0\PerfTest_Startup_v4_72_0.csproj", "{7131F7CC-BD7F-44EB-AD50-AE80CE38F28E}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitsNet.Serialization.SystemTextJson", "UnitsNet.Serialization.SystemTextJson\UnitsNet.Serialization.SystemTextJson.csproj", "{712419E5-5EAF-9B97-AEAB-CE449D2EAA29}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitsNet.Serialization.SystemTextJson.Tests", "UnitsNet.Serialization.SystemTextJson.Tests\UnitsNet.Serialization.SystemTextJson.Tests.csproj", "{EF75262E-DE78-005C-0867-2B4D647A141A}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -120,17 +124,25 @@ Global {7131F7CC-BD7F-44EB-AD50-AE80CE38F28E}.Debug|Any CPU.Build.0 = Debug|Any CPU {7131F7CC-BD7F-44EB-AD50-AE80CE38F28E}.Release|Any CPU.ActiveCfg = Release|Any CPU {7131F7CC-BD7F-44EB-AD50-AE80CE38F28E}.Release|Any CPU.Build.0 = Release|Any CPU + {712419E5-5EAF-9B97-AEAB-CE449D2EAA29}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {712419E5-5EAF-9B97-AEAB-CE449D2EAA29}.Debug|Any CPU.Build.0 = Debug|Any CPU + {712419E5-5EAF-9B97-AEAB-CE449D2EAA29}.Release|Any CPU.ActiveCfg = Release|Any CPU + {712419E5-5EAF-9B97-AEAB-CE449D2EAA29}.Release|Any CPU.Build.0 = Release|Any CPU + {EF75262E-DE78-005C-0867-2B4D647A141A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EF75262E-DE78-005C-0867-2B4D647A141A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EF75262E-DE78-005C-0867-2B4D647A141A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EF75262E-DE78-005C-0867-2B4D647A141A}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {554906B2-5972-4EBF-9DD5-EEFA77D735D8} - EndGlobalSection GlobalSection(NestedProjects) = preSolution {71C6EF60-7E52-4DF4-BA93-5FAF6D89AEC6} = {B92B01BE-243E-4CCB-B5E5-AF469ADB1F54} {BFF3DD22-0F58-4E79-86CD-662D1A174224} = {126F0393-A678-4609-9341-7028F1B2BC2B} {2E68C361-F6FA-49DC-BB0E-85ADE776391E} = {126F0393-A678-4609-9341-7028F1B2BC2B} {7131F7CC-BD7F-44EB-AD50-AE80CE38F28E} = {126F0393-A678-4609-9341-7028F1B2BC2B} EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {554906B2-5972-4EBF-9DD5-EEFA77D735D8} + EndGlobalSection EndGlobal diff --git a/UnitsNet/Comparison.cs b/UnitsNet/Comparison.cs index 8971906b04..07e84c0326 100644 --- a/UnitsNet/Comparison.cs +++ b/UnitsNet/Comparison.cs @@ -3,123 +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"); + ComparisonType.Relative => EqualsRelative(referenceValue, otherValue, tolerance), + ComparisonType.Absolute => EqualsAbsolute(referenceValue, otherValue, tolerance), + _ => throw new InvalidOperationException("The given ComparisonType is not supported.") + }; + } - 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."); - } + /// + /// 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)) + { + 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 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 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"); - - var maxVariation = Math.Abs(referenceValue * tolerance); - return Math.Abs(referenceValue - otherValue) <= maxVariation; + throw ExceptionHelper.CreateArgumentOutOfRangeExceptionForNegativeTolerance(nameof(tolerance)); } - /// - /// Checks if two values are equal with a given absolute tolerance. - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between - /// and - /// as a fixed number. - /// - /// In this example, the two values will be equal if abs( - - /// ) <= 0.01 - /// - /// Equals(a, b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// The first value. - /// The second value. - /// The absolute tolerance. Must be greater than or equal to 0. - /// True if the two values are equal within the given absolute tolerance, otherwise false. - public static bool EqualsAbsolute(double value1, double value2, double tolerance) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0"); + return QuantityValue.Abs(value1 - value2) <= tolerance; + } - return Math.Abs(value1 - value2) <= tolerance; + internal static int GetHashCode(Type type, QuantityValue value) + { +#if NET7_0_OR_GREATER + 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/Quantities/Temperature.extra.cs b/UnitsNet/CustomCode/Quantities/Temperature.extra.cs index 4556009fc6..89d2d4a342 100644 --- a/UnitsNet/CustomCode/Quantities/Temperature.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Temperature.extra.cs @@ -1,6 +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; namespace UnitsNet @@ -58,9 +59,10 @@ public partial struct Temperature /// Factor to multiply by. /// Unit to perform multiplication in. /// The resulting . - public Temperature Multiply(double factor, TemperatureUnit unit) + [Obsolete("Affine quantities, such as the Temperate, cannot be multiplied directly: consider using the TemperatureDelta type instead.")] + public Temperature Multiply(QuantityValue factor, TemperatureUnit unit) { - double resultInUnit = As(unit) * factor; + QuantityValue resultInUnit = this.As(unit) * factor; return From(resultInUnit, unit); } @@ -75,10 +77,48 @@ public Temperature Multiply(double factor, TemperatureUnit unit) /// Factor to multiply by. /// Unit to perform multiplication in. /// The resulting . - public Temperature Divide(double divisor, TemperatureUnit unit) + [Obsolete("Affine quantities, such as the Temperate, cannot be divided directly: consider using the TemperatureDelta type instead.")] + public Temperature Divide(QuantityValue divisor, TemperatureUnit unit) { - double resultInUnit = As(unit) / divisor; + QuantityValue resultInUnit = this.As(unit) / divisor; return From(resultInUnit, unit); } + + // /// + // public bool Equals(IQuantity? other, IQuantity tolerance) + // { + // return Comparison.EqualsAbsolute(this, other, tolerance); + // } + + /// /> + [Obsolete("Affine quantities, such as the Temperate, should use an offset-based tolerance: consider using the TemperatureDelta type instead.")] + public bool Equals(Temperature other, Temperature tolerance) + { + if (QuantityValue.IsNegative(tolerance.Value)) + { + throw ExceptionHelper.CreateArgumentOutOfRangeExceptionForNegativeTolerance(nameof(tolerance)); + } + + var unitKey = UnitKey.ForUnit(tolerance.Unit); + return Comparison.EqualsAbsolute(this.GetValue(unitKey), other.GetValue(unitKey), tolerance.Value); + } + + // /// + // /// Determines whether the specified object is equal to the current instance within a given tolerance. + // /// + // /// The object to compare with the current instance. + // /// The tolerance within which the two objects are considered equal. + // /// + // /// true if the specified object is equal to the current instance within the given tolerance; otherwise, false. + // /// + // /// + // /// This method compares the absolute values of the temperatures and checks if the difference is within the specified tolerance. + // /// + // public bool Equals(Temperature other, TemperatureDelta tolerance) + // { + // return this.EqualsAbsolute(other, tolerance); + // // return AffineQuantityExtensions.Equals(this, other, tolerance); + // } + } } diff --git a/UnitsNet/CustomCode/Quantity.cs b/UnitsNet/CustomCode/Quantity.cs index d606ea55da..2558d7dce4 100644 --- a/UnitsNet/CustomCode/Quantity.cs +++ b/UnitsNet/CustomCode/Quantity.cs @@ -1,44 +1,41 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Globalization; -using UnitsNet.Units; +using System.Globalization; namespace UnitsNet { - public partial class Quantity + public static partial class Quantity { private static QuantityInfoLookup Quantities => UnitsNetSetup.Default.QuantityInfoLookup; + private static QuantityParser QuantityParser => UnitsNetSetup.Default.QuantityParser; private static UnitParser UnitParser => UnitsNetSetup.Default.UnitParser; /// - /// All quantity names of , such as "Length" and "Mass". + /// All quantity names, such as "Length" and "Mass", that are present in the configuration. /// public static IReadOnlyCollection Names => Quantities.Names; /// - /// All quantity information objects, such as and . + /// All quantity information objects, such as and , that are present in the configuration. /// public static IReadOnlyList Infos => Quantities.Infos; /// - /// Get for a given unit enum value. + /// All QuantityInfo instances mapped by quantity name that are present in the configuration. /// - public static UnitInfo GetUnitInfo(Enum unitEnum) => Quantities.GetUnitInfo(unitEnum); + public static IReadOnlyDictionary ByName => Quantities.ByName; /// - /// Try to get for a given unit enum value. + /// Get for a given unit enum value. /// - public static bool TryGetUnitInfo(Enum unitEnum, [NotNullWhen(true)] out UnitInfo? unitInfo) => - Quantities.TryGetUnitInfo(unitEnum, out unitInfo); + public static UnitInfo GetUnitInfo(UnitKey unitEnum) => Quantities.GetUnitInfo(unitEnum); /// - /// + /// Try to get for a given unit enum value. /// - /// - /// - public static void AddUnitInfo(Enum unit, UnitInfo unitInfo) => Quantities.AddUnitInfo(unitInfo); - + public static bool TryGetUnitInfo(UnitKey unitEnum, [NotNullWhen(true)] out UnitInfo? unitInfo) + { + return Quantities.TryGetUnitInfo(unitEnum, out unitInfo); + } + /// /// Dynamically constructs a quantity from a numeric value and a unit enum value. /// @@ -46,11 +43,9 @@ public static bool TryGetUnitInfo(Enum unitEnum, [NotNullWhen(true)] out UnitInf /// Unit enum value. /// An object. /// Unit value is not a known unit enum type. - public static IQuantity From(double value, Enum unit) + public static IQuantity From(QuantityValue value, UnitKey unit) { - return TryFrom(value, unit, out IQuantity? quantity) - ? quantity - : throw new UnitNotFoundException($"Unit value {unit} of type {unit.GetType()} is not a known unit enum type. Expected types like UnitsNet.Units.LengthUnit. Did you pass in a custom enum type defined outside the UnitsNet library?"); + return Quantities.From(value, unit); } /// @@ -66,9 +61,28 @@ public static IQuantity From(double value, Enum 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 From(value, Quantities.GetUnitByName(quantityName, unitName).Value); + return Quantities.GetUnitByName(quantityName, unitName).From(value); + } + + /// + /// Dynamically constructs a quantity of the given with the value in the quantity's base + /// units. + /// + /// The of the quantity to create. + /// The value to construct the quantity with. + /// The created quantity. + /// + /// This is the equivalent to: + /// quantityInfo.From(value, quantityInfo.BaseUnitInfo.Value) + /// or + /// quantityInfo.BaseUnitInfo.From(value) + /// + [Obsolete("Consider using: quantityInfo.BaseUnitInfo.From(value)")] + public static IQuantity FromQuantityInfo(QuantityInfo quantityInfo, QuantityValue value) + { + return quantityInfo.BaseUnitInfo.From(value); } /// @@ -79,14 +93,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. @@ -96,17 +110,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 From(value, UnitParser.GetUnitFromAbbreviation(unitAbbreviation, formatProvider).Value); + return UnitParser.FromUnitAbbreviation(value, unitAbbreviation, culture); } /// @@ -117,15 +131,33 @@ 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)) + if (!Quantities.TryGetUnitByName(quantityName, unitName, out UnitInfo? unitInfo)) { - return TryFrom(value, unitInfo.Value, out quantity); + quantity = null; + return false; } - - quantity = null; - return false; + + quantity = unitInfo.From(value); + return true; + } + + /// + /// Attempts to create a quantity from the specified value and unit. + /// + /// The value of the quantity. + /// The unit of the quantity, represented as an . + /// + /// When this method returns, contains the created quantity if the conversion succeeded, + /// or null if the conversion failed. This parameter is passed uninitialized. + /// + /// + /// true if the quantity was successfully created; otherwise, false. + /// + public static bool TryFrom(QuantityValue value, Enum? unit, [NotNullWhen(true)] out IQuantity? quantity) + { + return Quantities.TryFrom(value, unit, out quantity); } /// @@ -136,14 +168,14 @@ public static bool TryFrom(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 . /// 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); /// @@ -154,7 +186,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. @@ -162,11 +194,12 @@ 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)) { - return TryFrom(value, unitInfo.Value, out quantity); + quantity = unitInfo.From(value); + return true; } quantity = null; @@ -183,27 +216,37 @@ public static bool TryFromUnitAbbreviation(IFormatProvider? formatProvider, doub /// Type of quantity, such as . /// Quantity string representation, such as "1.5 kg". Must be compatible with given quantity type. /// The parsed quantity. - /// Type must be of type UnitsNet.IQuantity -or- Type is not a known quantity type. - /// Type must be of type UnitsNet.IQuantity -or- Type is not a known quantity type. + /// + /// Thrown when the is not of type . + /// + /// + /// Thrown when the specified quantity type is not registered in the current configuration. + /// + /// Thrown when the is not in the expected format. public static IQuantity Parse(IFormatProvider? formatProvider, Type quantityType, string quantityString) { - // TODO Support custom units (via the QuantityParser), currently only hardcoded built-in quantities are supported. - if (!typeof(IQuantity).IsAssignableFrom(quantityType)) - throw new ArgumentException($"Type {quantityType} must be of type UnitsNet.IQuantity."); - - if (TryParse(formatProvider, quantityType, quantityString, out IQuantity? quantity)) - return quantity; - - throw new UnitNotFoundException($"Quantity string '{quantityString}' could not be parsed to quantity '{quantityType}'."); + QuantityInfo quantityInfo = Quantities.GetQuantityInfo(quantityType); + return QuantityParser.Parse(quantityString, formatProvider, quantityInfo); } /// public static bool TryParse(Type quantityType, string quantityString, [NotNullWhen(true)] out IQuantity? quantity) { - // TODO Support custom units (via the QuantityParser), currently only hardcoded built-in quantities are supported. return TryParse(null, quantityType, quantityString, out quantity); } + /// + public static bool TryParse(IFormatProvider? formatProvider, Type quantityType, string quantityString, [NotNullWhen(true)] out IQuantity? quantity) + { + if (Quantities.TryGetQuantityInfo(quantityType, out QuantityInfo? quantityInfo)) + { + return QuantityParser.TryParse(quantityString, formatProvider, quantityInfo, out quantity); + } + + quantity = null; + return false; + } + /// /// Get a list of quantities that has the given base dimensions. /// 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..3c6d07277a --- /dev/null +++ b/UnitsNet/CustomCode/QuantityInfo/Builder/QuantityInfoBuilderExtensions.cs @@ -0,0 +1,121 @@ +// 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 UnitsNet.Units; + +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 8d74808c67..fad9f745f7 100644 --- a/UnitsNet/CustomCode/QuantityInfo/QuantityInfoExtensions.cs +++ b/UnitsNet/CustomCode/QuantityInfo/QuantityInfoExtensions.cs @@ -1,6 +1,11 @@ -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; namespace UnitsNet; @@ -24,23 +29,78 @@ public static IEnumerable GetQuantitiesWithBaseDimensions(this IEn return quantityInfos.Where(info => info.BaseDimensions.Equals(baseDimensions)); } - + + /// + /// Filters a collection of unit information based on the specified base units. + /// + /// The type of the unit information. + /// The collection of unit information to filter. + /// The base units to filter by. + /// An containing the unit information that matches the specified base units. + /// Thrown when is null. + public static IEnumerable GetUnitInfosFor(this IEnumerable unitInfos, BaseUnits baseUnits) + where TUnitInfo : UnitInfo + { + if (baseUnits is null) + { + throw new ArgumentNullException(nameof(baseUnits)); + } + + return unitInfos.Where(unitInfo => unitInfo.BaseUnits.IsSubsetOf(baseUnits)); + } + + /// + /// Gets the whose is a subset of . + /// + /// + /// Length.Info.GetUnitInfoFor(unitSystemWithFootAsLengthUnit) returns for + /// . + /// + /// The collection of unit information to filter. + /// The to check against. + /// + /// The that has that is a subset of + /// . + /// + /// is null. + /// No unit was found that is a subset of . + /// + /// More than one unit was found that is a subset of + /// . + /// + public static TUnitInfo GetUnitInfoFor(this IEnumerable unitInfos, BaseUnits baseUnits) + where TUnitInfo : UnitInfo + { + using IEnumerator enumerator = unitInfos.GetUnitInfosFor(baseUnits).GetEnumerator(); + if (!enumerator.MoveNext()) + { + throw new InvalidOperationException($"No unit was found that is a subset of {nameof(baseUnits)}"); + } + + TUnitInfo firstUnitInfo = enumerator.Current!; + if (enumerator.MoveNext()) + { + throw new InvalidOperationException($"More than one unit was found that is a subset of {nameof(baseUnits)}"); + } + + return firstUnitInfo; + } + /// /// 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) @@ -53,9 +113,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)); @@ -63,4 +123,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 new file mode 100644 index 0000000000..dfd23ad642 --- /dev/null +++ b/UnitsNet/CustomCode/QuantityInfo/Units/UnitDefinition.cs @@ -0,0 +1,136 @@ +// 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; +using UnitsNet.Units; + +namespace UnitsNet; + +/// +[DebuggerDisplay("{Name} ({Value})")] +public sealed class UnitDefinition : IUnitDefinition + where TUnit : struct, Enum +{ + /// + /// Initializes a new instance of the class for the base unit. + /// + /// The enum value for this unit, for example . + /// The plural name of the unit, such as "Centimeters". + /// The for this unit. + public UnitDefinition(TUnit value, string pluralName, BaseUnits baseUnits) + : this(value, value.ToString(), pluralName, 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". + /// The associated with this unit. + /// + /// Thrown when , , , or + /// 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; + } + + /// + /// The enum value of the unit, such as . + /// + public TUnit Value { get; } + + /// + /// The singular name of the unit, such as "Centimeter". + /// + public string Name { get; } + + /// + /// The plural name of the unit, such as "Centimeters". + /// + public string PluralName { get; } + + /// + /// Gets the for this unit. + /// + public BaseUnits BaseUnits { get; } + + /// + public ConversionExpression ConversionFromBase { get; } + + /// + public ConversionExpression ConversionToBase { get; } +} diff --git a/UnitsNet/CustomCode/QuantityInfo/Units/UnitEqualityComparer.cs b/UnitsNet/CustomCode/QuantityInfo/Units/UnitEqualityComparer.cs new file mode 100644 index 0000000000..99f99e8c20 --- /dev/null +++ b/UnitsNet/CustomCode/QuantityInfo/Units/UnitEqualityComparer.cs @@ -0,0 +1,42 @@ +#if NETSTANDARD2_0 +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +namespace UnitsNet; + +/// +/// Provides a custom equality comparer for enumerations that represent units. +/// +/// The enumeration type representing the unit. +/// +/// This comparer uses the class to convert the enumeration to an +/// integer, +/// which is faster than the default equality comparer on .NET Framework. On .NET 8, the performance is comparable. +/// +internal class UnitEqualityComparer : IEqualityComparer + where TUnit : struct, Enum +{ + // Singleton instance of the comparer + public static readonly UnitEqualityComparer Default = new(); + + private UnitEqualityComparer() + { + } + + public bool Equals(TUnit x, TUnit y) + { + // Use Unsafe.As to convert enums to integers for comparison + var xInt = Unsafe.As(ref x); + var yInt = Unsafe.As(ref y); + return xInt == yInt; + } + + public int GetHashCode(TUnit obj) + { + // Use Unsafe.As to convert enum to integer for hash code calculation + var objInt = Unsafe.As(ref obj); + return objInt.GetHashCode(); + } +} +#endif diff --git a/UnitsNet/CustomCode/QuantityParser.cs b/UnitsNet/CustomCode/QuantityParser.cs index eb88e4f078..d49abfd0b3 100644 --- a/UnitsNet/CustomCode/QuantityParser.cs +++ b/UnitsNet/CustomCode/QuantityParser.cs @@ -10,253 +10,312 @@ using UnitsNet.Units; // ReSharper disable once CheckNamespace -namespace UnitsNet +namespace UnitsNet; + +/// +/// A method signature for creating a quantity given a numeric value and a strongly typed unit, for example 1.0 and +/// . +/// +/// The type of quantity to create, such as . +/// +/// The type of unit enum that belongs to this quantity, such as for +/// . +/// +public delegate TQuantity QuantityFromDelegate(QuantityValue value, TUnitType fromUnit) + where TQuantity : IQuantity + where TUnitType : struct, Enum; + +/// +/// Parses quantities from strings, such as "1.2 kg" to or "100 cm" to . +/// +public class QuantityParser { /// - /// A method signature for creating a quantity given a numeric value and a strongly typed unit, for example 1.0 and . + /// Allow integer, floating point or exponential number formats. /// - /// The type of quantity to create, such as . - /// The type of unit enum that belongs to this quantity, such as for . - public delegate TQuantity QuantityFromDelegate(double value, TUnitType fromUnit) - where TQuantity : IQuantity - where TUnitType : struct, Enum; + private const NumberStyles ParseNumberStyles = NumberStyles.Number | NumberStyles.Float | NumberStyles.AllowExponent; + private readonly UnitParser _unitParser; + /// - /// Parses quantities from strings, such as "1.2 kg" to or "100 cm" to . + /// Initializes a new instance of the class using the specified + /// . /// - public class QuantityParser + /// + /// The cache containing mappings of units to their abbreviations, used for parsing quantities. + /// + public QuantityParser(UnitAbbreviationsCache unitAbbreviationsCache) + : this(new UnitParser(unitAbbreviationsCache)) { - /// - /// Allow integer, floating point or exponential number formats. - /// - private const NumberStyles ParseNumberStyles = NumberStyles.Number | NumberStyles.Float | NumberStyles.AllowExponent; - - private readonly UnitAbbreviationsCache _unitAbbreviationsCache; - private readonly UnitParser _unitParser; - - /// - /// The default singleton instance for parsing quantities. - /// - /// - /// Convenience shortcut for ... - /// - public static QuantityParser Default => UnitsNetSetup.Default.QuantityParser; - - /// - /// Creates an instance of , optionally specifying an - /// with unit abbreviations to use when parsing. - /// - /// (Optional) The unit abbreviations cache, or specify null to use ... - public QuantityParser(UnitAbbreviationsCache? unitAbbreviationsCache = null) - { - _unitAbbreviationsCache = unitAbbreviationsCache ?? UnitsNetSetup.Default.UnitAbbreviations; - _unitParser = new UnitParser(_unitAbbreviationsCache); - } + } - /// - /// Parses a quantity from a string, such as "1.2 kg" to or "100 cm" to . - /// - /// The string to parse, such as "1.2 kg". - /// The culture for looking up localized unit abbreviations for a language, and for parsing the number formatted in this culture. Defaults to . - /// A function to create a quantity given a numeric value and a unit enum value. - /// The type of quantity to create, such as . - /// The type of unit enum that belongs to this quantity, such as for . - /// The parsed quantity if successful. - /// The string was null. - /// Failed to parse quantity. - [SuppressMessage("ReSharper", "UseStringInterpolation")] - public TQuantity Parse(string str, - IFormatProvider? formatProvider, - QuantityFromDelegate fromDelegate) - where TQuantity : IQuantity - where TUnitType : struct, Enum - { - if (str == null) throw new ArgumentNullException(nameof(str)); - str = str.Trim(); + /// + /// Initializes a new instance of the class using the specified . + /// + /// + /// The unit parser to use for parsing units. + /// + public QuantityParser(UnitParser unitParser) + { + _unitParser = unitParser ?? throw new ArgumentNullException(nameof(unitParser)); + } - var regex = CreateRegexForQuantity(formatProvider); + /// + /// The default instance of , which uses the default + /// unit abbreviations. + /// + public static QuantityParser Default + { + get => UnitsNetSetup.Default.QuantityParser; + } - if (!TryExtractValueAndUnit(regex, str, out var valueString, out var unitString)) - { - var ex = new FormatException("Unable to parse quantity. Expected the form \"{value} {unit abbreviation}\", such as \"5.5 m\". The spacing is optional."); - ex.Data["input"] = str; - throw ex; - } + /// + /// Parses a quantity from a string, such as "1.2 kg" to or "100 cm" to . + /// + /// The string to parse, such as "1.2 kg". + /// + /// The culture for looking up localized unit abbreviations for a language, and for parsing + /// the number formatted in this culture. Defaults to . + /// + /// A function to create a quantity given a numeric value and a unit enum value. + /// The type of quantity to create, such as . + /// + /// The type of unit enum that belongs to this quantity, such as for + /// . + /// + /// The parsed quantity if successful. + /// The string was null. + /// Failed to parse quantity. + public TQuantity Parse(string str, IFormatProvider? formatProvider, QuantityFromDelegate fromDelegate) + where TQuantity : IQuantity + where TUnitType : struct, Enum + { + if (str == null) throw new ArgumentNullException(nameof(str)); + str = str.Trim(); - return ParseWithRegex(valueString, unitString, fromDelegate, formatProvider); - } + Regex regex = CreateRegexForQuantity(formatProvider); - /// - /// Tries to parse a quantity from a string, such as "1.2 kg" to or "100 cm" to . - /// - /// The string to parse, such as "1.2 kg". - /// The culture for looking up localized unit abbreviations for a language, and for parsing the number formatted in this culture. Defaults to . - /// A function to create a quantity given a numeric value and a unit enum value. - /// The parsed quantity if successful, otherwise null. - /// The type of quantity to create, such as . - /// The type of unit enum that belongs to this quantity, such as for . - /// True if successful. - /// The string was null. - /// Failed to parse quantity. - [SuppressMessage("ReSharper", "UseStringInterpolation")] - public bool TryParse(string? str, - IFormatProvider? formatProvider, - QuantityFromDelegate fromDelegate, - out TQuantity result) - where TQuantity : struct, IQuantity - where TUnitType : struct, Enum + if (!TryExtractValueAndUnit(regex, str, out var valueString, out var unitString)) { - result = default; + throw new FormatException( + "Unable to parse quantity. Expected the form \"{value} {unit abbreviation}\", such as \"5.5 m\". The spacing is optional.") + { + Data = { ["input"] = str } + }; + } - if (string.IsNullOrWhiteSpace(str)) return false; - str = str!.Trim(); // netstandard2.0 nullable quirk + return ParseWithRegex(valueString, unitString, fromDelegate, formatProvider); + } - var regex = CreateRegexForQuantity(formatProvider); + /// + internal IQuantity Parse(string str, IFormatProvider? formatProvider, QuantityInfo quantityInfo) + { + if (str == null) throw new ArgumentNullException(nameof(str)); + str = str.Trim(); - return TryExtractValueAndUnit(regex, str, out var valueString, out var unitString) && - TryParseWithRegex(valueString, unitString, fromDelegate, formatProvider, out result); - } + Regex regex = CreateRegexForQuantity(quantityInfo.UnitType, formatProvider); - /// - /// Tries to parse a quantity from a string, such as "1.2 kg" to or "100 cm" to . - /// - /// - /// Similar to , - /// but returns instead. This is workaround for C# not allowing to pass on 'out' param from type Length to IQuantity, - /// even though the are compatible. - /// - /// The string to parse, such as "1.2 kg". - /// The culture for looking up localized unit abbreviations for a language, and for parsing the number formatted in this culture. Defaults to . - /// A function to create a quantity given a numeric value and a unit enum value. - /// The parsed quantity if successful, otherwise null. - /// The type of quantity to create, such as . - /// The type of unit enum that belongs to this quantity, such as for . - /// True if successful. - /// The string was null. - /// Failed to parse quantity. - [SuppressMessage("ReSharper", "UseStringInterpolation")] - public bool TryParse(string? str, - IFormatProvider? formatProvider, - QuantityFromDelegate fromDelegate, - out IQuantity? result) - where TQuantity : struct, IQuantity - where TUnitType : struct, Enum + if (!TryExtractValueAndUnit(regex, str, out var valueString, out var unitString)) { - if (TryParse(str, formatProvider, fromDelegate, out TQuantity parsedQuantity)) + throw new FormatException( + "Unable to parse quantity. Expected the form \"{value} {unit abbreviation}\", such as \"5.5 m\". The spacing is optional.") { - result = parsedQuantity; - return true; - } + Data = { ["input"] = str } + }; + } + + return ParseWithRegex(valueString, unitString, quantityInfo.UnitInfos, formatProvider); + } + + /// + /// Tries to parse a quantity from a string, such as "1.2 kg" to or "100 cm" to + /// . + /// + /// The string to parse, such as "1.2 kg". + /// + /// The culture for looking up localized unit abbreviations for a language, and for parsing + /// the number formatted in this culture. Defaults to . + /// + /// A function to create a quantity given a numeric value and a unit enum value. + /// The parsed quantity if successful, otherwise null. + /// The type of quantity to create, such as . + /// + /// The type of unit enum that belongs to this quantity, such as for + /// . + /// + /// True if successful. + /// The string was null. + /// Failed to parse quantity. + public bool TryParse(string? str, IFormatProvider? formatProvider, QuantityFromDelegate fromDelegate, + [NotNullWhen(true)] out TQuantity? result) + where TQuantity : IQuantity + where TUnitType : struct, Enum + { + result = default; + + if (string.IsNullOrWhiteSpace(str)) return false; + str = str!.Trim(); // netstandard2.0 nullable quirk + + Regex regex = CreateRegexForQuantity(formatProvider); + + return TryExtractValueAndUnit(regex, str, out var valueString, out var unitString) && + TryParseWithRegex(valueString, unitString, fromDelegate, formatProvider, out result); + } + + /// + internal bool TryParse(string? str, IFormatProvider? formatProvider, QuantityInfo quantityInfo, [NotNullWhen(true)] out IQuantity? result) + { + result = null; + + if (string.IsNullOrWhiteSpace(str)) return false; + str = str!.Trim(); // netstandard2.0 nullable quirk + + Regex regex = CreateRegexForQuantity(quantityInfo.UnitType, formatProvider); + + return TryExtractValueAndUnit(regex, str, out var valueString, out var unitString) && + TryParseWithRegex(valueString, unitString, quantityInfo.UnitInfos, formatProvider, out result); + } + + internal string CreateRegexPatternForUnit(TUnitType unit, IFormatProvider? formatProvider, bool matchEntireString = true) + where TUnitType : struct, Enum + { + IReadOnlyList unitAbbreviations = _unitParser.Abbreviations.GetUnitAbbreviations(unit, formatProvider); + var pattern = GetRegexPatternForUnitAbbreviations(unitAbbreviations); + return matchEntireString ? $"^{pattern}$" : pattern; + } + + private static string GetRegexPatternForUnitAbbreviations(IEnumerable abbreviations) + { + var orderedAbbreviations = abbreviations + .OrderByDescending(s => s.Length) // Important to order by length -- if "m" is before "mm" and the input is "mm", it will match just "m" + .Select(Regex.Escape) // Escape special regex characters + .ToArray(); + + var abbreviationsPiped = $"{string.Join("|", orderedAbbreviations)}"; + return $@"(?.*?)\s?(?{abbreviationsPiped})"; + } + + /// + /// Parse a string given a particular regular expression. + /// + /// Error parsing string. + private TQuantity ParseWithRegex(string valueString, string unitString, QuantityFromDelegate fromDelegate, + IFormatProvider? formatProvider) + where TQuantity : IQuantity + where TUnitType : struct, Enum + { + var value = QuantityValue.Parse(valueString, ParseNumberStyles, formatProvider); + TUnitType parsedUnit = _unitParser.Parse(unitString, formatProvider); + return fromDelegate(value, parsedUnit); + } + + /// + /// Parse a string given a particular regular expression. + /// + /// Error parsing string. + private IQuantity ParseWithRegex(string valueString, string unitString, IReadOnlyList units, IFormatProvider? formatProvider) + { + var value = QuantityValue.Parse(valueString, ParseNumberStyles, formatProvider); + UnitInfo unitInfo = _unitParser.Parse(unitString, units, formatProvider); + return unitInfo.From(value); + } - result = default; + /// + /// Parse a string given a particular regular expression. + /// + /// Error parsing string. + private bool TryParseWithRegex(string? valueString, string? unitString, QuantityFromDelegate fromDelegate, + IFormatProvider? formatProvider, [NotNullWhen(true)] out TQuantity? result) + where TQuantity : IQuantity + where TUnitType : struct, Enum + { + result = default; + + if (!QuantityValue.TryParse(valueString, ParseNumberStyles, formatProvider, out QuantityValue value)) + { return false; } - internal string CreateRegexPatternForUnit( - TUnitType unit, - IFormatProvider? formatProvider, - bool matchEntireString = true) - where TUnitType : struct, Enum + if (!_unitParser.TryParse(unitString, formatProvider, out TUnitType parsedUnit)) { - var unitAbbreviations = _unitAbbreviationsCache.GetUnitAbbreviations(unit, formatProvider); - var pattern = GetRegexPatternForUnitAbbreviations(unitAbbreviations); - return matchEntireString ? $"^{pattern}$" : pattern; + return false; } - private static string GetRegexPatternForUnitAbbreviations(IEnumerable abbreviations) - { - var orderedAbbreviations = abbreviations - .OrderByDescending(s => s.Length) // Important to order by length -- if "m" is before "mm" and the input is "mm", it will match just "m" - .Select(Regex.Escape) // Escape special regex characters - .ToArray(); + result = fromDelegate(value, parsedUnit); + return true; + } - var abbreviationsPiped = $"{string.Join("|", orderedAbbreviations)}"; - return $@"(?.*?)\s?(?{abbreviationsPiped})"; - } + /// + /// Parse a string given a particular regular expression. + /// + /// Error parsing string. + private bool TryParseWithRegex(string? valueString, string? unitString, IReadOnlyList units, IFormatProvider? formatProvider, + [NotNullWhen(true)] out IQuantity? result) + { + result = null; - /// - /// Parse a string given a particular regular expression. - /// - /// Error parsing string. - private TQuantity ParseWithRegex(string valueString, - string unitString, - QuantityFromDelegate fromDelegate, - IFormatProvider? formatProvider) - where TQuantity : IQuantity - where TUnitType : struct, Enum + if (!QuantityValue.TryParse(valueString, ParseNumberStyles, formatProvider, out QuantityValue value)) { - var value = double.Parse(valueString, ParseNumberStyles, formatProvider); - var parsedUnit = _unitParser.Parse(unitString, formatProvider); - return fromDelegate(value, parsedUnit); + return false; } - /// - /// Parse a string given a particular regular expression. - /// - /// Error parsing string. - private bool TryParseWithRegex(string? valueString, - string? unitString, - QuantityFromDelegate fromDelegate, - IFormatProvider? formatProvider, - out TQuantity result) - where TQuantity : struct, IQuantity - where TUnitType : struct, Enum + if (!_unitParser.TryParse(unitString, units, formatProvider, out UnitInfo? parsedUnit)) { - result = default; + return false; + } - if (!double.TryParse(valueString, ParseNumberStyles, formatProvider, out var value)) - return false; + result = parsedUnit.From(value); + return true; + } - if (!_unitParser.TryParse(unitString, formatProvider, out var parsedUnit)) - return false; + private static bool TryExtractValueAndUnit(Regex regex, string str, [NotNullWhen(true)] out string? valueString, [NotNullWhen(true)] out string? unitString) + { + Match match = regex.Match(str); - result = fromDelegate(value, parsedUnit); - return true; + // the regex coming in contains all allowed units as strings. + // That means if the unit in str is not formatted right + // the regex.Match will either put str or string.empty into Groups[0] and Groups[1] + // Therefore a mismatch can be detected by comparing the values of this two groups. + if (match.Groups[0].Value == match.Groups[1].Value) + { + str = UnitParser.NormalizeUnitString(str); + match = regex.Match(str); } - private static bool TryExtractValueAndUnit(Regex regex, string str, [NotNullWhen(true)] out string? valueString, [NotNullWhen(true)] out string? unitString) - { - var match = regex.Match(str); + GroupCollection groups = match.Groups; - // the regex coming in contains all allowed units as strings. - // That means if the unit in str is not formatted right - // the regex.Match will ether put str or string.empty into Groups[0] and Groups[1] - // Therefore a mismatch can be detected by comparing the values of this two groups. - if (match.Groups[0].Value == match.Groups[1].Value) - { - str = UnitParser.NormalizeUnitString(str); - match = regex.Match(str); - } + Group valueGroup = groups["value"]; + Group unitGroup = groups["unit"]; + if (!valueGroup.Success || !unitGroup.Success) + { + valueString = null; + unitString = null; + return false; + } - var groups = match.Groups; + valueString = valueGroup.Value; + unitString = unitGroup.Value; + return true; + } - var valueGroup = groups["value"]; - var unitGroup = groups["unit"]; - if (!valueGroup.Success || !unitGroup.Success) - { - valueString = null; - unitString = null; - return false; - } - - valueString = valueGroup.Value; - unitString = unitGroup.Value; - return true; - } + private string CreateRegexPatternForQuantity(Type unitType, IFormatProvider? formatProvider) + { + IReadOnlyList unitAbbreviations = _unitParser.Abbreviations.GetAllUnitAbbreviationsForQuantity(unitType, formatProvider); + var pattern = GetRegexPatternForUnitAbbreviations(unitAbbreviations); - private string CreateRegexPatternForQuantity(IFormatProvider? formatProvider) where TUnitType : struct, Enum - { - var unitAbbreviations = _unitAbbreviationsCache.GetAllUnitAbbreviationsForQuantity(typeof(TUnitType), formatProvider); - var pattern = GetRegexPatternForUnitAbbreviations(unitAbbreviations); + // Match entire string exactly + return $"^{pattern}$"; + } - // Match entire string exactly - return $"^{pattern}$"; - } + private Regex CreateRegexForQuantity(Type unitType, IFormatProvider? formatProvider) + { + var pattern = CreateRegexPatternForQuantity(unitType, formatProvider); + return new Regex(pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase); + } - private Regex CreateRegexForQuantity(IFormatProvider? formatProvider) where TUnitType : struct, Enum - { - var pattern = CreateRegexPatternForQuantity(formatProvider); - return new Regex(pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase); - } + private Regex CreateRegexForQuantity(IFormatProvider? formatProvider) + where TUnitType : struct, Enum + { + return CreateRegexForQuantity(typeof(TUnitType), formatProvider); } } diff --git a/UnitsNet/CustomCode/UnitAbbreviationsCache.cs b/UnitsNet/CustomCode/UnitAbbreviationsCache.cs index 264caa0d93..d97403d8d1 100644 --- a/UnitsNet/CustomCode/UnitAbbreviationsCache.cs +++ b/UnitsNet/CustomCode/UnitAbbreviationsCache.cs @@ -15,32 +15,35 @@ namespace UnitsNet { /// /// Cache of the mapping between unit enum values and unit abbreviation strings for one or more cultures. - /// A static instance .. is used internally - /// for ToString() and Parse() of quantities and units. + /// A static instance is created in the , which is used for ToString() and Parse() of quantities and units. /// public sealed class UnitAbbreviationsCache { /// - /// Fallback culture used by and + /// Fallback culture used by and /// if no abbreviations are found with a given culture. /// /// - /// User wants to call or with Russian - /// culture, but no translation is defined, so we return the US English definition as a last resort. If it's not + /// User wants to call or with Russian + /// culture, but no translation is defined, so we return the US English (en-US) definition as a last resort. If it's not /// defined there either, an exception is thrown. /// internal static readonly CultureInfo FallbackCulture = CultureInfo.InvariantCulture; /// - /// The default singleton instance with the default configured unit abbreviations, used for ToString() and parsing of quantities and units. + /// The static instance used internally for ToString() and Parse() of quantities and units. /// - /// - /// Convenience shortcut for ...
- /// You can add custom unit abbreviations at runtime, and this will affect all usages globally in the application. - ///
public static UnitAbbreviationsCache Default => UnitsNetSetup.Default.UnitAbbreviations; - private QuantityInfoLookup QuantityInfoLookup { get; } + /// + /// Gets the lookup table for quantity information used by this cache. + /// + /// + /// This property provides access to the instance that contains + /// information about quantities and their associated units. It is used internally to map units + /// to their abbreviations and vice versa. + /// + public QuantityInfoLookup Quantities { get; } /// /// Culture name to abbreviations. To add a custom default abbreviation, add to the beginning of the list. @@ -48,10 +51,11 @@ public sealed class UnitAbbreviationsCache private ConcurrentDictionary> AbbreviationsMap { get; } = new(); /// - /// Create an empty instance of the cache, with no default abbreviations loaded. + /// Create an instance of the cache and load all the built-in quantities defined in the library. /// + /// Instance for mapping any of the built-in units. public UnitAbbreviationsCache() - : this(new QuantityInfoLookup([])) + :this(UnitsNetSetup.Default.QuantityInfoLookup) { } @@ -63,116 +67,186 @@ public UnitAbbreviationsCache(IEnumerable quantities) :this(new QuantityInfoLookup(quantities)) { } - + /// /// Creates an instance of the cache using the specified set of quantities. /// /// /// Access type is internal until this class is matured and ready for external use. /// - internal UnitAbbreviationsCache(QuantityInfoLookup quantityInfoLookup) + internal UnitAbbreviationsCache(QuantityInfoLookup quantities) { - QuantityInfoLookup = quantityInfoLookup; + Quantities = quantities; } - + /// /// Create an instance of the cache and load all the built-in quantities defined in the library. /// /// Instance for mapping any of the built-in units. - public static UnitAbbreviationsCache CreateDefault() => new(new QuantityInfoLookup(Quantity.Infos)); + public static UnitAbbreviationsCache CreateDefault() + { + return new UnitAbbreviationsCache(); + } /// - /// Adds one or more unit abbreviation for the given unit enum value. - /// This is used to dynamically add abbreviations for existing unit enums such as or to extend with third-party unit enums - /// in order to or on them later. + /// Creates an instance of that maps to the default quantities, with an option to + /// customize the selection. /// - /// The unit enum value. - /// Unit abbreviations to add. - /// The type of unit enum. - public void MapUnitToAbbreviation(TUnitType unit, params string[] abbreviations) where TUnitType : struct, Enum + /// An action to configure the . + /// An instance of mapped to the default quantities. + public static UnitAbbreviationsCache CreateDefault(Action configureQuantities) { - PerformAbbreviationMapping(UnitKey.ForUnit(unit), CultureInfo.CurrentCulture, false, abbreviations); + return Create(Quantity.Provider.DefaultQuantities, configureQuantities); } /// - /// Adds a unit abbreviation for the given unit enum value and sets it as the default. - /// This is used to dynamically add abbreviations for existing unit enums such as or to extend with third-party unit enums - /// in order to or on them later. + /// Creates an instance of the class with a specified selection of default + /// quantities + /// and an action to configure the quantities selector. /// - /// The unit enum value. - /// Unit abbreviations to add as default. - /// The type of unit enum. - public void MapUnitToDefaultAbbreviation(TUnitType unit, string abbreviation) where TUnitType : struct, Enum + /// 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) { - PerformAbbreviationMapping(UnitKey.ForUnit(unit), CultureInfo.CurrentCulture, true, abbreviation); + return new UnitAbbreviationsCache(QuantityInfoLookup.Create(defaultQuantities, configureQuantities)); } + #region MapUnitToAbbreviation overloads + /// /// Adds one or more unit abbreviation for the given unit enum value. - /// This is used to dynamically add abbreviations for existing unit enums such as or to extend with third-party unit enums - /// in order to or on them later. + /// This is used to dynamically add abbreviations for existing unit enums such as or to extend with third-party unit enums + /// in order to or on them later. /// /// The unit enum value. - /// The format provider to use for lookup. Defaults to if null. /// Unit abbreviations to add. /// The type of unit enum. - public void MapUnitToAbbreviation(TUnitType unit, IFormatProvider? formatProvider, params string[] abbreviations) where TUnitType : struct, Enum + /// + /// Thrown when no unit information is found for the specified + /// . + /// + public void MapUnitToAbbreviation(TUnitType unit, params IEnumerable abbreviations) + where TUnitType : struct, Enum { - PerformAbbreviationMapping(UnitKey.ForUnit(unit), formatProvider, false, abbreviations); + MapUnitToAbbreviation(UnitKey.ForUnit(unit), abbreviations); } - /// - /// Adds a unit abbreviation for the given unit enum value and sets it as the default. - /// This is used to dynamically add abbreviations for existing unit enums such as or to extend with third-party unit enums - /// in order to or on them later. - /// + /// > + /// The unit enum type. + /// The unit enum value. + /// The format provider to use for lookup. Defaults to if null. + /// Unit abbreviations to add. + /// + /// Thrown when the provided type is null. + /// + /// + /// Thrown when the provided type is not an enumeration type. + /// + public void MapUnitToAbbreviation(Type unitType, int unitValue, IFormatProvider? formatProvider, params IEnumerable abbreviations) + { + MapUnitToAbbreviation(UnitKey.Create(unitType, unitValue), formatProvider, abbreviations); + } + + /// > + /// The unit key value. + /// Unit abbreviations to add. + public void MapUnitToAbbreviation(UnitKey unitKey, params IEnumerable abbreviations) + { + MapUnitToAbbreviation(unitKey, CultureInfo.CurrentCulture, abbreviations); + } + + /// > /// The unit enum value. /// The format provider to use for lookup. Defaults to if null. - /// Unit abbreviation to add as default. + /// Unit abbreviations to add. /// The type of unit enum. - public void MapUnitToDefaultAbbreviation(TUnitType unit, IFormatProvider? formatProvider, string abbreviation) where TUnitType : struct, Enum + public void MapUnitToAbbreviation(TUnitType unit, IFormatProvider? formatProvider, params IEnumerable abbreviations) + where TUnitType : struct, Enum { - PerformAbbreviationMapping(UnitKey.ForUnit(unit), formatProvider, true, abbreviation); + MapUnitToAbbreviation(UnitKey.ForUnit(unit), formatProvider, abbreviations); } - - /// - /// Adds one or more unit abbreviation for the given unit enum value. - /// This is used to dynamically add abbreviations for existing unit enums such as or to extend with third-party unit enums - /// in order to or on them later. - /// - /// The unit enum type. - /// The unit enum value. + + /// > + /// The unit key value. /// The format provider to use for lookup. Defaults to if null. /// Unit abbreviations to add. - public void MapUnitToAbbreviation(Type unitType, int unitValue, IFormatProvider? formatProvider, params string[] abbreviations) + public void MapUnitToAbbreviation(UnitKey unitKey, IFormatProvider? formatProvider, params IEnumerable abbreviations) { - PerformAbbreviationMapping(new UnitKey(unitType, unitValue), formatProvider, false, abbreviations); + PerformAbbreviationMapping(unitKey, formatProvider, false, abbreviations); } + #endregion + + #region MapUnitToDefaultAbbreviation overloads + /// /// Adds a unit abbreviation for the given unit enum value and sets it as the default. - /// This is used to dynamically add abbreviations for existing unit enums such as or to extend with third-party unit enums - /// in order to or on them later. + /// This is used to dynamically add abbreviations for existing unit enums such as or to extend with third-party unit enums + /// in order to or on them later. /// + /// The unit enum value. + /// Unit abbreviations to add as default. + /// The type of unit enum. + /// + /// Thrown when no unit information is found for the specified + /// . + /// + public void MapUnitToDefaultAbbreviation(TUnitType unit, string abbreviation) + where TUnitType : struct, Enum + { + MapUnitToDefaultAbbreviation(UnitKey.ForUnit(unit), abbreviation); + } + + /// > + /// The unit key value. + /// Unit abbreviations to add as default. + public void MapUnitToDefaultAbbreviation(UnitKey unitKey, string abbreviation) + { + MapUnitToDefaultAbbreviation(unitKey, CultureInfo.CurrentCulture, abbreviation); + } + + /// > + /// The unit enum value. + /// The format provider to use for lookup. Defaults to if null. + /// Unit abbreviation to add as default. + /// The type of unit enum. + public void MapUnitToDefaultAbbreviation(TUnitType unit, IFormatProvider? formatProvider, string abbreviation) + where TUnitType : struct, Enum + { + MapUnitToDefaultAbbreviation(UnitKey.ForUnit(unit), formatProvider, abbreviation); + } + + /// > /// The unit enum type. /// The unit enum value. /// The format provider to use for lookup. Defaults to if null. /// Unit abbreviation to add as default. + /// + /// Thrown when the provided type is null. + /// + /// + /// Thrown when the provided type is not an enumeration type. + /// public void MapUnitToDefaultAbbreviation(Type unitType, int unitValue, IFormatProvider? formatProvider, string abbreviation) { - PerformAbbreviationMapping(new UnitKey(unitType, unitValue), formatProvider, true, abbreviation); + MapUnitToDefaultAbbreviation(UnitKey.Create(unitType, unitValue), formatProvider, abbreviation); } - private void PerformAbbreviationMapping(UnitKey unitValue, IFormatProvider? formatProvider, bool setAsDefault, params string[] abbreviations) + /// > + /// The unit key value. + /// The format provider to use for lookup. Defaults to if null. + /// Unit abbreviation to add as default. + public void MapUnitToDefaultAbbreviation(UnitKey unitKey, IFormatProvider? formatProvider, string abbreviation) { - if(!QuantityInfoLookup.TryGetUnitInfo(unitValue, out UnitInfo? unitInfo)) - { - // TODO we should throw QuantityNotFoundException here (all QuantityInfos should be provided through the constructor) - unitInfo = new UnitInfo((Enum)unitValue, unitValue.ToString(), BaseUnits.Undefined); - QuantityInfoLookup.AddUnitInfo(unitInfo); - } + PerformAbbreviationMapping(unitKey, formatProvider, true, abbreviation); + } - AddAbbreviation(unitInfo, formatProvider, setAsDefault, abbreviations); + #endregion + + private void PerformAbbreviationMapping(UnitKey unitKey, IFormatProvider? formatProvider, bool setAsDefault, params IEnumerable abbreviations) + { + AddAbbreviation(Quantities.GetUnitInfo(unitKey), formatProvider, setAsDefault, abbreviations); } /// @@ -183,7 +257,16 @@ private void PerformAbbreviationMapping(UnitKey unitValue, IFormatProvider? form /// The unit enum value. /// The format provider to use for lookup. Defaults to if null. /// The type of unit enum. - public string GetDefaultAbbreviation(TUnitType unit, IFormatProvider? formatProvider = null) where TUnitType : struct, Enum + /// The default unit abbreviation string. + /// + /// Thrown when no unit information is found for the specified + /// . + /// + /// + /// Thrown when no abbreviations are mapped for the specified unit. + /// + public string GetDefaultAbbreviation(TUnitType unit, IFormatProvider? formatProvider = null) + where TUnitType : struct, Enum { return GetDefaultAbbreviation(UnitKey.ForUnit(unit), formatProvider); } @@ -196,24 +279,40 @@ public string GetDefaultAbbreviation(TUnitType unit, IFormatProvider? /// The unit enum type. /// The unit enum value. /// The format provider to use for lookup. Defaults to if null. + /// + /// Thrown when the provided type is null. + /// + /// + /// Thrown when the provided type is not an enumeration type. + /// + /// + /// Thrown when no unit information is found for the specified + /// and . + /// + /// + /// Thrown when no abbreviations are mapped for the specified unit. + /// public string GetDefaultAbbreviation(Type unitType, int unitValue, IFormatProvider? formatProvider = null) { - return GetDefaultAbbreviation(new UnitKey(unitType, unitValue), formatProvider); + return GetDefaultAbbreviation(UnitKey.Create(unitType, unitValue), formatProvider); } - - /// + + /// /// The key representing the unit type and value. - /// - /// The format provider to use for lookup. Defaults to - /// if null. - /// - /// The default unit abbreviation string. + /// The format provider to use for lookup. Defaults to if null. + /// + /// Thrown when no unit information is found for the specified + /// . + /// + /// + /// Thrown when no abbreviations are mapped for the specified unit. + /// public string GetDefaultAbbreviation(UnitKey unitKey, IFormatProvider? formatProvider = null) { IReadOnlyList abbreviations = GetUnitAbbreviations(unitKey, formatProvider); if (abbreviations.Count == 0) { - throw new InvalidOperationException($"No abbreviations were found for {unitKey.UnitType.Name}.{(Enum)unitKey}. Make sure that the unit abbreviations are mapped."); + throw new InvalidOperationException($"No abbreviations were found for {unitKey.UnitEnumType.Name}.{(Enum)unitKey}. Make sure that the unit abbreviations are mapped."); } return abbreviations[0]; @@ -226,9 +325,14 @@ public string GetDefaultAbbreviation(UnitKey unitKey, IFormatProvider? formatPro /// Enum value for unit. /// The format provider to use for lookup. Defaults to if null. /// Unit abbreviations associated with unit. - public string[] GetUnitAbbreviations(TUnitType unit, IFormatProvider? formatProvider = null) where TUnitType : struct, Enum + /// + /// Thrown when no unit information is found for the specified + /// . + /// + public IReadOnlyList GetUnitAbbreviations(TUnitType unit, IFormatProvider? formatProvider = null) + where TUnitType : struct, Enum { - return GetUnitAbbreviations(UnitKey.ForUnit(unit), formatProvider).ToArray(); // TODO can we change this to return an IReadonlyCollection (as the GetAbbreviations)? + return GetUnitAbbreviations(UnitKey.ForUnit(unit), formatProvider); } /// @@ -238,137 +342,150 @@ public string[] GetUnitAbbreviations(TUnitType unit, IFormatProvider? /// Enum value for unit. /// The format provider to use for lookup. Defaults to if null. /// Unit abbreviations associated with unit. - public string[] GetUnitAbbreviations(Type unitType, int unitValue, IFormatProvider? formatProvider = null) + /// + /// Thrown when the provided type is null. + /// + /// + /// Thrown when the provided type is not an enumeration type. + /// + /// + /// Thrown when no unit information is found for the specified + /// and . + /// + public IReadOnlyList GetUnitAbbreviations(Type unitType, int unitValue, IFormatProvider? formatProvider = null) { - return GetUnitAbbreviations(new UnitKey(unitType, unitValue), formatProvider).ToArray(); // TODO can we change this to return an IReadOnlyList (as the GetAbbreviations)? + return GetUnitAbbreviations(UnitKey.Create(unitType, unitValue), formatProvider); } /// /// Retrieves the unit abbreviations for a specified unit key and optional format provider. /// /// The key representing the unit type and value. - /// An optional format provider to use for culture-specific formatting. + /// The format provider to use for lookup. Defaults to if null. /// A read-only collection of unit abbreviation strings. + /// + /// Thrown when no unit information is found for the specified + /// . + /// public IReadOnlyList GetUnitAbbreviations(UnitKey unitKey, IFormatProvider? formatProvider = null) { - return GetAbbreviations(QuantityInfoLookup.GetUnitInfo(unitKey), formatProvider); - } - - /// - /// Get all abbreviations for unit. - /// - /// The unit-enum type as a hash-friendly type. - /// The format provider to use for lookup. Defaults to if null. - /// The unit abbreviations associated with unit. - /// True if found, otherwise false. - private bool TryGetUnitAbbreviations(UnitKey unitKey, IFormatProvider? formatProvider, out IReadOnlyList abbreviations) - { - if(QuantityInfoLookup.TryGetUnitInfo(unitKey, out UnitInfo? unitInfo)) + if (formatProvider is not CultureInfo culture) { - abbreviations = GetAbbreviations(unitInfo, formatProvider); - return true; + culture = CultureInfo.CurrentCulture; } - abbreviations = []; - return false; + return GetAbbreviationsWithFallbackCulture(Quantities.GetUnitInfo(unitKey), culture); } /// - /// Get all abbreviations for all units of a quantity. + /// Retrieves all abbreviations for all units of a specified quantity. /// - /// Enum type for unit. + /// + /// The enum type representing the unit. This must be a valid unit type. + /// /// The format provider to use for lookup. Defaults to if null. - /// Unit abbreviations associated with unit. + /// + /// A read-only list of unit abbreviations associated with the specified unit type. + /// + /// + /// Thrown when the provided type is null. + /// + /// + /// Thrown when the provided type is not an enumeration type. + /// + /// + /// Thrown when no quantity is found for the specified unit type. + /// public IReadOnlyList GetAllUnitAbbreviationsForQuantity(Type unitEnumType, IFormatProvider? formatProvider = null) { - var allAbbreviations = new List(); - if (!QuantityInfoLookup.TryGetQuantityByUnitType(unitEnumType, out QuantityInfo? quantityInfo)) + if (unitEnumType == null) { - // TODO I think we should either return empty or throw QuantityNotFoundException here - var enumValues = Enum.GetValues(unitEnumType).Cast(); - var all = GetStringUnitPairs(enumValues, formatProvider); - return all.Select(pair => pair.Item2).ToList(); + throw new ArgumentNullException(nameof(unitEnumType)); } - foreach(UnitInfo unitInfo in quantityInfo.UnitInfos) + if (!Quantities.TryGetQuantityByUnitType(unitEnumType, out QuantityInfo? quantityInfo)) { - if(TryGetUnitAbbreviations(unitInfo.UnitKey, formatProvider, out IReadOnlyList abbreviations)) + if (!unitEnumType.IsEnum) { - allAbbreviations.AddRange(abbreviations); + throw new ArgumentException($"Unit type must be an enumeration, but was {unitEnumType.FullName}.", nameof(unitEnumType)); } + + throw new UnitNotFoundException($"No quantity was found with the specified unit type: '{unitEnumType}'.") { Data = { ["unitType"] = unitEnumType.Name } }; + } + + if (formatProvider is not CultureInfo culture) + { + culture = CultureInfo.CurrentCulture; } - return allAbbreviations; - } - - internal List<(Enum Unit, string Abbreviation)> GetStringUnitPairs(IEnumerable enumValues, IFormatProvider? formatProvider = null) - { - var unitAbbreviationsPairs = new List<(Enum, string)>(); - formatProvider ??= CultureInfo.CurrentCulture; - - foreach(var enumValue in enumValues) + var allAbbreviations = new List(); + foreach(UnitInfo unitInfo in quantityInfo.UnitInfos) { - if(TryGetUnitAbbreviations(enumValue, formatProvider, out var abbreviations)) - { - foreach(var abbrev in abbreviations) - { - unitAbbreviationsPairs.Add((enumValue, abbrev)); - } - } + allAbbreviations.AddRange(GetAbbreviationsWithFallbackCulture(unitInfo, culture)); } - return unitAbbreviationsPairs; + return allAbbreviations; } /// /// Get all abbreviations for the given unit and culture. /// /// The unit. - /// The culture to get localized abbreviations for. Defaults to . + /// The culture to get localized abbreviations for. /// The list of abbreviations mapped for this unit. The first in the list is the primary abbreviation used by ToString(). /// was null. - public IReadOnlyList GetAbbreviations(UnitInfo unitInfo, IFormatProvider? formatProvider = null) + internal IReadOnlyList GetAbbreviationsWithFallbackCulture(UnitInfo unitInfo, CultureInfo culture) { - if (unitInfo == null) throw new ArgumentNullException(nameof(unitInfo)); - if (formatProvider is not CultureInfo) - formatProvider = CultureInfo.CurrentCulture; - - var culture = (CultureInfo)formatProvider; - var cultureName = GetCultureNameOrEnglish(culture); + IReadOnlyList abbreviations = GetAbbreviationsForCulture(unitInfo, culture); - AbbreviationMapKey key = GetAbbreviationMapKey(unitInfo, cultureName); - - IReadOnlyList abbreviations = AbbreviationsMap.GetOrAdd(key, - valueFactory: _ => ReadAbbreviationsFromResourceFile(unitInfo.QuantityName, unitInfo.PluralName, culture)); - - return abbreviations.Count == 0 && !culture.Equals(FallbackCulture) - ? GetAbbreviations(unitInfo, FallbackCulture) + return abbreviations.Count == 0 && HasFallbackCulture(culture) + ? GetAbbreviationsForCulture(unitInfo, FallbackCulture) : abbreviations; } + internal static bool HasFallbackCulture(CultureInfo culture) + { + // accounting for the fact that we're using the same abbreviations for both "en-US" and the "Invariant" culture (Name == string.Empty) + return culture.Name != string.Empty && culture.Name != FallbackCulture.Name; + } + + internal IReadOnlyList GetAbbreviationsForCulture(UnitInfo unitInfo, CultureInfo culture) + { + AbbreviationMapKey abbreviationMapKey = GetAbbreviationMapKey(unitInfo, culture); +#if NET + return AbbreviationsMap.GetOrAdd(abbreviationMapKey, ReadAbbreviationsForCulture, (unitInfo, culture)); + static IReadOnlyList ReadAbbreviationsForCulture(AbbreviationMapKey key, (UnitInfo unitInfo, CultureInfo culture) unitForCulture) + { + return ReadAbbreviationsFromResourceFile(unitForCulture.unitInfo, unitForCulture.culture); + } +#else + // intentionally not using the factory overload here, as it causes an extra allocation for the Func + return AbbreviationsMap.TryGetValue(abbreviationMapKey, out IReadOnlyList abbreviations) + ? abbreviations + : AbbreviationsMap.GetOrAdd(abbreviationMapKey, _ => ReadAbbreviationsFromResourceFile(unitInfo, culture)); +#endif + } + /// /// Add unit abbreviation for the given , such as "kg" for . /// /// The unit to add for. - /// The culture this abbreviation is for, defaults to . + /// The format provider to use for lookup. Defaults to if null. /// Whether to set as the primary/default unit abbreviation used by ToString(). /// One or more abbreviations to add. - private void AddAbbreviation(UnitInfo unitInfo, IFormatProvider? formatProvider, bool setAsDefault, - params string[] newAbbreviations) + private void AddAbbreviation(UnitInfo unitInfo, IFormatProvider? formatProvider, bool setAsDefault, params IEnumerable newAbbreviations) { if (formatProvider is not CultureInfo culture) { culture = CultureInfo.CurrentCulture; } - var cultureName = GetCultureNameOrEnglish(culture); - - AbbreviationMapKey key = GetAbbreviationMapKey(unitInfo, cultureName); + AbbreviationMapKey key = GetAbbreviationMapKey(unitInfo, culture); AbbreviationsMap.AddOrUpdate(key, addValueFactory: _ => { - List bundledAbbreviations = ReadAbbreviationsFromResourceFile(unitInfo.QuantityName, unitInfo.PluralName, culture).ToList(); + List bundledAbbreviations = ReadAbbreviationsFromResourceFile(unitInfo, culture); return AddAbbreviationsToList(setAsDefault, bundledAbbreviations, newAbbreviations); }, updateValueFactory: (_, existingReadOnlyList) => AddAbbreviationsToList(setAsDefault, existingReadOnlyList.ToList(), newAbbreviations)); @@ -394,63 +511,30 @@ private static IReadOnlyList AddAbbreviationsToList(bool setAsDefault, L return list.AsReadOnly(); } - private static AbbreviationMapKey GetAbbreviationMapKey(UnitInfo unitInfo, string cultureName) + private static AbbreviationMapKey GetAbbreviationMapKey(UnitInfo unitInfo, CultureInfo culture) { - return new AbbreviationMapKey(unitInfo.UnitKey, cultureName); + // In order to support running in "invariant mode" (DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1) the FallbackCulture is set to the InvariantCulture. + // However, if we want to avoid having two entries in the cache ("", "en-US"), we need to map the invariant culture name to the primary localization language. + return new AbbreviationMapKey(unitInfo.UnitKey, culture.Name == string.Empty ? "en-US" : culture.Name); } - - private static string GetCultureNameOrEnglish(CultureInfo culture) - { - // Fallback culture is invariant to support DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1, - // but we need to map that to the primary localization, English. - return culture.Equals(CultureInfo.InvariantCulture) - ? "en-US" - : culture.Name; - } - - private IReadOnlyList ReadAbbreviationsFromResourceFile(string? quantityName, string unitPluralName, CultureInfo culture) + + private static List ReadAbbreviationsFromResourceFile(UnitInfo unitInfo, CultureInfo culture) { var abbreviationsList = new List(); + QuantityInfo quantityInfo = unitInfo.QuantityInfo; + ResourceManager? resourceManager = quantityInfo.UnitAbbreviations; + if (resourceManager is null) + { + return abbreviationsList; + } - if (quantityName is null) return abbreviationsList.AsReadOnly(); - - string resourceName = $"UnitsNet.GeneratedCode.Resources.{quantityName}"; - var resourceManager = new ResourceManager(resourceName, GetType().Assembly); - - var abbreviationsString = resourceManager.GetString(unitPluralName, culture); - if(abbreviationsString is not null) + var abbreviationsString = resourceManager.GetString(unitInfo.PluralName, culture); + if (abbreviationsString is not null) + { abbreviationsList.AddRange(abbreviationsString.Split(',')); + } - return abbreviationsList.AsReadOnly(); - } - - /// - /// Retrieves a list of unit information objects that match the specified unit abbreviation. - /// - /// An optional format provider to use for culture-specific formatting. - /// The unit abbreviation to search for. - /// A list of objects that match the specified unit abbreviation. - /// - /// This method performs a case-sensitive match to reduce ambiguity. For example, "cm" could match both - /// LengthUnit.Centimeter (cm) and - /// MolarityUnit.CentimolePerLiter (cM). - /// - internal List GetUnitsForAbbreviation(IFormatProvider? formatProvider, string unitAbbreviation) - { - // TODO this is certain to have terrible performance (especially on the first run) - // TODO we should consider adding a (lazy) dictionary for these - // Use case-sensitive match to reduce ambiguity. - // Don't use UnitParser.TryParse() here, since it allows case-insensitive match per quantity as long as there are no ambiguous abbreviations for - // units of that quantity, but here we try all quantities and this results in too high of a chance for ambiguous matches, - // such as "cm" matching both LengthUnit.Centimeter (cm) and MolarityUnit.CentimolePerLiter (cM). - return QuantityInfoLookup.Infos - .SelectMany(quantityInfo => quantityInfo.UnitInfos) - .Select(unitInfo => GetAbbreviations(unitInfo, formatProvider).Contains(unitAbbreviation, StringComparer.Ordinal) - ? unitInfo - : null) - .Where(unitValue => unitValue != null) - .Select(unitValue => unitValue!) - .ToList(); + return abbreviationsList; } } } diff --git a/UnitsNet/CustomCode/UnitKey.cs b/UnitsNet/CustomCode/UnitKey.cs index f759dac2a0..7c02364822 100644 --- a/UnitsNet/CustomCode/UnitKey.cs +++ b/UnitsNet/CustomCode/UnitKey.cs @@ -17,8 +17,8 @@ namespace UnitsNet; public readonly record struct UnitKey { // apparently, on netstandard, the use of auto-properties is significantly slower - private readonly Type _unitType; - private readonly int _unitValue; + private readonly Type _unitEnumType; + private readonly int _unitEnumValue; /// /// Represents a unique key for a unit type and its corresponding value. @@ -27,10 +27,10 @@ public readonly record struct UnitKey /// This key is particularly useful when using an enum-based unit in a hash-based collection, /// as it avoids the boxing that would normally occur when casting the enum to . /// - public UnitKey(Type UnitType, int UnitValue) + internal UnitKey(Type UnitEnumType, int UnitEnumValue) { - _unitType = UnitType; - _unitValue = UnitValue; + _unitEnumType = UnitEnumType; + _unitEnumValue = UnitEnumValue; } /// @@ -40,9 +40,9 @@ public UnitKey(Type UnitType, int UnitValue) /// This property holds the of the unit enumeration associated with this key. /// It is particularly useful for identifying the unit type in scenarios where multiple unit types are used. /// - public Type UnitType + public Type UnitEnumType { - get => _unitType; + get => _unitEnumType; } /// @@ -52,9 +52,9 @@ public Type UnitType /// This property represents the unique value of the unit within its type, typically corresponding to the underlying /// integer value of an enumeration. /// - public int UnitValue + public int UnitEnumValue { - get => _unitValue; + get => _unitEnumValue; } /// @@ -81,6 +81,36 @@ public static UnitKey Create(int unitValue) return new UnitKey(typeof(TUnit), unitValue); } + /// + /// Creates a new instance of the struct for the specified unit type and value. + /// + /// The type of the unit, which must be an enumeration. + /// The integer value representing the unit. + /// A new instance of the struct. + /// + /// Thrown if is null. + /// + /// + /// Thrown if is not an enumeration type. + /// + /// + /// This method is useful for creating a when the unit type and value are known. + /// + public static UnitKey Create(Type unitType, int unitValue) + { + if (unitType is null) + { + throw new ArgumentNullException(nameof(unitType)); + } + + if (!unitType.IsEnum) + { + throw new ArgumentException($"Unit type must be an enumeration, but was {unitType.FullName}."); + } + + return new UnitKey(unitType, unitValue); + } + /// /// Implicitly converts an enumeration value to a . /// @@ -111,7 +141,7 @@ public static implicit operator UnitKey(Enum unit) /// public static explicit operator Enum(UnitKey unitKey) { - return (Enum)Enum.ToObject(unitKey._unitType, unitKey._unitValue); + return (Enum)Enum.ToObject(unitKey._unitEnumType, unitKey._unitEnumValue); } /// @@ -129,12 +159,12 @@ public static explicit operator Enum(UnitKey unitKey) /// public TUnit ToUnit() where TUnit : struct, Enum { - if (typeof(TUnit) != _unitType) + if (typeof(TUnit) != _unitEnumType) { - throw new InvalidOperationException($"Cannot convert UnitKey of type {_unitType} to {typeof(TUnit)}."); + throw new InvalidOperationException($"Cannot convert UnitKey of type {_unitEnumType} to {typeof(TUnit)}."); } - var unitValue = _unitValue; + var unitValue = _unitEnumValue; return Unsafe.As(ref unitValue); } @@ -142,12 +172,12 @@ private string GetDebuggerDisplay() { try { - var unitName = Enum.GetName(_unitType, _unitValue); - return string.IsNullOrEmpty(unitName) ? $"{nameof(UnitType)}: {_unitType}, {nameof(UnitValue)} = {_unitValue}" : $"{_unitType.Name}.{unitName}"; + var unitName = Enum.GetName(_unitEnumType, _unitEnumValue); + return string.IsNullOrEmpty(unitName) ? $"{nameof(UnitEnumType)}: {_unitEnumType}, {nameof(UnitEnumValue)} = {_unitEnumValue}" : $"{_unitEnumType.Name}.{unitName}"; } catch { - return $"{nameof(UnitType)}: {_unitType}, {nameof(UnitValue)} = {_unitValue}"; + return $"{nameof(UnitEnumType)}: {_unitEnumType}, {nameof(UnitEnumValue)} = {_unitEnumValue}"; } } @@ -162,8 +192,8 @@ private string GetDebuggerDisplay() /// public void Deconstruct(out Type unitType, out int unitValue) { - unitType = _unitType; - unitValue = _unitValue; + unitType = _unitEnumType; + unitValue = _unitEnumValue; } #region Equality members @@ -172,21 +202,21 @@ public void Deconstruct(out Type unitType, out int unitValue) public bool Equals(UnitKey other) { // implementing the Equality members on net48 is 5x faster than the default - return _unitType == other._unitType && _unitValue == other._unitValue; + return _unitEnumType == other._unitEnumType && _unitEnumValue == other._unitEnumValue; } /// public override int GetHashCode() { // implementing the Equality members on net48 is 5x faster than the default - if (_unitType == null) + if (_unitEnumType == null) { - return _unitValue; + return _unitEnumValue; } unchecked { - return (_unitType.GetHashCode() * 397) ^ _unitValue; + return (_unitEnumType.GetHashCode() * 397) ^ _unitEnumValue; } } diff --git a/UnitsNet/CustomCode/UnitParser.cs b/UnitsNet/CustomCode/UnitParser.cs index e31612211d..81941cd752 100644 --- a/UnitsNet/CustomCode/UnitParser.cs +++ b/UnitsNet/CustomCode/UnitParser.cs @@ -1,314 +1,754 @@ // 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.Globalization; using System.Linq; -using UnitsNet.Units; +using System.Text; // ReSharper disable once CheckNamespace -namespace UnitsNet +namespace UnitsNet; + +/// +/// Parses units given a unit abbreviations cache. +/// A static instance is created in the , which is used internally to parse +/// quantities and units using the +/// default abbreviations cache for all units and abbreviations defined in the library. +/// +public sealed class UnitParser { /// - /// Parses units given a unit abbreviations cache. - /// The static instance is used internally to parse quantities and units using the + /// Initializes a new instance of the class using the specified collection of quantity + /// information. + /// + /// + /// A read-only collection of quantity information used to initialize the unit abbreviations cache. + /// + public UnitParser(IEnumerable quantities) + : this(new UnitAbbreviationsCache(quantities)) + { + } + + internal UnitParser(QuantityInfoLookup quantitiesLookup) + : this(new UnitAbbreviationsCache(quantitiesLookup)) + { + } + + /// + /// Initializes a new instance of the class using the specified unit abbreviations cache. + /// + /// + /// The cache containing unit abbreviations. + /// + /// + /// If is null. + /// + public UnitParser(UnitAbbreviationsCache unitAbbreviationsCache) + { + Abbreviations = unitAbbreviationsCache ?? throw new ArgumentNullException(nameof(unitAbbreviationsCache)); + } + + /// + /// Gets the instance used by this . + /// This cache contains mappings of unit abbreviations to their corresponding units, enabling efficient + /// parsing and retrieval of unit information. + /// + public UnitAbbreviationsCache Abbreviations { get; } + + /// + /// Gets the collection of quantities available in this instance. + /// + /// + /// This property provides access to the that contains + /// information about all quantities and their associated units. + /// + public QuantityInfoLookup Quantities + { + get => Abbreviations.Quantities; + } + + /// + /// The default static instance used internally to parse quantities and units using the /// default abbreviations cache for all units and abbreviations defined in the library. /// - public sealed class UnitParser + public static UnitParser Default => UnitsNetSetup.Default.UnitParser; + + /// + /// Creates a default instance of the class with all the built-in unit abbreviations defined + /// in the library. + /// + /// A instance with the default abbreviations cache. + 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 + /// + /// + /// The format provider to use for lookup. Defaults to if null. + /// + /// Unit enum value, such as . + /// No quantity found matching the unit type. + /// No units match the abbreviation. + public TUnitType Parse(string unitAbbreviation, IFormatProvider? formatProvider = null) + where TUnitType : struct, Enum + { + if (unitAbbreviation == null) throw new ArgumentNullException(nameof(unitAbbreviation)); + + QuantityInfo quantityInfo = Quantities.GetQuantityByUnitType(typeof(TUnitType)); + return Parse(unitAbbreviation, quantityInfo.UnitInfos, formatProvider).UnitKey.ToUnit(); + } + + /// + /// Parse a unit abbreviation, such as "kg" or "m", to the unit enum value of the enum type + /// . + /// + /// + /// Unit abbreviation, such as "kg" or "m" for and + /// respectively. + /// + /// Unit enum type, such as and . + /// The format provider to use for lookup. Defaults to if null. + /// Unit enum value, such as . + /// The or the is null. + /// The is not a valid enumeration type. + /// No quantity found matching the unit type. + /// No units match the abbreviation. + /// More than one unit matches the abbreviation. + public Enum Parse(string unitAbbreviation, Type unitType, IFormatProvider? formatProvider = null) + { + if (unitAbbreviation == null) throw new ArgumentNullException(nameof(unitAbbreviation)); + + QuantityInfo quantityInfo = Quantities.GetQuantityByUnitType(unitType); + return Parse(unitAbbreviation, quantityInfo.UnitInfos, formatProvider).Value; + } + + /// + /// Retrieves the corresponding to the specified unit abbreviation within a given quantity. + /// + /// The name of the quantity to which the unit belongs. + /// The abbreviation of the unit to retrieve. + /// The format provider to use for lookup. Defaults to if null. + /// + /// The that matches the specified unit abbreviation within the given quantity. + /// + /// The or the is null. + /// + /// Thrown if the specified does not correspond to a known quantity. + /// + /// + /// Thrown if the cannot be resolved to a valid unit for the specified quantity. + /// + /// + /// When a specific is provided, both localized and non-localized units would be compared. + /// Both the and the comparisons are case-insensitive. + /// + public UnitInfo GetUnitFromAbbreviation(string quantityName, string unitAbbreviation, IFormatProvider? formatProvider) + { + if (quantityName == null) throw new ArgumentNullException(nameof(quantityName)); + if (unitAbbreviation == null) throw new ArgumentNullException(nameof(unitAbbreviation)); + + QuantityInfo quantityInfo = Quantities.GetQuantityByName(quantityName); + return Parse(unitAbbreviation, quantityInfo.UnitInfos, formatProvider); + } + + /// + /// Retrieves the corresponding to the specified unit abbreviation within a given quantity. + /// + /// The type of the quantity to which the unit belongs. + /// The abbreviation of the unit to retrieve. + /// The format provider to use for lookup. Defaults to if null. + /// + /// The that matches the specified unit abbreviation within the given quantity. + /// + /// The or the is null. + /// + /// Thrown if the specified does not correspond to a known quantity. + /// + /// No quantity found matching the unit type. + /// No units match the abbreviation. + /// + /// When a specific is provided, both localized and non-localized units would be compared. + /// The comparisons are case-insensitive. + /// + public UnitInfo GetUnitFromAbbreviation(Type quantityType, string unitAbbreviation, IFormatProvider? formatProvider) { - private readonly UnitAbbreviationsCache _unitAbbreviationsCache; - - /// - /// The default singleton instance for parsing units from the default configured unit abbreviations. - /// - /// - /// Convenience shortcut for ... - /// - public static UnitParser Default => UnitsNetSetup.Default.UnitParser; - - /// - /// Create a parser using the given unit abbreviations cache. - /// - /// The unit abbreviations to parse with. - /// No unit abbreviations cache was given. - public UnitParser(UnitAbbreviationsCache unitAbbreviationsCache) + if (quantityType == null) throw new ArgumentNullException(nameof(quantityType)); + if (unitAbbreviation == null) throw new ArgumentNullException(nameof(unitAbbreviation)); + + QuantityInfo quantityInfo = Quantities.GetQuantityInfo(quantityType); + return Parse(unitAbbreviation, quantityInfo.UnitInfos, formatProvider); + } + + /// + /// Parses the specified unit abbreviation, such as "kg" or "m", to find the corresponding unit information. + /// + /// The type of the unit information. + /// The abbreviation of the unit to parse. + /// A collection of unit information to search through. + /// The format provider to use for lookup. Defaults to if null. + /// The unit information that matches the specified abbreviation. + /// Thrown when is null. + /// Thrown when no matching unit is found. + /// Thrown when multiple matching units are found. + internal TUnitInfo Parse(string unitAbbreviation, IReadOnlyList units, IFormatProvider? formatProvider = null) + where TUnitInfo : UnitInfo + { + if (unitAbbreviation == null) throw new ArgumentNullException(nameof(unitAbbreviation)); + + if (formatProvider is not CultureInfo culture) { - _unitAbbreviationsCache = unitAbbreviationsCache ?? throw new ArgumentNullException(nameof(unitAbbreviationsCache)); + culture = CultureInfo.CurrentCulture; } + + unitAbbreviation = unitAbbreviation.Trim(); + while (true) + { + List<(TUnitInfo UnitInfo, string Abbreviation)> matches = FindMatchingUnits(unitAbbreviation, units, culture); + switch (matches.Count) + { + case 1: + return matches[0].UnitInfo; + case 0: + // Retry with fallback culture, if different. + if (UnitAbbreviationsCache.HasFallbackCulture(culture)) + { + culture = UnitAbbreviationsCache.FallbackCulture; + continue; + } - /// - /// Parses a unit abbreviation for a given unit enumeration type. - /// Example: Parse<LengthUnit>("km") => LengthUnit.Kilometer - /// - /// - /// The format provider to use for lookup. Defaults to if null. - /// - /// - public TUnitType Parse(string unitAbbreviation, IFormatProvider? formatProvider = null) - where TUnitType : struct, Enum + throw new UnitNotFoundException($"Unit not found with abbreviation [{unitAbbreviation}] for unit type [{typeof(TUnitInfo)}]."); + default: + var unitsCsv = string.Join(", ", matches.Select(x => $"{x.UnitInfo.Name} (\"{x.Abbreviation}\")").OrderBy(x => x)); + throw new AmbiguousUnitParseException($"Cannot parse \"{unitAbbreviation}\" since it matches multiple units: {unitsCsv}."); + } + } + } + + + internal static string NormalizeUnitString(string unitAbbreviation) + { + var abbreviationLength = unitAbbreviation.Length; + if (abbreviationLength == 0) { - return (TUnitType)Parse(unitAbbreviation, typeof(TUnitType), formatProvider); + return unitAbbreviation; } - /// - /// Parse a unit abbreviation, such as "kg" or "m", to the unit enum value of the enum type - /// . - /// - /// - /// Unit abbreviation, such as "kg" or "m" for and - /// respectively. - /// - /// Unit enum type, such as and . - /// The format provider to use for lookup. Defaults to if null. - /// Unit enum value, such as . - /// No units match the abbreviation. - /// More than one unit matches the abbreviation. - public Enum Parse(string unitAbbreviation, Type unitType, IFormatProvider? formatProvider = null) + // Remove all whitespace using StringBuilder + var sb = new StringBuilder(abbreviationLength); + for (var i = 0; i < unitAbbreviation.Length; i++) { - if (unitAbbreviation == null) throw new ArgumentNullException(nameof(unitAbbreviation)); - unitAbbreviation = unitAbbreviation.Trim(); - Enum[] enumValues = Enum.GetValues(unitType).Cast().ToArray(); - while (true) + var character = unitAbbreviation[i]; + if (!char.IsWhiteSpace(character)) { - (Enum Unit, string Abbreviation)[] matches = FindMatchingUnits(unitAbbreviation, enumValues, formatProvider); - switch(matches.Length) - { - case 1: - return matches[0].Unit; - case 0: - // Retry with fallback culture, if different. - if (Equals(formatProvider, UnitAbbreviationsCache.FallbackCulture)) - { - throw new UnitNotFoundException($"Unit not found with abbreviation [{unitAbbreviation}] for unit type [{unitType}]."); - } - - formatProvider = UnitAbbreviationsCache.FallbackCulture; - continue; - default: - var unitsCsv = string.Join(", ", matches.Select(x => $"{Enum.GetName(unitType, x.Unit)} (\"{x.Abbreviation}\")").OrderBy(x => x)); - throw new AmbiguousUnitParseException($"Cannot parse \"{unitAbbreviation}\" since it matches multiple units: {unitsCsv}."); - } + sb.Append(character); } } - internal static string NormalizeUnitString(string unitAbbreviation) + // Perform replacements using StringBuilder + sb.Replace("^-9", "⁻⁹") + .Replace("^-8", "⁻⁸") + .Replace("^-7", "⁻⁷") + .Replace("^-6", "⁻⁶") + .Replace("^-5", "⁻⁵") + .Replace("^-4", "⁻⁴") + .Replace("^-3", "⁻³") + .Replace("^-2", "⁻²") + .Replace("^-1", "⁻¹") + .Replace("^1", "") + .Replace("^2", "²") + .Replace("^3", "³") + .Replace("^4", "⁴") + .Replace("^5", "⁵") + .Replace("^6", "⁶") + .Replace("^7", "⁷") + .Replace("^8", "⁸") + .Replace("^9", "⁹") + .Replace("*", "·") + .Replace("\u03bc", "\u00b5"); // Greek letter 'Mu' to Micro sign + + return sb.ToString(); + } + + /// + /// Try to parse a unit abbreviation. + /// + /// The string value. + /// The unit enum value as out result. + /// Type of unit enum. + /// True if successful. + public bool TryParse([NotNullWhen(true)] string? unitAbbreviation, out TUnitType unit) + where TUnitType : struct, Enum + { + return TryParse(unitAbbreviation, null, out unit); + } + + /// + /// Try to parse a unit abbreviation. + /// + /// The string value. + /// The format provider to use for lookup. Defaults to if null. + /// The unit enum value as out result. + /// Type of unit enum. + /// True if successful. + public bool TryParse([NotNullWhen(true)] string? unitAbbreviation, IFormatProvider? formatProvider, out TUnitType unit) + where TUnitType : struct, Enum + { + if (!TryParse(unitAbbreviation, typeof(TUnitType), formatProvider, out Enum? unitObj)) { - // remove all whitespace in the string - unitAbbreviation = new string(unitAbbreviation.Where(c => !char.IsWhiteSpace(c)).ToArray()); - - unitAbbreviation = unitAbbreviation.Replace("^-9", "⁻⁹"); - unitAbbreviation = unitAbbreviation.Replace("^-8", "⁻⁸"); - unitAbbreviation = unitAbbreviation.Replace("^-7", "⁻⁷"); - unitAbbreviation = unitAbbreviation.Replace("^-6", "⁻⁶"); - unitAbbreviation = unitAbbreviation.Replace("^-5", "⁻⁵"); - unitAbbreviation = unitAbbreviation.Replace("^-4", "⁻⁴"); - unitAbbreviation = unitAbbreviation.Replace("^-3", "⁻³"); - unitAbbreviation = unitAbbreviation.Replace("^-2", "⁻²"); - unitAbbreviation = unitAbbreviation.Replace("^-1", "⁻¹"); - unitAbbreviation = unitAbbreviation.Replace("^1", ""); - unitAbbreviation = unitAbbreviation.Replace("^2", "²"); - unitAbbreviation = unitAbbreviation.Replace("^3", "³"); - unitAbbreviation = unitAbbreviation.Replace("^4", "⁴"); - unitAbbreviation = unitAbbreviation.Replace("^5", "⁵"); - unitAbbreviation = unitAbbreviation.Replace("^6", "⁶"); - unitAbbreviation = unitAbbreviation.Replace("^7", "⁷"); - unitAbbreviation = unitAbbreviation.Replace("^8", "⁸"); - unitAbbreviation = unitAbbreviation.Replace("^9", "⁹"); - unitAbbreviation = unitAbbreviation.Replace("*", "·"); - // "\u03bc" = Lower case Greek letter 'Mu' - // "\u00b5" = Micro sign - unitAbbreviation = unitAbbreviation.Replace("\u03bc", "\u00b5"); + unit = default; + return false; + } - return unitAbbreviation; + unit = (TUnitType)unitObj; + return true; + } + + /// + /// Try to parse a unit abbreviation. + /// + /// The string value. + /// Type of unit enum. + /// The unit enum value as out result. + /// True if successful. + public bool TryParse([NotNullWhen(true)]string? unitAbbreviation, Type unitType, [NotNullWhen(true)] out Enum? unit) + { + return TryParse(unitAbbreviation, unitType, null, out unit); + } + + /// + /// Try to parse a unit abbreviation. + /// + /// The string value. + /// Type of unit enum. + /// The format provider to use for lookup. Defaults to if null. + /// The unit enum value as out result. + /// True if successful. + public bool TryParse([NotNullWhen(true)] string? unitAbbreviation, Type unitType, IFormatProvider? formatProvider, [NotNullWhen(true)] out Enum? unit) + { + if (unitAbbreviation == null) + { + unit = null; + return false; } - /// - /// Try to parse a unit abbreviation. - /// - /// The string value. - /// The unit enum value as out result. - /// Type of unit enum. - /// True if successful. - public bool TryParse([NotNullWhen(true)]string? unitAbbreviation, out TUnitType unit) - where TUnitType : struct, Enum + if (Quantities.TryGetQuantityByUnitType(unitType, out QuantityInfo? quantityInfo) && + TryParse(unitAbbreviation, quantityInfo.UnitInfos, formatProvider, out UnitInfo? unitInfo)) { - return TryParse(unitAbbreviation, null, out unit); + unit = unitInfo.Value; + return true; } - /// - /// Try to parse a unit abbreviation. - /// - /// The string value. - /// The format provider to use for lookup. Defaults to if null. - /// The unit enum value as out result. - /// Type of unit enum. - /// True if successful. - public bool TryParse([NotNullWhen(true)]string? unitAbbreviation, IFormatProvider? formatProvider, out TUnitType unit) - where TUnitType : struct, Enum + unit = null; + return false; + } + + /// + /// Attempts to parse the specified unit abbreviation, such as "kg" or "m", into a unit of the specified type. + /// + /// The type of the unit enumeration. + /// The unit abbreviation to parse. + /// The quantity information that provides context for the unit. + /// The format provider to use for lookup. Defaults to if null. + /// + /// When this method returns, contains the parsed unit if the parsing succeeded, or null if the parsing failed. + /// + /// + /// true if the unit abbreviation was successfully parsed; otherwise, false. + /// + internal bool TryParse([NotNullWhen(true)] string? unitAbbreviation, QuantityInfo quantityInfo, IFormatProvider? formatProvider, + out TUnit unit) + where TUnit : struct, Enum + { + if (TryParse(unitAbbreviation, quantityInfo.UnitInfos, formatProvider, out UnitInfo? unitInfo)) { - unit = default; + unit = unitInfo.Value; + return true; + } - if (!TryParse(unitAbbreviation, typeof(TUnitType), formatProvider, out var unitObj)) - return false; + unit = default; + return false; + } - unit = (TUnitType)unitObj; + + /// + /// Attempts to retrieve the corresponding to the specified unit abbreviation within a given + /// quantity. + /// + /// The name of the quantity to which the unit belongs. + /// + /// The abbreviation of the unit to retrieve. Can be null, in which case the method will return false. + /// + /// The format provider to use for lookup. Defaults to if null. + /// + /// When this method returns, contains the that matches the specified unit abbreviation + /// within the given quantity, if the operation succeeds; otherwise, null. + /// + /// + /// true if the unit abbreviation was successfully resolved to a ; otherwise, + /// false. + /// + /// + /// This method does not throw exceptions for invalid input or unresolved unit abbreviations. Instead, it returns + /// false. + /// + public bool TryGetUnitFromAbbreviation(string quantityName, string? unitAbbreviation, IFormatProvider? formatProvider, [NotNullWhen(true)] out UnitInfo? unitInfo) + { + if (unitAbbreviation != null && Quantities.TryGetQuantityByName(quantityName, out QuantityInfo? quantityInfo)) + { + return TryParse(unitAbbreviation, quantityInfo.UnitInfos, formatProvider, out unitInfo); + } + + unitInfo = null; + return false; + } + + /// + /// Attempts to match the provided unit abbreviation against the defined abbreviations for the units and returns the + /// matching unit information. + /// + /// The type of the unit information. + /// The unit abbreviation to match. + /// The collection of units to match against. + /// The format provider to use for lookup. Defaults to if null. + /// + /// When this method returns, contains the matching unit information if the match was successful; otherwise, the + /// default value for the type of the unit parameter. + /// + /// + /// true if the unit abbreviation was successfully matched; otherwise, false. + /// + internal bool TryParse([NotNullWhen(true)] string? unitAbbreviation, IReadOnlyList units, IFormatProvider? formatProvider, + [NotNullWhen(true)] out TUnitInfo? unit) + where TUnitInfo : UnitInfo + { + unit = null; + if (unitAbbreviation == null) + { + return false; + } + + unitAbbreviation = unitAbbreviation.Trim(); + + if (formatProvider is not CultureInfo culture) + { + culture = CultureInfo.CurrentCulture; + } + + List<(TUnitInfo UnitInfo, string Abbreviation)> matches = FindMatchingUnits(unitAbbreviation, units, culture); + + if (matches.Count == 1) + { + unit = matches[0].UnitInfo; return true; } - /// - /// Try to parse a unit abbreviation. - /// - /// The string value. - /// Type of unit enum. - /// The unit enum value as out result. - /// True if successful. - public bool TryParse([NotNullWhen(true)] string? unitAbbreviation, Type unitType, [NotNullWhen(true)] out Enum? unit) + if (matches.Count != 0 || !UnitAbbreviationsCache.HasFallbackCulture(culture)) { - return TryParse(unitAbbreviation, unitType, null, out unit); + return false; // either there are duplicates or nothing was matched and we're already using the fallback culture } - /// - /// Try to parse a unit abbreviation. - /// - /// The string value. - /// Type of unit enum. - /// The format provider to use for lookup. Defaults to if null. - /// The unit enum value as out result. - /// True if successful. - public bool TryParse([NotNullWhen(true)] string? unitAbbreviation, Type unitType, IFormatProvider? formatProvider, [NotNullWhen(true)] out Enum? unit) + // retry the lookup using the fallback culture + matches = FindMatchingUnits(unitAbbreviation, units, UnitAbbreviationsCache.FallbackCulture); + if (matches.Count != 1) { - unit = null; - if (unitAbbreviation == null) - { - return false; - } + return false; + } + + unit = matches[0].UnitInfo; + return true; + } - unitAbbreviation = unitAbbreviation.Trim(); - Enum[] enumValues = Enum.GetValues(unitType).Cast().ToArray(); - (Enum Unit, string Abbreviation)[] matches = FindMatchingUnits(unitAbbreviation, enumValues, formatProvider); + private List<(TUnitInfo UnitInfo, string Abbreviation)> FindMatchingUnits(string unitAbbreviation, IReadOnlyList units, + CultureInfo culture) + where TUnitInfo : UnitInfo + { + List<(TUnitInfo UnitInfo, string Abbreviation)> caseInsensitiveMatches = FindMatchingUnitsForCulture(units, unitAbbreviation, culture, StringComparison.OrdinalIgnoreCase); - if (matches.Length == 1) + if (caseInsensitiveMatches.Count == 0) + { + var normalizeUnitString = NormalizeUnitString(unitAbbreviation); + if (unitAbbreviation == normalizeUnitString) { - unit = matches[0].Unit; - return true; + return caseInsensitiveMatches; } - if (matches.Length != 0 || Equals(formatProvider, UnitAbbreviationsCache.FallbackCulture)) + unitAbbreviation = normalizeUnitString; + caseInsensitiveMatches = FindMatchingUnitsForCulture(units, unitAbbreviation, culture, StringComparison.OrdinalIgnoreCase); + if (caseInsensitiveMatches.Count == 0) { - return false; // either there are duplicates or nothing was matched and we're already using the fallback culture + return caseInsensitiveMatches; } + } + + var nbAbbreviationsFound = caseInsensitiveMatches.Count; + if (nbAbbreviationsFound == 1) + { + return caseInsensitiveMatches; + } - // retry the lookup using the fallback culture - matches = FindMatchingUnits(unitAbbreviation, enumValues, UnitAbbreviationsCache.FallbackCulture); - if (matches.Length != 1) + // Narrow the search if too many hits, for example Megabar "Mbar" and Millibar "mbar" need to be distinguished + var caseSensitiveMatches = new List<(TUnitInfo UnitInfo, string Abbreviation)>(nbAbbreviationsFound); + for (var i = 0; i < nbAbbreviationsFound; i++) + { + (TUnitInfo UnitInfo, string Abbreviation) match = caseInsensitiveMatches[i]; + if (unitAbbreviation == match.Abbreviation) { - return false; + caseSensitiveMatches.Add(match); } - - unit = matches[0].Unit; - return true; } - private (Enum Unit, string Abbreviation)[] FindMatchingUnits(string unitAbbreviation, IEnumerable enumValues, IFormatProvider? formatProvider) - { - // TODO see about optimizing this method: both Parse and TryParse only care about having one match (in case of a failure we could return the number of matches) - List<(Enum Unit, string Abbreviation)> stringUnitPairs = _unitAbbreviationsCache.GetStringUnitPairs(enumValues, formatProvider); - (Enum Unit, string Abbreviation)[] matches = - stringUnitPairs.Where(pair => pair.Abbreviation.Equals(unitAbbreviation, StringComparison.OrdinalIgnoreCase)).ToArray(); + return caseSensitiveMatches.Count == 0 ? caseInsensitiveMatches : caseSensitiveMatches; + } - // No match? Retry after normalizing the unit abbreviation. - if (matches.Length == 0) + private List<(TUnitInfo UnitInfo, string Abbreviation)> FindMatchingUnitsForCulture(IReadOnlyList unitInfos, string unitAbbreviation, + CultureInfo culture, StringComparison comparison) + where TUnitInfo: UnitInfo + { + var unitAbbreviationsPairs = new List<(TUnitInfo, string)>(); + var nbUnits = unitInfos.Count; + for (var i = 0; i < nbUnits; i++) + { + TUnitInfo unitInfo = unitInfos[i]; + IReadOnlyList abbreviations = Abbreviations.GetAbbreviationsForCulture(unitInfo, culture); + var nbAbbreviations = abbreviations.Count; + for (var p = 0; p < nbAbbreviations; p++) { - var normalizeUnitString = NormalizeUnitString(unitAbbreviation); - if (unitAbbreviation != normalizeUnitString) + var abbreviation = abbreviations[p]; + if (unitAbbreviation.Equals(abbreviation, comparison)) { - unitAbbreviation = normalizeUnitString; - matches = stringUnitPairs.Where(pair => pair.Abbreviation.Equals(unitAbbreviation, StringComparison.OrdinalIgnoreCase)).ToArray(); + unitAbbreviationsPairs.Add((unitInfo, abbreviation)); } } + } - if (matches.Length == 1) - { - return matches; - } + return unitAbbreviationsPairs; + } - // Narrow the search if too many hits, for example Megabar "Mbar" and Millibar "mbar" need to be distinguished - (Enum Unit, string Abbreviation)[] caseSensitiveMatches = stringUnitPairs.Where(pair => pair.Abbreviation.Equals(unitAbbreviation)).ToArray(); - return caseSensitiveMatches.Length == 0 ? matches : caseSensitiveMatches; + /// + /// Retrieves the unit information corresponding to the specified unit abbreviation. + /// + /// The unit abbreviation to parse. Cannot be null or empty. + /// The format provider to use for lookup. Defaults to if null. + /// The instance representing the parsed unit. + /// + /// Thrown when is null. + /// + /// + /// Thrown when the unit abbreviation is not recognized as a valid unit for the specified culture. + /// + /// + /// Thrown when multiple units match the given unit abbreviation, making the result ambiguous. + /// + /// + /// This method performs a series of searches to find the unit: + /// + /// Case-sensitive search using the current culture. + /// Case-sensitive search using the fallback culture, if applicable. + /// Case-insensitive search. + /// + /// Note that this method is not optimized for performance, as it enumerates all units and their abbreviations + /// during each invocation. + /// + public UnitInfo GetUnitFromAbbreviation(string unitAbbreviation, IFormatProvider? formatProvider) + { + if (unitAbbreviation == null) throw new ArgumentNullException(nameof(unitAbbreviation)); + + List<(UnitInfo UnitInfo, string Abbreviation)> matches = FindAllMatchingUnits(unitAbbreviation, formatProvider); + switch (matches.Count) + { + case 1: + return matches[0].UnitInfo; + case 0: + throw new UnitNotFoundException($"Unit not found with abbreviation [{unitAbbreviation}]."); + default: + var unitsCsv = string.Join(", ", matches.Select(x => $"{x.UnitInfo.Name} (\"{x.Abbreviation}\")").OrderBy(x => x)); + throw new AmbiguousUnitParseException($"Cannot parse \"{unitAbbreviation}\" since it matches multiple units: {unitsCsv}."); } + } - /// - /// Retrieves the unit information from the given unit abbreviation. - /// - /// - /// This method is currently not optimized for performance and will enumerate all units and their unit abbreviations - /// each time.
- /// Unit abbreviation matching in the - /// overload is case-insensitive.
- ///
- /// This will fail if more than one unit across all quantities share the same unit abbreviation.
- ///
- /// The unit abbreviation to parse. - /// The format provider to use for culture-specific formatting. Can be null. - /// The unit information corresponding to the given unit abbreviation. - /// - /// Thrown when the unit abbreviation is not recognized as a valid unit for the specified culture. - /// - /// - /// Thrown when multiple units are found matching the given unit abbreviation. - /// - internal UnitInfo GetUnitFromAbbreviation(string unitAbbreviation, IFormatProvider? formatProvider) + /// + /// Attempts to parse the specified unit abbreviation into an object. + /// + /// The unit abbreviation to parse. + /// The format provider to use for lookup. Defaults to if null. + /// + /// When this method returns, contains the parsed object if the parsing succeeded, + /// or null if the parsing failed. This parameter is passed uninitialized. + /// + /// + /// true if the unit abbreviation was successfully parsed; otherwise, false. + /// + /// + /// This method performs a series of searches to find the unit: + /// + /// Case-sensitive search using the current culture. + /// Case-sensitive search using the fallback culture, if applicable. + /// Case-insensitive search. + /// + /// Note that this method is not optimized for performance, as it enumerates all units and their abbreviations + /// during each invocation. + /// + public bool TryGetUnitFromAbbreviation([NotNullWhen(true)]string? unitAbbreviation, IFormatProvider? formatProvider, [NotNullWhen(true)] out UnitInfo? unit) + { + if (unitAbbreviation == null) { - List units = _unitAbbreviationsCache.GetUnitsForAbbreviation(formatProvider, unitAbbreviation); - return units.Count switch - { - 0 => throw new UnitNotFoundException( - $"The unit abbreviation '{unitAbbreviation}' is not recognized as a valid unit for the specified culture."), - 1 => units[0], - _ => throw new AmbiguousUnitParseException( - $"Cannot parse \"{unitAbbreviation}\" since it matches multiple units: {string.Join(", ", units.Select(x => x.Name).OrderBy(x => x))}.") - }; + unit = null; + return false; + } + + List<(UnitInfo UnitInfo, string Abbreviation)> matches = FindAllMatchingUnits(unitAbbreviation, formatProvider); + if (matches.Count == 1) + { + unit = matches[0].UnitInfo; + return true; } - /// - /// Attempts to parse the specified unit abbreviation into an object. - /// - /// - /// This method is currently not optimized for performance and will enumerate all units and their unit abbreviations - /// each time.
- /// Unit abbreviation matching in the - /// overload is case-insensitive.
- ///
- /// This will fail if more than one unit across all quantities share the same unit abbreviation.
- ///
- /// The unit abbreviation to parse. - /// The format provider to use for parsing, or null to use the current culture. - /// - /// When this method returns, contains the parsed object if the parsing succeeded, - /// or null if the parsing failed. This parameter is passed uninitialized. - /// - /// - /// true if the unit abbreviation was successfully parsed; otherwise, false. - /// - internal bool TryGetUnitFromAbbreviation([NotNullWhen(true)]string? unitAbbreviation, IFormatProvider? formatProvider, [NotNullWhen(true)] out UnitInfo? unit) + unit = null; + return false; + } + + private List<(UnitInfo UnitInfo, string Abbreviation)> FindAllMatchingUnits(string unitAbbreviation, IFormatProvider? formatProvider) + { + if (formatProvider is not CultureInfo culture) + { + culture = CultureInfo.CurrentCulture; + } + + unitAbbreviation = unitAbbreviation.Trim(); + StringComparison comparison = StringComparison.Ordinal; + while (true) { - if (unitAbbreviation == null) + List<(UnitInfo UnitInfo, string Abbreviation)> matches = FindAllMatchingUnitsForCulture(unitAbbreviation, culture, comparison); + if (matches.Count != 0) + { + return matches; + } + + // Retry with fallback culture, if different. + if (UnitAbbreviationsCache.HasFallbackCulture(culture)) { - unit = null; - return false; + culture = UnitAbbreviationsCache.FallbackCulture; + continue; + } + + var normalizedUnitString = NormalizeUnitString(unitAbbreviation); + if (normalizedUnitString != unitAbbreviation) + { + unitAbbreviation = normalizedUnitString; + continue; } - List units = _unitAbbreviationsCache.GetUnitsForAbbreviation(formatProvider, unitAbbreviation); - if (units.Count == 1) + if (comparison == StringComparison.Ordinal) { - unit = units[0]; - return true; + comparison = StringComparison.OrdinalIgnoreCase; + continue; } - unit = null; - return false; + return matches; } } + + private List<(UnitInfo UnitInfo, string Abbreviation)> FindAllMatchingUnitsForCulture(string unitAbbreviation, CultureInfo culture, + StringComparison comparison) + { + var unitAbbreviationsPairs = new List<(UnitInfo, string)>(); + foreach (QuantityInfo quantityInfo in Quantities.Infos) + { + IReadOnlyList unitInfos = quantityInfo.UnitInfos; + var nbUnits = unitInfos.Count; + for (var i = 0; i < nbUnits; i++) + { + UnitInfo unitInfo = unitInfos[i]; + IReadOnlyList abbreviations = Abbreviations.GetAbbreviationsForCulture(unitInfo, culture); + var nbAbbreviations = abbreviations.Count; + for (var p = 0; p < nbAbbreviations; p++) + { + var abbreviation = abbreviations[p]; + if (unitAbbreviation.Equals(abbreviation, comparison)) + { + unitAbbreviationsPairs.Add((unitInfo, abbreviation)); + } + } + } + } + + return unitAbbreviationsPairs; + } + + /// + /// Dynamically construct a quantity from a numeric value and a unit abbreviation. + /// + /// + /// This method is currently not optimized for performance and will enumerate all units and their unit abbreviations + /// each time.
+ /// Unit abbreviation matching in the overload is case-insensitive.
+ ///
+ /// This will fail if more than one unit across all quantities share the same unit abbreviation.
+ ///
+ /// Numeric value. + /// Unit abbreviation, such as "kg" for . + /// The format provider to use for lookup. Defaults to if null. + /// An object. + /// Unit abbreviation is not known. + /// Multiple units found matching the given unit abbreviation. + 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 76ac4c7d26..88103768e2 100644 --- a/UnitsNet/CustomCode/UnitsNetSetup.cs +++ b/UnitsNet/CustomCode/UnitsNetSetup.cs @@ -1,8 +1,8 @@ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. +using System; using System.Collections.Generic; -using System.Linq; using UnitsNet.Units; namespace UnitsNet; @@ -14,33 +14,272 @@ namespace UnitsNet; /// abbreviations.
/// Alternatively, a setup instance may be provided for most static methods, such as /// and -/// . +/// . ///
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 { - var unitConverter = UnitConverter.CreateDefault(); - IReadOnlyCollection quantityInfos = Quantity.ByName.Values.ToList(); + 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"); + } + + _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.Provider.DefaultQuantities); + _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.Provider.DefaultQuantities); + 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.Provider.DefaultQuantities); + _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.Provider.DefaultQuantities) + : 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; - UnitParser = new UnitParser(unitAbbreviations); - QuantityParser = new QuantityParser(unitAbbreviations); - QuantityInfoLookup = 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) + { + QuantityInfoLookup = 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)); } /// @@ -53,7 +292,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. @@ -61,10 +300,14 @@ 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. + /// + public QuantityFormatter Formatter { get; } /// /// Parses units from strings, such as from "cm". @@ -82,5 +325,5 @@ public UnitsNetSetup(IEnumerable quantityInfos, UnitConverter unit /// /// Access type is internal until this class is matured and ready for external use. /// - internal QuantityInfoLookup QuantityInfoLookup { get; } + public QuantityInfoLookup QuantityInfoLookup { get; } } 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 5291b7d77b..5db271201d 100644 --- a/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs +++ b/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs @@ -2,7 +2,6 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; -using System.Linq; using UnitsNet.CustomCode.Units; using UnitsNet.Units; @@ -29,14 +28,13 @@ 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: , /// , and /// - public static PressureReference[] References { get; } = - Enum.GetValues(typeof(PressureReference)).Cast().ToArray(); + public static PressureReference[] References { get; } = [PressureReference.Absolute, PressureReference.Gauge, PressureReference.Vacuum]; /// /// Initializes a new instance of the struct requiring measured @@ -99,26 +97,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); @@ -130,7 +128,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(); @@ -141,14 +139,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 not 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 not convert {Reference} to {reference}.") + }; } /// @@ -156,7 +153,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/AmbiguousUnitParseException.cs b/UnitsNet/Exceptions/AmbiguousUnitParseException.cs similarity index 100% rename from UnitsNet/AmbiguousUnitParseException.cs rename to UnitsNet/Exceptions/AmbiguousUnitParseException.cs diff --git a/UnitsNet/Exceptions/ExceptionHelper.cs b/UnitsNet/Exceptions/ExceptionHelper.cs new file mode 100644 index 0000000000..8e8969e0f6 --- /dev/null +++ b/UnitsNet/Exceptions/ExceptionHelper.cs @@ -0,0 +1,32 @@ +using System; + +namespace UnitsNet; + +internal static class ExceptionHelper +{ + internal static ArgumentException CreateArgumentException(object obj, string argumentName) + where TQuantity : IQuantity + { + return new ArgumentException($"The given object is of type {obj.GetType()}. The expected type is {typeof(TQuantity)}.", argumentName); + } + + internal static ArgumentException CreateArgumentOutOfRangeExceptionForNegativeTolerance(string argumentName) + { + return new ArgumentOutOfRangeException(argumentName, "The tolerance must be greater than or equal to 0."); + } + + internal static InvalidOperationException CreateInvalidOperationOnEmptyCollectionException() + { + return new InvalidOperationException("Sequence contains no elements."); + } + + internal static InvalidCastException CreateInvalidCastException() + { + return CreateInvalidCastException(typeof(TOther)); + } + + internal static InvalidCastException CreateInvalidCastException(Type targetType) + { + return new InvalidCastException($"Converting {typeof(TSource)} to {targetType} is not supported."); + } +} 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/QuantityNotFoundException.cs b/UnitsNet/Exceptions/QuantityNotFoundException.cs similarity index 100% rename from UnitsNet/QuantityNotFoundException.cs rename to UnitsNet/Exceptions/QuantityNotFoundException.cs diff --git a/UnitsNet/UnitNotFoundException.cs b/UnitsNet/Exceptions/UnitNotFoundException.cs similarity index 91% rename from UnitsNet/UnitNotFoundException.cs rename to UnitsNet/Exceptions/UnitNotFoundException.cs index 0a1001e273..a520bd7621 100644 --- a/UnitsNet/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/UnitsNetException.cs b/UnitsNet/Exceptions/UnitsNetException.cs similarity index 100% rename from UnitsNet/UnitsNetException.cs rename to UnitsNet/Exceptions/UnitsNetException.cs diff --git a/UnitsNet/Extensions/AffineQuantityExtensions.cs b/UnitsNet/Extensions/AffineQuantityExtensions.cs new file mode 100644 index 0000000000..6c5334870e --- /dev/null +++ b/UnitsNet/Extensions/AffineQuantityExtensions.cs @@ -0,0 +1,187 @@ +// 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 UnitsNet.Units; +using UnitsNet; +#if NET +using System.Numerics; +#endif + +namespace UnitsNet; + +/// +/// Provides extension methods for affine quantities, such as the , enabling comparison and +/// averaging operations. +/// +public static class AffineQuantityExtensions +{ +#if NET + /// + public static bool Equals(this TQuantity quantity, TQuantity? other, TOffset tolerance) + where TQuantity : IAffineQuantity, ISubtractionOperators + where TOffset : IQuantityInstance, IAdditiveIdentity + { + return other != null && quantity.EqualsAbsolute(other, tolerance); + } + + /// + /// + /// Thrown when the is not of the same type as the + /// . + /// + public static bool Equals(this TQuantity quantity, IQuantity? other, TOffset tolerance) + where TQuantity : IAffineQuantity, ISubtractionOperators + where TOffset : IQuantityInstance, IAdditiveIdentity + { + if (other is not TQuantity otherInstance) + { + return false; + } + + // // TODO see about this (I think the exception should take precedence to the null check, but the QuantityTests disagree) + // if (tolerance is not TOffset toleranceQuantity) + // { + // throw ExceptionHelper.CreateArgumentException(tolerance, nameof(tolerance)); + // } + + return quantity.EqualsAbsolute(otherInstance, tolerance); + } + + /// + /// + /// 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 type of the quantity being compared. + /// The type of the tolerance quantity. + /// The quantity to compare. + /// 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. + /// Thrown when the is negative. + /// Thrown when no unit information is found for one of the specified enum value. + /// + /// It is generally advised against specifying "zero" tolerance, preferring the use of the default equality + /// comparer, which is significantly more performant. + /// + public static bool EqualsAbsolute(this TQuantity quantity, TQuantity other, TOffset tolerance) + where TQuantity : IAffineQuantity, ISubtractionOperators + where TOffset : IQuantityInstance, IAdditiveIdentity + { + if (QuantityValue.IsNegative(tolerance.Value)) + { + throw ExceptionHelper.CreateArgumentOutOfRangeExceptionForNegativeTolerance(nameof(tolerance)); + } + + TOffset difference = quantity - other; + return QuantityValue.Abs(difference.Value) <= tolerance.GetValue(difference.UnitKey); + } +#else + /// + public static bool Equals(this Temperature quantity, Temperature other, TemperatureDelta tolerance) + { + return quantity.EqualsAbsolute(other, tolerance); + // return other.HasValue && quantity.EqualsAbsolute(other.Value, tolerance); + } + + /// + /// + /// Thrown when the is not of the same type as the + /// . + /// + public static bool Equals(this Temperature quantity, IQuantity? other, TemperatureDelta tolerance) + { + if (other is not Temperature otherInstance) + { + return false; + } + + // TODO see about this (I think the exception should take precedence to the null check, but the QuantityTests disagree) + // if (tolerance is not TemperatureDelta toleranceQuantity) + // { + // throw ExceptionHelper.CreateArgumentException(tolerance, nameof(tolerance)); + // } + + return quantity.EqualsAbsolute(otherInstance, tolerance); + } + + /// + /// + /// Compare equality to given a for the maximum allowed +/- + /// difference. + /// + /// + /// In this example, the two temperatures will be considered equal if the value of b is within 0.5 degrees Celsius + /// of a. + /// + /// var a = Temperature.FromDegreesCelsius(25); + /// var b = Temperature.FromDegreesCelsius(25.4); + /// var tolerance = TemperatureDelta.FromDegreesCelsius(0.5); + /// a.Equals(b, tolerance); // true, 25°C equals 25.4°C +/- 0.5°C + /// + /// + /// + /// The quantity to compare. + /// 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. + /// Thrown when the is negative. + /// Thrown when no unit information is found for one of the specified enum value. + /// + /// It is generally advised against specifying "zero" tolerance, preferring the use of the default equality + /// comparer, which is significantly more performant. + /// + public static bool EqualsAbsolute(this Temperature quantity, Temperature other, TemperatureDelta tolerance) + { + if (QuantityValue.IsNegative(tolerance.Value)) + { + throw ExceptionHelper.CreateArgumentOutOfRangeExceptionForNegativeTolerance(nameof(tolerance)); + } + + TemperatureDelta difference = quantity - other; + return QuantityValue.Abs(difference.Value) <= tolerance.GetValue(UnitKey.ForUnit(difference.Unit)); + } +#endif + + /// + /// Calculates the average of a collection of values. + /// + /// The collection of values to average. + /// The average , in the unit of the first element in the sequence. + /// Thrown if the collection is null. + /// Thrown if the collection is empty. + public static Temperature Average(this IEnumerable temperatures) + { + return temperatures.ArithmeticMean(); + } + + /// + /// Calculates the average of a collection of values. + /// + /// The collection of values to average. + /// The unit in which to express the average. + /// The average , in the specified unit. + /// Thrown if the collection is null. + /// Thrown if the collection is empty. + /// + /// This method is slightly more performant than the alternative + /// + /// when most of the quantities in the collection are expected to be in the target unit. + /// + public static Temperature Average(this IEnumerable temperatures, TemperatureUnit unit) + { + return temperatures.ArithmeticMean(unit); + } +} diff --git a/UnitsNet/Extensions/LinearQuantityExtensions.cs b/UnitsNet/Extensions/LinearQuantityExtensions.cs new file mode 100644 index 0000000000..23375b5231 --- /dev/null +++ b/UnitsNet/Extensions/LinearQuantityExtensions.cs @@ -0,0 +1,274 @@ +// 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 linear quantities, such as Mass and Length, enabling operations such as equality +/// checks, summation, and averaging. +/// +public static class LinearQuantityExtensions +{ + /// + public static bool Equals(this TQuantity quantity, TOther? other, TTolerance tolerance) + where TQuantity : ILinearQuantity + where TOther : IQuantityInstance + where TTolerance : IQuantityInstance + { + return other != null && quantity.EqualsAbsolute(other, tolerance); + } + + /// + /// + /// Thrown when the is not of the same type as the + /// . + /// + public static bool Equals(this TQuantity quantity, IQuantity? other, IQuantity tolerance) + where TQuantity : ILinearQuantity + { + if (other is not TQuantity otherInstance) + { + return false; + } + + // TODO see about this (I think the exception should take precedence to the null check, but the QuantityTests disagree) + if (tolerance is not TQuantity toleranceQuantity) + { + throw ExceptionHelper.CreateArgumentException(tolerance, nameof(tolerance)); + } + + return quantity.EqualsAbsolute(otherInstance, toleranceQuantity); + } + + /// + /// + /// 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 type of the quantity being compared. + /// The type of the other quantity being compared. + /// The type of the tolerance quantity. + /// The quantity to compare. + /// 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. + /// Thrown when the is negative. + /// Thrown when no unit information is found for one of the specified enum value. + /// + /// It is generally advised against specifying "zero" tolerance, preferring the use of the default equality + /// comparer, which is significantly more performant. + /// + public static bool EqualsAbsolute(this TQuantity quantity, TOther other, TTolerance tolerance) + where TQuantity : ILinearQuantity + where TOther : IQuantityInstance + where TTolerance : IQuantityInstance + { + UnitKey quantityUnit = quantity.UnitKey; + return Comparison.EqualsAbsolute(quantity.Value, other.GetValue(quantityUnit), tolerance.GetValue(quantityUnit)); + } + + /// + /// Sums a sequence of linear quantities, such as Mass and Length. + /// + /// The type of the linear quantity. + /// The collection of linear quantities to sum. + /// + /// The sum of the linear quantities. If the sequence is empty, returns zero in the base unit. + /// In all other cases, the result will have the unit of the first element in the collection. + /// + public static TQuantity Sum(this IEnumerable quantities) + where TQuantity : ILinearQuantity + { + using IEnumerator enumerator = quantities.GetEnumerator(); + if (!enumerator.MoveNext()) + { +#if NET + return TQuantity.Zero; +#else + // for a struct-constrained TQuantity we could simply return default here + if (typeof(TQuantity).IsValueType) + { + return default!; + } + + return (TQuantity)UnitsNetSetup.Default.QuantityInfoLookup.GetQuantityInfo(typeof(TQuantity)).Zero; +#endif + } + + TQuantity firstQuantity = enumerator.Current!; + UnitKey resultUnit = firstQuantity.UnitKey; + QuantityValue sumOfValues = firstQuantity.Value; + while (enumerator.MoveNext()) + { + sumOfValues += enumerator.Current!.GetValue(resultUnit); + } + +#if NET + return TQuantity.Create(sumOfValues, resultUnit); +#else + 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. + /// + /// The type of the elements of the source sequence. + /// 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 sum of the projected quantities. If the sequence is empty, returns zero in the base unit; otherwise, + /// returns the sum in the unit of the first element. + /// + /// Thrown if the source or selector is null. + public static TQuantity Sum(this IEnumerable source, Func selector) + where TQuantity : ILinearQuantity + { + return source.Select(selector).Sum(); + } + + /// + /// Sums a sequence of linear quantities, such as Mass and Length. + /// + /// The type of the linear quantity. + /// The unit type of the linear quantity. + /// The collection of linear quantities to sum. + /// The unit in which to express the sum. + /// The sum of the linear quantities in the specified unit. + /// Thrown when the sequence is null. + /// + /// This method is slightly more performant than the alternative + /// when most of the quantities in the sequence are expected to be in the target unit. + /// + public static TQuantity Sum(this IEnumerable quantities, TUnit unit) + where TQuantity : ILinearQuantity, IQuantity + where TUnit : struct, Enum + { + using IEnumerator enumerator = quantities.GetEnumerator(); + if (!enumerator.MoveNext()) + { +#if NET + return TQuantity.From(QuantityValue.Zero, unit); +#else + return (TQuantity)Quantity.From(QuantityValue.Zero, UnitKey.ForUnit(unit)); +#endif + } + + var unitKey = UnitKey.ForUnit(unit); + TQuantity firstQuantity = enumerator.Current!; + QuantityValue resultValue = firstQuantity.GetValue(unitKey); + while (enumerator.MoveNext()) + { + resultValue += enumerator.Current!.GetValue(unitKey); + } + + return firstQuantity.QuantityInfo.From(resultValue, unit); + } + + /// + /// Computes the sum of the sequence of values that are obtained by invoking a + /// transform function on each element of the input sequence. + /// + /// The type of the elements of the source sequence. + /// The type of the quantity elements in the source sequence. + /// The type of the unit of the quantities. + /// 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 sum of the projected quantities in the specified unit. + /// Thrown if the source or selector is null. + public static TQuantity Sum(this IEnumerable source, Func selector, TUnit targetUnit) + where TQuantity : ILinearQuantity, IQuantity + where TUnit : struct, Enum + { + return source.Select(selector).Sum(targetUnit); + } + + /// + /// Calculates the arithmetic average of a sequence of linear quantities, such as Mass and Length. + /// + /// The type of the linear quantity. + /// The sequence of linear quantities to average. + /// The average of the linear quantities, using the unit of the first element in the sequence. + /// Thrown when the sequence is null. + /// Thrown when the sequence is empty. + public static TQuantity Average(this IEnumerable quantities) + where TQuantity : ILinearQuantity + { + return quantities.ArithmeticMean(); + } + + /// + /// Computes the arithmetic average of a sequence of quantities, such as Mass and Length, by applying a specified + /// selector + /// function to each element of the elements in the sequence. + /// + /// The type of the elements of the source sequence. + /// The type of the quantity elements in the source sequence. + /// A sequence of quantities to calculate the average of. + /// A function to transform each element of the source sequence into a quantity. + /// The average of the projected quantities in the unit of the first element in the sequence. + /// Thrown when the sequence is null. + /// Thrown when the sequence is empty. + public static TQuantity Average(this IEnumerable source, Func selector) + where TQuantity : ILinearQuantity + { + return source.Select(selector).Average(); + } + + /// + /// Calculates the average of a sequence of linear quantities, such as Mass and Length. + /// + /// The type of the linear quantity. + /// The unit type of the linear quantity. + /// The sequence of linear quantities to average. + /// The unit in which to express the average. + /// The average of the linear quantities in the specified unit. + /// Thrown when the sequence is empty. + /// + /// This method is slightly more performant than the alternative + /// + /// when most of the quantities in the sequence are expected to be in the target unit. + /// + public static TQuantity Average(this IEnumerable quantities, TUnit targetUnit) + where TQuantity : ILinearQuantity, IQuantity + where TUnit : struct, Enum + { + return quantities.ArithmeticMean(targetUnit); + } + + /// + /// Computes the average of the sequence of values, such as Mass and Length, that are + /// obtained by invoking a transform function on each element of the input sequence. + /// + /// The type of the elements of the source sequence. + /// The type of the quantity elements in the source sequence. + /// The type of the unit of the quantities. + /// A sequence of quantities to calculate the average of. + /// A function to transform each element of the source sequence into a quantity. + /// The desired unit type for the resulting quantity. + /// The average of the projected quantities in the specified unit. + /// Thrown when the sequence is empty. + public static TQuantity Average(this IEnumerable source, Func selector, TUnit targetUnit) + where TQuantity : ILinearQuantity, IQuantity + where TUnit : struct, Enum + { + return source.Select(selector).Average(targetUnit); + } +} diff --git a/UnitsNet/Extensions/LogarithmicQuantityExtensions.cs b/UnitsNet/Extensions/LogarithmicQuantityExtensions.cs new file mode 100644 index 0000000000..26f68307da --- /dev/null +++ b/UnitsNet/Extensions/LogarithmicQuantityExtensions.cs @@ -0,0 +1,519 @@ +// 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 logarithmic quantities, enabling operations such as equality checks, +/// summation, arithmetic mean, and geometric mean calculations. +/// +public static class LogarithmicQuantityExtensions +{ + /// + public static bool Equals(this TQuantity quantity, TOther? other, TTolerance tolerance) + where TQuantity : ILogarithmicQuantity + where TOther : IQuantityInstance + where TTolerance : IQuantityInstance + { + return other is not null && quantity.EqualsAbsolute(other, tolerance); + } + + /// + /// + /// Thrown when the is not of the same type as the + /// . + /// + public static bool Equals(this TQuantity quantity, IQuantity? other, IQuantity tolerance) + where TQuantity : ILogarithmicQuantity + { + if (other is not TQuantity otherInstance) + { + return false; + } + + // TODO see about this (I think the exception should take precedence to the null check, but the QuantityTests disagree) + if (tolerance is not TQuantity toleranceQuantity) + { + throw ExceptionHelper.CreateArgumentException(tolerance, nameof(tolerance)); + } + + return quantity.EqualsAbsolute(otherInstance, toleranceQuantity); + } + + /// + /// Compares the logarithmic equality of the current quantity to another quantity, given a specified tolerance. + /// + /// In this example, the two power ratios will be considered equal if the value of `b` is within 0.5 decibels of + /// `a`. + /// + /// var a = PowerRatio.FromDecibelMilliwatts(30); // Reference power of 1 mW + /// var b = PowerRatio.FromDecibelMilliwatts(29.8); // Slightly less than `a` + /// var tolerance = PowerRatio.FromDecibelMilliwatts(0.5); // 0.5 dBm tolerance + /// a.Equals(b, tolerance); // true, as 30 dBm equals 29.8 dBm +/- 0.5 dBm + /// + /// + /// + /// The type of the quantity being compared. + /// The type of the other quantity being compared. + /// The type of the tolerance value. + /// The logarithmic quantity to compare. + /// The other quantity to compare to. + /// The tolerance value for the maximum allowed difference. + /// + /// True if the absolute difference between the two quantities, when converted to linear space, is not greater + /// than the specified tolerance. + /// + /// Thrown when no unit information is found for one of the specified enum value. + /// + /// This method converts the quantities and the tolerance to linear space before performing the comparison, an + /// operation which doesn't produce an exact value. + /// + /// It is generally advised against specifying "zero" tolerance, preferring the use of the default equality + /// comparer, which is significantly more performant. + /// + /// + public static bool EqualsAbsolute(this TQuantity quantity, TOther other, TTolerance tolerance) + where TQuantity : ILogarithmicQuantity + where TOther : IQuantityInstance + where TTolerance : IQuantityInstance + { + UnitKey quantityUnit = quantity.UnitKey; +#if NET + QuantityValue scalingFactor = TQuantity.LogarithmicScalingFactor; +#else + QuantityValue scalingFactor = quantity.LogarithmicScalingFactor; +#endif + var valueInLinearSpace = quantity.Value.ToLinearSpace(scalingFactor); + var otherValueInLinearSpace = other.GetValue(quantityUnit).ToLinearSpace(scalingFactor); + var toleranceInLinearSpace = Math.Abs(tolerance.GetValue(quantityUnit).ToLinearSpace(scalingFactor)); + return Math.Abs(valueInLinearSpace - otherValueInLinearSpace) <= toleranceInLinearSpace; + } + + /// + /// Sums a sequence of logarithmic quantities, such as PowerRatio and AmplitudeRatio. + /// + /// 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, byte significantDigits = 15) + where TQuantity : ILogarithmicQuantity + { + if (quantities is null) + { + throw new ArgumentNullException(nameof(quantities)); + } + + using IEnumerator enumerator = quantities.GetEnumerator(); + if (!enumerator.MoveNext()) + { + throw ExceptionHelper.CreateInvalidOperationOnEmptyCollectionException(); + } + + TQuantity firstQuantity = enumerator.Current!; +#if NET + QuantityValue logarithmicScalingFactor = TQuantity.LogarithmicScalingFactor; +#else + QuantityValue logarithmicScalingFactor = firstQuantity.LogarithmicScalingFactor; +#endif + UnitKey resultUnit = firstQuantity.UnitKey; + var resultValue = firstQuantity.Value.ToLinearSpace(logarithmicScalingFactor); + while (enumerator.MoveNext()) + { + resultValue += enumerator.Current!.GetValue(resultUnit).ToLinearSpace(logarithmicScalingFactor); + } +#if NET + return TQuantity.Create(resultValue.ToLogSpace(logarithmicScalingFactor, significantDigits), resultUnit); +#else + return firstQuantity.QuantityInfo.Create(resultValue.ToLogSpace(logarithmicScalingFactor, significantDigits), resultUnit); +#endif + } + + /// + /// Computes the sum of a sequence of logarithmic quantities, such as PowerRatio and AmplitudeRatio, by applying a + /// specified selector function to each element of the + /// sequence. + /// + /// The type of the elements of the source sequence. + /// 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, byte significantDigits = 15) + where TQuantity : ILogarithmicQuantity + { + return source.Select(selector).Sum(significantDigits); + } + + /// + /// Sums a sequence of logarithmic quantities, such as PowerRatio and AmplitudeRatio, converting them to the + /// specified unit. + /// + /// The type of the logarithmic quantity. + /// 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, byte significantDigits = 15) + where TQuantity : ILogarithmicQuantity + where TUnit : struct, Enum + { + if (quantities is null) + { + throw new ArgumentNullException(nameof(quantities)); + } + + using IEnumerator enumerator = quantities.GetEnumerator(); + if (!enumerator.MoveNext()) + { + throw ExceptionHelper.CreateInvalidOperationOnEmptyCollectionException(); + } + + var unitKey = UnitKey.ForUnit(targetUnit); + TQuantity firstQuantity = enumerator.Current!; +#if NET + QuantityValue logarithmicScalingFactor = TQuantity.LogarithmicScalingFactor; +#else + QuantityValue logarithmicScalingFactor = firstQuantity.LogarithmicScalingFactor; +#endif + var sumInLinearSpace = firstQuantity.GetValue(unitKey).ToLinearSpace(logarithmicScalingFactor); + while (enumerator.MoveNext()) + { + sumInLinearSpace += enumerator.Current!.GetValue(unitKey).ToLinearSpace(logarithmicScalingFactor); + } + + return firstQuantity.QuantityInfo.From(sumInLinearSpace.ToLogSpace(logarithmicScalingFactor, significantDigits), targetUnit); + } + + /// + /// Computes the sum of the sequence of values, such as PowerRatio and + /// AmplitudeRatio, that is obtained by invoking a + /// transform function on each element of the input sequence. + /// + /// The type of the elements of the source sequence. + /// The type of the quantity elements in the source sequence. + /// The type of the unit of the quantities. + /// 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, + byte significantDigits = 15) + where TQuantity : ILogarithmicQuantity + where TUnit : struct, Enum + { + return source.Select(selector).Sum(targetUnit, significantDigits); + } + + /// + /// Computes the arithmetic mean of a sequence of logarithmic quantities, such as PowerRatio and AmplitudeRatio. + /// + /// 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, byte significantDigits = 15) + where TQuantity : ILogarithmicQuantity + { + if (quantities is null) + { + throw new ArgumentNullException(nameof(quantities)); + } + + using IEnumerator enumerator = quantities.GetEnumerator(); + if (!enumerator.MoveNext()) + { + throw ExceptionHelper.CreateInvalidOperationOnEmptyCollectionException(); + } + + TQuantity firstQuantity = enumerator.Current!; +#if NET + QuantityValue logarithmicScalingFactor = TQuantity.LogarithmicScalingFactor; +#else + QuantityValue logarithmicScalingFactor = firstQuantity.LogarithmicScalingFactor; +#endif + UnitKey resultUnit = firstQuantity.UnitKey; + var sumInLinearSpace = firstQuantity.Value.ToLinearSpace(logarithmicScalingFactor); + var nbQuantities = 1; + while (enumerator.MoveNext()) + { + sumInLinearSpace += enumerator.Current!.GetValue(resultUnit).ToLinearSpace(logarithmicScalingFactor); + nbQuantities++; + } + + var avgInLinearSpace = sumInLinearSpace / nbQuantities; +#if NET + return TQuantity.Create(avgInLinearSpace.ToLogSpace(logarithmicScalingFactor, significantDigits), resultUnit); +#else + return firstQuantity.QuantityInfo.Create(avgInLinearSpace.ToLogSpace(logarithmicScalingFactor, significantDigits), resultUnit); +#endif + } + + /// + /// Computes the average of a sequence of quantities by applying a specified selector function to each element of the + /// sequence. + /// + /// The type of the elements of the source sequence. + /// 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, byte significantDigits = 15) + where TQuantity : ILogarithmicQuantity + { + return source.Select(selector).ArithmeticMean(significantDigits); + } + + /// + /// Computes the arithmetic mean of a sequence of logarithmic quantities, such as PowerRatio and AmplitudeRatio. + /// + /// The type of the logarithmic quantity. + /// 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 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, byte significantDigits = 15) + where TQuantity : ILogarithmicQuantity + where TUnit : struct, Enum + { + if (quantities is null) + { + throw new ArgumentNullException(nameof(quantities)); + } + + using IEnumerator enumerator = quantities.GetEnumerator(); + if (!enumerator.MoveNext()) + { + throw ExceptionHelper.CreateInvalidOperationOnEmptyCollectionException(); + } + + var unitKey = UnitKey.ForUnit(unit); + TQuantity firstQuantity = enumerator.Current!; +#if NET + QuantityValue logarithmicScalingFactor = TQuantity.LogarithmicScalingFactor; +#else + QuantityValue logarithmicScalingFactor = firstQuantity.LogarithmicScalingFactor; +#endif + var sumInLinearSpace = firstQuantity.GetValue(unitKey).ToLinearSpace(logarithmicScalingFactor); + var nbQuantities = 1; + while (enumerator.MoveNext()) + { + sumInLinearSpace += enumerator.Current!.GetValue(unitKey).ToLinearSpace(logarithmicScalingFactor); + nbQuantities++; + } + + var avgInLinearSpace = sumInLinearSpace / nbQuantities; + return firstQuantity.QuantityInfo.From(avgInLinearSpace.ToLogSpace(logarithmicScalingFactor, significantDigits), unit); + } + + /// + /// Computes the arithmetic mean of the sequence of values that are obtained by + /// invoking a + /// transform function on each element of the input sequence. + /// + /// The type of the elements of the source sequence. + /// The type of the quantity elements in the source sequence. + /// The type of the unit of the quantities. + /// 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 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, + byte significantDigits = 15) + where TQuantity : ILogarithmicQuantity + where TUnit : struct, Enum + { + return source.Select(selector).ArithmeticMean(targetUnit, significantDigits); + } + + + /// + /// Computes the geometric mean of a sequence of logarithmic quantities, such as PowerRatio and AmplitudeRatio. + /// + /// 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, int accuracy = 15) + where TQuantity : ILogarithmicQuantity + { + if (quantities is null) + { + throw new ArgumentNullException(nameof(quantities)); + } + + using IEnumerator enumerator = quantities.GetEnumerator(); + if (!enumerator.MoveNext()) + { + throw ExceptionHelper.CreateInvalidOperationOnEmptyCollectionException(); + } + + TQuantity firstQuantity = enumerator.Current!; + UnitKey resultUnit = firstQuantity.UnitKey; + QuantityValue sumInLogSpace = firstQuantity.Value; + var nbQuantities = 1; + while (enumerator.MoveNext()) + { + sumInLogSpace += enumerator.Current!.GetValue(resultUnit); + nbQuantities++; + } + + // var geometricMean = QuantityValue.Pow(sumInLogSpace, new QuantityValue(1, nbQuantities), significantDigits); + var geometricMean = QuantityValue.RootN(sumInLogSpace, nbQuantities, accuracy); +#if NET + return TQuantity.Create(geometricMean, resultUnit); +#else + return firstQuantity.QuantityInfo.Create(geometricMean, resultUnit); +#endif + } + + + /// + /// Computes the geometric mean of a sequence of quantities by applying a specified selector function to each element + /// of the + /// sequence. + /// + /// The type of the elements of the source sequence. + /// 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, int accuracy = 15) + where TQuantity : ILogarithmicQuantity + { + 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. + /// + /// The type of the logarithmic quantity. + /// The 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, int accuracy = 15) + where TQuantity : ILogarithmicQuantity + where TUnit : struct, Enum + { + if (quantities is null) + { + throw new ArgumentNullException(nameof(quantities)); + } + + using IEnumerator enumerator = quantities.GetEnumerator(); + if (!enumerator.MoveNext()) + { + throw ExceptionHelper.CreateInvalidOperationOnEmptyCollectionException(); + } + + var unitKey = UnitKey.ForUnit(targetUnit); + TQuantity firstQuantity = enumerator.Current!; + QuantityValue sumInLogSpace = firstQuantity.GetValue(unitKey); + var nbQuantities = 1; + while (enumerator.MoveNext()) + { + sumInLogSpace += enumerator.Current!.GetValue(unitKey); + nbQuantities++; + } + + // var geometricMean = QuantityValue.Pow(sumInLogSpace, new QuantityValue(1, nbQuantities), significantDigits); + var geometricMean = QuantityValue.RootN(sumInLogSpace, nbQuantities, accuracy); + return firstQuantity.QuantityInfo.From(geometricMean, unitKey.ToUnit()); + } + + /// + /// Computes the geometric mean of the sequence of values that are obtained by + /// invoking a + /// transform function on each element of the input sequence. + /// + /// The type of the elements of the source sequence. + /// The type of the quantity elements in the source sequence. + /// The type of the unit of the quantities. + /// 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 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, + int accuracy = 15) + where TQuantity : ILogarithmicQuantity + where TUnit : struct, Enum + { + return source.Select(selector).GeometricMean(targetUnit, accuracy); + } +} diff --git a/UnitsNet/Extensions/QuantityExtensions.cs b/UnitsNet/Extensions/QuantityExtensions.cs new file mode 100644 index 0000000000..ee62b90f27 --- /dev/null +++ b/UnitsNet/Extensions/QuantityExtensions.cs @@ -0,0 +1,204 @@ +// 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; + +namespace UnitsNet; + +/// +/// Provides extension methods applicable to all quantities in the UnitsNet library. +/// +public static class QuantityExtensions +{ + /// + internal static QuantityValue GetValue(this TQuantity quantity, UnitKey toUnit) + where TQuantity : IQuantity + { + 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 : IQuantityInstance + { + QuantityValue convertedValue = converter.ConvertValue(quantity.Value, quantity.UnitKey, toUnit); +#if NET + return TQuantity.Create(convertedValue, toUnit); +#else + return quantity.QuantityInfo.Create(convertedValue, toUnit); +#endif + } + + /// + /// Returns the string representation of the specified quantity using the provided format provider. + /// + /// + /// The type of the quantity, which must implement and + /// . + /// + /// The quantity to convert to a string. + /// + /// The format provider to use for localization and number formatting. + /// If null, the default is . + /// + /// A string representation of the quantity. + public static string ToString(this TQuantity quantity, IFormatProvider? formatProvider) + where TQuantity : IQuantity, IFormattable + { + return quantity.ToString(null, formatProvider); + } + + /// + /// Returns the string representation of the specified quantity using the provided format string. + /// + /// + /// The type of the quantity, which must implement and + /// . + /// + /// The quantity to convert to a string. + /// + /// The format string to use for formatting the quantity. + /// If null or empty, the default format is used. + /// + /// A string representation of the quantity. + public static string ToString(this TQuantity quantity, string? format) + where TQuantity : IQuantity, IFormattable + { + return quantity.ToString(format, null); + } + + // /// + // public static TQuantity ToUnit(this TQuantity quantity, UnitSystem unitSystem) + // where TQuantity : IQuantity + // where TUnit : struct, Enum + // { + // return UnitConverter.Default.ConvertToUnit(quantity, quantity.QuantityInfo.GetDefaultUnit(unitSystem)); + // } + + // /// + // /// + // /// + // /// + // /// + // /// + // /// + // /// + // [Obsolete( + // "This method was only created in order to facilitate the transition from the old IQuantity interface definition. Consider using the safer, and more performant extensions available on the IVectorQuantity, ILogarithmicQuantity or IAffineQuantity interfaces.")] + // public static bool Equals(this TQuantity quantity, TQuantity? other, TQuantity tolerance) where TQuantity : IQuantity + // { + // if (other is null) + // { + // return false; + // } + // + // var type = typeof(IVectorQuantity<>); + // + // // if (quantity is IVectorQuantity vectorQuantity && other is IVectorQuantity otherVectorQuantity) + // // { + // // return VectorQuantityExtensions.Equals(vectorQuantity, otherVectorQuantity, tolerance); + // // } + // // + // // if (quantity is ILogarithmicQuantity logarithmicQuantity && other is ILogarithmicQuantity otherLogarithmicQuantity) + // // { + // // return LogarithmicQuantityExtensions.Equals(logarithmicQuantity, otherLogarithmicQuantity, tolerance); + // // } + // + // // if (quantity is IAffineQuantity affineQuantity && other is IAffineQuantity otherAffineQuantity) + // // { + // // return AffineQuantityExtensions.Equals(affineQuantity, otherAffineQuantity, tolerance); + // // } + // + // throw new InvalidOperationException("Unsupported quantity type."); + // } + + /// + /// Calculates the arithmetic mean of a sequence of quantities. + /// + /// The type of the quantity. + /// The collection of quantities to average. + /// The average of the quantities, using the unit of the first element in the sequence. + /// Thrown when the collection is null. + /// Thrown when the collection is empty. + internal static TQuantity ArithmeticMean(this IEnumerable quantities) + where TQuantity : IQuantityInstance + { + if (quantities is null) + { + throw new ArgumentNullException(nameof(quantities)); + } + + using IEnumerator enumerator = quantities.GetEnumerator(); + if (!enumerator.MoveNext()) + { + throw ExceptionHelper.CreateInvalidOperationOnEmptyCollectionException(); + } + + TQuantity firstQuantity = enumerator.Current!; + UnitKey resultUnit = firstQuantity.UnitKey; + QuantityValue sumOfValues = firstQuantity.Value; + var nbValues = 1; + while (enumerator.MoveNext()) + { + sumOfValues += enumerator.Current!.GetValue(resultUnit); + nbValues++; + } + +#if NET + return TQuantity.Create(sumOfValues / nbValues, resultUnit); +#else + return firstQuantity.QuantityInfo.Create(sumOfValues / nbValues, resultUnit); +#endif + } + + /// + /// Calculates the arithmetic mean of a sequence of quantities. + /// + /// The type of the quantity. + /// The unit type of the quantity. + /// The collection of quantities to average. + /// The unit in which to express the sum. + /// The average of the vector quantities in the specified unit. + /// Thrown when the collection is empty. + /// + /// This method is slightly more performant than the alternative + /// + /// when most of the quantities in the collection are expected to be in the target unit. + /// + internal static TQuantity ArithmeticMean(this IEnumerable quantities, TUnit unit) + where TQuantity : IQuantity + where TUnit: struct, Enum + { + if (quantities is null) + { + throw new ArgumentNullException(nameof(quantities)); + } + + using IEnumerator enumerator = quantities.GetEnumerator(); + if (!enumerator.MoveNext()) + { + throw ExceptionHelper.CreateInvalidOperationOnEmptyCollectionException(); + } + + TQuantity firstQuantity = enumerator.Current!; + var unitKey = UnitKey.ForUnit(unit); + QuantityValue sumOfValues = firstQuantity.GetValue(unitKey); + var nbValues = 1; + while (enumerator.MoveNext()) + { + sumOfValues += enumerator.Current!.GetValue(unitKey); + nbValues++; + } + + return firstQuantity.QuantityInfo.From(sumOfValues / nbValues, unit); + } +} diff --git a/UnitsNet/Extensions/UnitConversionExtensions.cs b/UnitsNet/Extensions/UnitConversionExtensions.cs new file mode 100644 index 0000000000..e444f438e4 --- /dev/null +++ b/UnitsNet/Extensions/UnitConversionExtensions.cs @@ -0,0 +1,58 @@ +// ReSharper disable once CheckNamespace +namespace UnitsNet.Units; + +/// +/// 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 : IQuantityInstance + { +#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 6526699053..f4e0600ff4 100644 --- a/UnitsNet/GeneratedCode/Quantities/AbsorbedDoseOfIonizingRadiation.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AbsorbedDoseOfIonizingRadiation.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,52 +46,130 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class AbsorbedDoseOfIonizingRadiationInfo: QuantityInfo + { + /// + public AbsorbedDoseOfIonizingRadiationInfo(string name, AbsorbedDoseOfIonizingRadiationUnit baseUnit, IEnumerable> unitMappings, AbsorbedDoseOfIonizingRadiation zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public AbsorbedDoseOfIonizingRadiationInfo(string name, AbsorbedDoseOfIonizingRadiationUnit baseUnit, IEnumerable> unitMappings, AbsorbedDoseOfIonizingRadiation zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, AbsorbedDoseOfIonizingRadiation.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.AbsorbedDoseOfIonizingRadiation", typeof(AbsorbedDoseOfIonizingRadiation).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the AbsorbedDoseOfIonizingRadiation quantity. + /// + /// A new instance of the class with the default settings. + public static AbsorbedDoseOfIonizingRadiationInfo CreateDefault() + { + return new AbsorbedDoseOfIonizingRadiationInfo(nameof(AbsorbedDoseOfIonizingRadiation), DefaultBaseUnit, GetDefaultMappings(), new AbsorbedDoseOfIonizingRadiation(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the AbsorbedDoseOfIonizingRadiation quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static AbsorbedDoseOfIonizingRadiationInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new AbsorbedDoseOfIonizingRadiationInfo(nameof(AbsorbedDoseOfIonizingRadiation), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new AbsorbedDoseOfIonizingRadiation(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-2L^2. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 0, -2, 0, 0, 0, 0); + + /// + /// The default base unit of AbsorbedDoseOfIonizingRadiation is Gray. All conversions, as defined in the , go via this value. + /// + public static AbsorbedDoseOfIonizingRadiationUnit DefaultBaseUnit { get; } = AbsorbedDoseOfIonizingRadiationUnit.Gray; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 100 + ); + 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, + 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() { - BaseDimensions = new BaseDimensions(2, 0, -2, 0, 0, 0, 0); - BaseUnit = AbsorbedDoseOfIonizingRadiationUnit.Gray; - Units = Enum.GetValues(typeof(AbsorbedDoseOfIonizingRadiationUnit)).Cast().ToArray(); - Zero = new AbsorbedDoseOfIonizingRadiation(0, BaseUnit); - Info = new QuantityInfo("AbsorbedDoseOfIonizingRadiation", - new UnitInfo[] - { - new UnitInfo(AbsorbedDoseOfIonizingRadiationUnit.Centigray, "Centigrays", new BaseUnits(length: LengthUnit.Decimeter, time: DurationUnit.Second), "AbsorbedDoseOfIonizingRadiation"), - new UnitInfo(AbsorbedDoseOfIonizingRadiationUnit.Femtogray, "Femtograys", BaseUnits.Undefined, "AbsorbedDoseOfIonizingRadiation"), - new UnitInfo(AbsorbedDoseOfIonizingRadiationUnit.Gigagray, "Gigagrays", BaseUnits.Undefined, "AbsorbedDoseOfIonizingRadiation"), - new UnitInfo(AbsorbedDoseOfIonizingRadiationUnit.Gray, "Grays", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second), "AbsorbedDoseOfIonizingRadiation"), - new UnitInfo(AbsorbedDoseOfIonizingRadiationUnit.Kilogray, "Kilograys", BaseUnits.Undefined, "AbsorbedDoseOfIonizingRadiation"), - new UnitInfo(AbsorbedDoseOfIonizingRadiationUnit.Kilorad, "Kilorads", BaseUnits.Undefined, "AbsorbedDoseOfIonizingRadiation"), - new UnitInfo(AbsorbedDoseOfIonizingRadiationUnit.Megagray, "Megagrays", new BaseUnits(length: LengthUnit.Kilometer, time: DurationUnit.Second), "AbsorbedDoseOfIonizingRadiation"), - new UnitInfo(AbsorbedDoseOfIonizingRadiationUnit.Megarad, "Megarads", BaseUnits.Undefined, "AbsorbedDoseOfIonizingRadiation"), - new UnitInfo(AbsorbedDoseOfIonizingRadiationUnit.Microgray, "Micrograys", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Second), "AbsorbedDoseOfIonizingRadiation"), - new UnitInfo(AbsorbedDoseOfIonizingRadiationUnit.Milligray, "Milligrays", BaseUnits.Undefined, "AbsorbedDoseOfIonizingRadiation"), - new UnitInfo(AbsorbedDoseOfIonizingRadiationUnit.Millirad, "Millirads", BaseUnits.Undefined, "AbsorbedDoseOfIonizingRadiation"), - new UnitInfo(AbsorbedDoseOfIonizingRadiationUnit.Nanogray, "Nanograys", BaseUnits.Undefined, "AbsorbedDoseOfIonizingRadiation"), - new UnitInfo(AbsorbedDoseOfIonizingRadiationUnit.Petagray, "Petagrays", BaseUnits.Undefined, "AbsorbedDoseOfIonizingRadiation"), - new UnitInfo(AbsorbedDoseOfIonizingRadiationUnit.Picogray, "Picograys", new BaseUnits(length: LengthUnit.Micrometer, time: DurationUnit.Second), "AbsorbedDoseOfIonizingRadiation"), - new UnitInfo(AbsorbedDoseOfIonizingRadiationUnit.Rad, "Rads", BaseUnits.Undefined, "AbsorbedDoseOfIonizingRadiation"), - new UnitInfo(AbsorbedDoseOfIonizingRadiationUnit.Teragray, "Teragrays", new BaseUnits(length: LengthUnit.Megameter, time: DurationUnit.Second), "AbsorbedDoseOfIonizingRadiation"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(AbsorbedDoseOfIonizingRadiationInfo.CreateDefault); } /// @@ -104,7 +177,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; @@ -118,7 +191,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); @@ -129,194 +202,159 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of AbsorbedDoseOfIonizingRadiation, which is Gray. All conversions go via this value. /// - public static AbsorbedDoseOfIonizingRadiationUnit BaseUnit { get; } + public static AbsorbedDoseOfIonizingRadiationUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the AbsorbedDoseOfIonizingRadiation quantity. /// - public static AbsorbedDoseOfIonizingRadiationUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Gray. /// - public static AbsorbedDoseOfIonizingRadiation Zero { get; } - - /// - public static AbsorbedDoseOfIonizingRadiation AdditiveIdentity => Zero; + public static AbsorbedDoseOfIonizingRadiation Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public AbsorbedDoseOfIonizingRadiationUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => AbsorbedDoseOfIonizingRadiation.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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 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.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.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. /// @@ -345,7 +383,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); } @@ -353,7 +391,7 @@ public static AbsorbedDoseOfIonizingRadiation FromCentigrays(double value) /// /// Creates a from . /// - public static AbsorbedDoseOfIonizingRadiation FromFemtograys(double value) + public static AbsorbedDoseOfIonizingRadiation FromFemtograys(QuantityValue value) { return new AbsorbedDoseOfIonizingRadiation(value, AbsorbedDoseOfIonizingRadiationUnit.Femtogray); } @@ -361,7 +399,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); } @@ -369,7 +407,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); } @@ -377,7 +415,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); } @@ -385,7 +423,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); } @@ -393,7 +431,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); } @@ -401,7 +439,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); } @@ -409,7 +447,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); } @@ -417,7 +455,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); } @@ -425,7 +463,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); } @@ -433,7 +471,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); } @@ -441,7 +479,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); } @@ -449,7 +487,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); } @@ -457,7 +495,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); } @@ -465,7 +503,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); } @@ -476,7 +514,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); } @@ -537,10 +575,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); } /// @@ -568,11 +603,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); } /// @@ -593,7 +624,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")); /// @@ -601,10 +632,10 @@ public static AbsorbedDoseOfIonizingRadiationUnit ParseUnit(string str) /// Error parsing string. public static AbsorbedDoseOfIonizingRadiationUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -619,10 +650,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -638,35 +669,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; } @@ -678,88 +709,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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current AbsorbedDoseOfIonizingRadiation. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(AbsorbedDoseOfIonizingRadiation), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -771,252 +796,24 @@ public int CompareTo(object? obj) /// public int CompareTo(AbsorbedDoseOfIonizingRadiation other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another AbsorbedDoseOfIonizingRadiation within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(AbsorbedDoseOfIonizingRadiation other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is AbsorbedDoseOfIonizingRadiation otherTyped - && (tolerance is AbsorbedDoseOfIonizingRadiation toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'AbsorbedDoseOfIonizingRadiation'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(AbsorbedDoseOfIonizingRadiation other, AbsorbedDoseOfIonizingRadiation tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current AbsorbedDoseOfIonizingRadiation. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(AbsorbedDoseOfIonizingRadiationUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - 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 NotImplementedException($"Can not 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.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.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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1031,137 +828,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(AbsorbedDoseOfIonizingRadiation)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(AbsorbedDoseOfIonizingRadiation)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(AbsorbedDoseOfIonizingRadiation)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(AbsorbedDoseOfIonizingRadiation)) - return this; - else if (conversionType == typeof(AbsorbedDoseOfIonizingRadiationUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return AbsorbedDoseOfIonizingRadiation.Info; - else if (conversionType == typeof(BaseDimensions)) - return AbsorbedDoseOfIonizingRadiation.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(AbsorbedDoseOfIonizingRadiation)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs b/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs index c998ba68e4..fa2a629b66 100644 --- a/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -55,50 +50,124 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class AccelerationInfo: QuantityInfo + { + /// + public AccelerationInfo(string name, AccelerationUnit baseUnit, IEnumerable> unitMappings, Acceleration zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public AccelerationInfo(string name, AccelerationUnit baseUnit, IEnumerable> unitMappings, Acceleration zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Acceleration.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Acceleration", typeof(Acceleration).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Acceleration quantity. + /// + /// A new instance of the class with the default settings. + public static AccelerationInfo CreateDefault() + { + return new AccelerationInfo(nameof(Acceleration), DefaultBaseUnit, GetDefaultMappings(), new Acceleration(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Acceleration quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static AccelerationInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new AccelerationInfo(nameof(Acceleration), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Acceleration(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-2L. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, 0, -2, 0, 0, 0, 0); + + /// + /// The default base unit of Acceleration is MeterPerSecondSquared. All conversions, as defined in the , go via this value. + /// + public static AccelerationUnit DefaultBaseUnit { get; } = AccelerationUnit.MeterPerSecondSquared; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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), + 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() { - BaseDimensions = new BaseDimensions(1, 0, -2, 0, 0, 0, 0); - BaseUnit = AccelerationUnit.MeterPerSecondSquared; - Units = Enum.GetValues(typeof(AccelerationUnit)).Cast().ToArray(); - Zero = new Acceleration(0, BaseUnit); - Info = new QuantityInfo("Acceleration", - new UnitInfo[] - { - new UnitInfo(AccelerationUnit.CentimeterPerSecondSquared, "CentimetersPerSecondSquared", new BaseUnits(length: LengthUnit.Centimeter, time: DurationUnit.Second), "Acceleration"), - new UnitInfo(AccelerationUnit.DecimeterPerSecondSquared, "DecimetersPerSecondSquared", new BaseUnits(length: LengthUnit.Decimeter, time: DurationUnit.Second), "Acceleration"), - new UnitInfo(AccelerationUnit.FootPerSecondSquared, "FeetPerSecondSquared", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Second), "Acceleration"), - new UnitInfo(AccelerationUnit.InchPerSecondSquared, "InchesPerSecondSquared", new BaseUnits(length: LengthUnit.Inch, time: DurationUnit.Second), "Acceleration"), - new UnitInfo(AccelerationUnit.KilometerPerSecondSquared, "KilometersPerSecondSquared", new BaseUnits(length: LengthUnit.Kilometer, time: DurationUnit.Second), "Acceleration"), - new UnitInfo(AccelerationUnit.KnotPerHour, "KnotsPerHour", new BaseUnits(length: LengthUnit.NauticalMile, time: DurationUnit.Hour), "Acceleration"), - new UnitInfo(AccelerationUnit.KnotPerMinute, "KnotsPerMinute", new BaseUnits(length: LengthUnit.NauticalMile, time: DurationUnit.Minute), "Acceleration"), - new UnitInfo(AccelerationUnit.KnotPerSecond, "KnotsPerSecond", new BaseUnits(length: LengthUnit.NauticalMile, time: DurationUnit.Second), "Acceleration"), - new UnitInfo(AccelerationUnit.MeterPerSecondSquared, "MetersPerSecondSquared", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second), "Acceleration"), - new UnitInfo(AccelerationUnit.MicrometerPerSecondSquared, "MicrometersPerSecondSquared", new BaseUnits(length: LengthUnit.Micrometer, time: DurationUnit.Second), "Acceleration"), - new UnitInfo(AccelerationUnit.MillimeterPerSecondSquared, "MillimetersPerSecondSquared", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Second), "Acceleration"), - new UnitInfo(AccelerationUnit.MillistandardGravity, "MillistandardGravity", BaseUnits.Undefined, "Acceleration"), - new UnitInfo(AccelerationUnit.NanometerPerSecondSquared, "NanometersPerSecondSquared", new BaseUnits(length: LengthUnit.Nanometer, time: DurationUnit.Second), "Acceleration"), - new UnitInfo(AccelerationUnit.StandardGravity, "StandardGravity", BaseUnits.Undefined, "Acceleration"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(AccelerationInfo.CreateDefault); } /// @@ -106,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; @@ -120,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); @@ -131,180 +200,149 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Acceleration, which is MeterPerSecondSquared. All conversions go via this value. /// - public static AccelerationUnit BaseUnit { get; } + public static AccelerationUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Acceleration quantity. /// - public static AccelerationUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit MeterPerSecondSquared. /// - public static Acceleration Zero { get; } - - /// - public static Acceleration AdditiveIdentity => Zero; + public static Acceleration Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public AccelerationUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Acceleration.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -333,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); } @@ -341,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); } @@ -349,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); } @@ -357,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); } @@ -365,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); } @@ -373,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); } @@ -381,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); } @@ -389,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); } @@ -397,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); } @@ -405,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); } @@ -413,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); } @@ -421,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); } @@ -429,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); } @@ -437,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); } @@ -448,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); } @@ -509,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); } /// @@ -540,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); } /// @@ -565,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")); /// @@ -573,10 +604,10 @@ public static AccelerationUnit ParseUnit(string str) /// Error parsing string. public static AccelerationUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -591,10 +622,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -610,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; } @@ -684,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Acceleration. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Acceleration), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -777,248 +802,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Acceleration other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Acceleration within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Acceleration other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Acceleration otherTyped - && (tolerance is Acceleration toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Acceleration'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Acceleration other, Acceleration tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Acceleration. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(AccelerationUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(AccelerationUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(AccelerationUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1033,137 +834,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Acceleration)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Acceleration)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Acceleration)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Acceleration)) - return this; - else if (conversionType == typeof(AccelerationUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Acceleration.Info; - else if (conversionType == typeof(BaseDimensions)) - return Acceleration.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Acceleration)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs b/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs index 70442d991c..8919d72a6d 100644 --- a/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -56,53 +51,133 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class AmountOfSubstanceInfo: QuantityInfo + { + /// + public AmountOfSubstanceInfo(string name, AmountOfSubstanceUnit baseUnit, IEnumerable> unitMappings, AmountOfSubstance zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public AmountOfSubstanceInfo(string name, AmountOfSubstanceUnit baseUnit, IEnumerable> unitMappings, AmountOfSubstance zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, AmountOfSubstance.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.AmountOfSubstance", typeof(AmountOfSubstance).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the AmountOfSubstance quantity. + /// + /// A new instance of the class with the default settings. + public static AmountOfSubstanceInfo CreateDefault() + { + return new AmountOfSubstanceInfo(nameof(AmountOfSubstance), DefaultBaseUnit, GetDefaultMappings(), new AmountOfSubstance(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the AmountOfSubstance quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static AmountOfSubstanceInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new AmountOfSubstanceInfo(nameof(AmountOfSubstance), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new AmountOfSubstance(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is N. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, 0, 0, 0, 1, 0); + + /// + /// The default base unit of AmountOfSubstance is Mole. All conversions, as defined in the , go via this value. + /// + public static AmountOfSubstanceUnit DefaultBaseUnit { get; } = AmountOfSubstanceUnit.Mole; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for AmountOfSubstance. + public static IEnumerable> GetDefaultMappings() + { + 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), + 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() { - BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 1, 0); - BaseUnit = AmountOfSubstanceUnit.Mole; - Units = Enum.GetValues(typeof(AmountOfSubstanceUnit)).Cast().ToArray(); - Zero = new AmountOfSubstance(0, BaseUnit); - Info = new QuantityInfo("AmountOfSubstance", - new UnitInfo[] - { - new UnitInfo(AmountOfSubstanceUnit.Centimole, "Centimoles", new BaseUnits(amount: AmountOfSubstanceUnit.Centimole), "AmountOfSubstance"), - new UnitInfo(AmountOfSubstanceUnit.CentipoundMole, "CentipoundMoles", new BaseUnits(amount: AmountOfSubstanceUnit.CentipoundMole), "AmountOfSubstance"), - new UnitInfo(AmountOfSubstanceUnit.Decimole, "Decimoles", new BaseUnits(amount: AmountOfSubstanceUnit.Decimole), "AmountOfSubstance"), - new UnitInfo(AmountOfSubstanceUnit.DecipoundMole, "DecipoundMoles", new BaseUnits(amount: AmountOfSubstanceUnit.DecipoundMole), "AmountOfSubstance"), - new UnitInfo(AmountOfSubstanceUnit.Femtomole, "Femtomoles", new BaseUnits(amount: AmountOfSubstanceUnit.Femtomole), "AmountOfSubstance"), - new UnitInfo(AmountOfSubstanceUnit.Kilomole, "Kilomoles", new BaseUnits(amount: AmountOfSubstanceUnit.Kilomole), "AmountOfSubstance"), - new UnitInfo(AmountOfSubstanceUnit.KilopoundMole, "KilopoundMoles", new BaseUnits(amount: AmountOfSubstanceUnit.KilopoundMole), "AmountOfSubstance"), - new UnitInfo(AmountOfSubstanceUnit.Megamole, "Megamoles", new BaseUnits(amount: AmountOfSubstanceUnit.Megamole), "AmountOfSubstance"), - new UnitInfo(AmountOfSubstanceUnit.Micromole, "Micromoles", new BaseUnits(amount: AmountOfSubstanceUnit.Micromole), "AmountOfSubstance"), - new UnitInfo(AmountOfSubstanceUnit.MicropoundMole, "MicropoundMoles", new BaseUnits(amount: AmountOfSubstanceUnit.MicropoundMole), "AmountOfSubstance"), - new UnitInfo(AmountOfSubstanceUnit.Millimole, "Millimoles", new BaseUnits(amount: AmountOfSubstanceUnit.Millimole), "AmountOfSubstance"), - new UnitInfo(AmountOfSubstanceUnit.MillipoundMole, "MillipoundMoles", new BaseUnits(amount: AmountOfSubstanceUnit.MillipoundMole), "AmountOfSubstance"), - new UnitInfo(AmountOfSubstanceUnit.Mole, "Moles", new BaseUnits(amount: AmountOfSubstanceUnit.Mole), "AmountOfSubstance"), - new UnitInfo(AmountOfSubstanceUnit.Nanomole, "Nanomoles", new BaseUnits(amount: AmountOfSubstanceUnit.Nanomole), "AmountOfSubstance"), - new UnitInfo(AmountOfSubstanceUnit.NanopoundMole, "NanopoundMoles", new BaseUnits(amount: AmountOfSubstanceUnit.NanopoundMole), "AmountOfSubstance"), - new UnitInfo(AmountOfSubstanceUnit.Picomole, "Picomoles", new BaseUnits(amount: AmountOfSubstanceUnit.Picomole), "AmountOfSubstance"), - new UnitInfo(AmountOfSubstanceUnit.PoundMole, "PoundMoles", new BaseUnits(amount: AmountOfSubstanceUnit.PoundMole), "AmountOfSubstance"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(AmountOfSubstanceInfo.CreateDefault); } /// @@ -110,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; @@ -124,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); @@ -135,201 +210,164 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of AmountOfSubstance, which is Mole. All conversions go via this value. /// - public static AmountOfSubstanceUnit BaseUnit { get; } + public static AmountOfSubstanceUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the AmountOfSubstance quantity. /// - public static AmountOfSubstanceUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Mole. /// - public static AmountOfSubstance Zero { get; } - - /// - public static AmountOfSubstance AdditiveIdentity => Zero; + public static AmountOfSubstance Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public AmountOfSubstanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => AmountOfSubstance.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -358,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); } @@ -366,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); } @@ -374,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); } @@ -382,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); } @@ -390,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); } @@ -398,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); } @@ -406,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); } @@ -414,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); } @@ -422,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); } @@ -430,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); } @@ -438,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); } @@ -446,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); } @@ -454,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); } @@ -462,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); } @@ -470,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); } @@ -478,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); } @@ -486,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); } @@ -497,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); } @@ -558,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); } /// @@ -589,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); } /// @@ -614,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")); /// @@ -622,10 +653,10 @@ public static AmountOfSubstanceUnit ParseUnit(string str) /// Error parsing string. public static AmountOfSubstanceUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -640,10 +671,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -659,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; } @@ -739,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current AmountOfSubstance. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(AmountOfSubstance), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -832,254 +857,24 @@ public int CompareTo(object? obj) /// public int CompareTo(AmountOfSubstance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another AmountOfSubstance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(AmountOfSubstance other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is AmountOfSubstance otherTyped - && (tolerance is AmountOfSubstance toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'AmountOfSubstance'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(AmountOfSubstance other, AmountOfSubstance tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current AmountOfSubstance. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(AmountOfSubstanceUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(AmountOfSubstanceUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(AmountOfSubstanceUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1094,137 +889,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(AmountOfSubstance)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(AmountOfSubstance)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(AmountOfSubstance)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(AmountOfSubstance)) - return this; - else if (conversionType == typeof(AmountOfSubstanceUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return AmountOfSubstance.Info; - else if (conversionType == typeof(BaseDimensions)) - return AmountOfSubstance.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(AmountOfSubstance)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs b/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs index 824ccb8c40..299de2792f 100644 --- a/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,49 +33,107 @@ 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 : - IArithmeticQuantity, + ILogarithmicQuantity, #if NET7_0_OR_GREATER IComparisonOperators, IParsable, #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static AmplitudeRatio() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class AmplitudeRatioInfo: QuantityInfo { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = AmplitudeRatioUnit.DecibelVolt; - Units = Enum.GetValues(typeof(AmplitudeRatioUnit)).Cast().ToArray(); - Zero = new AmplitudeRatio(0, BaseUnit); - Info = new QuantityInfo("AmplitudeRatio", - new UnitInfo[] - { - new UnitInfo(AmplitudeRatioUnit.DecibelMicrovolt, "DecibelMicrovolts", BaseUnits.Undefined, "AmplitudeRatio"), - new UnitInfo(AmplitudeRatioUnit.DecibelMillivolt, "DecibelMillivolts", BaseUnits.Undefined, "AmplitudeRatio"), - new UnitInfo(AmplitudeRatioUnit.DecibelUnloaded, "DecibelsUnloaded", BaseUnits.Undefined, "AmplitudeRatio"), - new UnitInfo(AmplitudeRatioUnit.DecibelVolt, "DecibelVolts", BaseUnits.Undefined, "AmplitudeRatio"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public AmplitudeRatioInfo(string name, AmplitudeRatioUnit baseUnit, IEnumerable> unitMappings, AmplitudeRatio zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public AmplitudeRatioInfo(string name, AmplitudeRatioUnit baseUnit, IEnumerable> unitMappings, AmplitudeRatio zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, AmplitudeRatio.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.AmplitudeRatio", typeof(AmplitudeRatio).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the AmplitudeRatio quantity. + /// + /// A new instance of the class with the default settings. + public static AmplitudeRatioInfo CreateDefault() + { + return new AmplitudeRatioInfo(nameof(AmplitudeRatio), DefaultBaseUnit, GetDefaultMappings(), new AmplitudeRatio(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the AmplitudeRatio quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static AmplitudeRatioInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new AmplitudeRatioInfo(nameof(AmplitudeRatio), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new AmplitudeRatio(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is . + /// + public static BaseDimensions DefaultBaseDimensions { get; } = BaseDimensions.Dimensionless; + + /// + /// The default base unit of AmplitudeRatio is DecibelVolt. All conversions, as defined in the , go via this value. + /// + public static AmplitudeRatioUnit DefaultBaseUnit { get; } = AmplitudeRatioUnit.DecibelVolt; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for AmplitudeRatio. + public static IEnumerable> GetDefaultMappings() + { + 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 = UnitsNetSetup.CreateQuantityInfo(AmplitudeRatioInfo.CreateDefault); } /// @@ -89,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; @@ -100,110 +152,106 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of AmplitudeRatio, which is DecibelVolt. All conversions go via this value. /// - public static AmplitudeRatioUnit BaseUnit { get; } + public static AmplitudeRatioUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the AmplitudeRatio quantity. /// - public static AmplitudeRatioUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit DecibelVolt. /// - public static AmplitudeRatio Zero { get; } + public static AmplitudeRatio Zero => Info.Zero; - /// - public static AmplitudeRatio AdditiveIdentity => Zero; + /// + public static QuantityValue LogarithmicScalingFactor {get;} = 20; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public AmplitudeRatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => AmplitudeRatio.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + +#if NETSTANDARD2_0 + QuantityValue ILogarithmicQuantity.LogarithmicScalingFactor => LogarithmicScalingFactor; +#endif + + #endregion + #endregion #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. /// @@ -232,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); } @@ -240,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); } @@ -248,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); } @@ -256,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); } @@ -267,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); } @@ -328,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); } /// @@ -359,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); } /// @@ -384,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")); /// @@ -392,10 +433,10 @@ public static AmplitudeRatioUnit ParseUnit(string str) /// Error parsing string. public static AmplitudeRatioUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -410,10 +451,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -421,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 @@ -477,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current AmplitudeRatio. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(AmplitudeRatio), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -570,228 +613,24 @@ public int CompareTo(object? obj) /// public int CompareTo(AmplitudeRatio other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another AmplitudeRatio within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(AmplitudeRatio other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is AmplitudeRatio otherTyped - && (tolerance is AmplitudeRatio toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'AmplitudeRatio'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(AmplitudeRatio other, AmplitudeRatio tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current AmplitudeRatio. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(AmplitudeRatioUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(AmplitudeRatioUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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), - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -806,137 +645,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(AmplitudeRatio)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(AmplitudeRatio)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(AmplitudeRatio)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(AmplitudeRatio)) - return this; - else if (conversionType == typeof(AmplitudeRatioUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return AmplitudeRatio.Info; - else if (conversionType == typeof(BaseDimensions)) - return AmplitudeRatio.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(AmplitudeRatio)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Angle.g.cs b/UnitsNet/GeneratedCode/Quantities/Angle.g.cs index 20072f8797..669c272e87 100644 --- a/UnitsNet/GeneratedCode/Quantities/Angle.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Angle.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -53,51 +48,127 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class AngleInfo: QuantityInfo + { + /// + public AngleInfo(string name, AngleUnit baseUnit, IEnumerable> unitMappings, Angle zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public AngleInfo(string name, AngleUnit baseUnit, IEnumerable> unitMappings, Angle zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Angle.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Angle", typeof(Angle).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Angle quantity. + /// + /// A new instance of the class with the default settings. + public static AngleInfo CreateDefault() + { + return new AngleInfo(nameof(Angle), DefaultBaseUnit, GetDefaultMappings(), new Angle(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Angle quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static AngleInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new AngleInfo(nameof(Angle), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Angle(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is . + /// + public static BaseDimensions DefaultBaseDimensions { get; } = BaseDimensions.Dimensionless; + + /// + /// The default base unit of Angle is Radian. All conversions, as defined in the , go via this value. + /// + public static AngleUnit DefaultBaseUnit { get; } = AngleUnit.Radian; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Angle. + public static IEnumerable> GetDefaultMappings() + { + 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, + new QuantityValue(500000000000000, 3141592653589793) + ); + } + } + static Angle() { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = AngleUnit.Radian; - Units = Enum.GetValues(typeof(AngleUnit)).Cast().ToArray(); - Zero = new Angle(0, BaseUnit); - Info = new QuantityInfo("Angle", - new UnitInfo[] - { - new UnitInfo(AngleUnit.Arcminute, "Arcminutes", BaseUnits.Undefined, "Angle"), - new UnitInfo(AngleUnit.Arcsecond, "Arcseconds", BaseUnits.Undefined, "Angle"), - new UnitInfo(AngleUnit.Centiradian, "Centiradians", BaseUnits.Undefined, "Angle"), - new UnitInfo(AngleUnit.Deciradian, "Deciradians", BaseUnits.Undefined, "Angle"), - new UnitInfo(AngleUnit.Degree, "Degrees", BaseUnits.Undefined, "Angle"), - new UnitInfo(AngleUnit.Gradian, "Gradians", BaseUnits.Undefined, "Angle"), - new UnitInfo(AngleUnit.Microdegree, "Microdegrees", BaseUnits.Undefined, "Angle"), - new UnitInfo(AngleUnit.Microradian, "Microradians", BaseUnits.Undefined, "Angle"), - new UnitInfo(AngleUnit.Millidegree, "Millidegrees", BaseUnits.Undefined, "Angle"), - new UnitInfo(AngleUnit.Milliradian, "Milliradians", BaseUnits.Undefined, "Angle"), - new UnitInfo(AngleUnit.Nanodegree, "Nanodegrees", BaseUnits.Undefined, "Angle"), - new UnitInfo(AngleUnit.Nanoradian, "Nanoradians", BaseUnits.Undefined, "Angle"), - new UnitInfo(AngleUnit.NatoMil, "NatoMils", BaseUnits.Undefined, "Angle"), - new UnitInfo(AngleUnit.Radian, "Radians", BaseUnits.Undefined, "Angle"), - new UnitInfo(AngleUnit.Revolution, "Revolutions", BaseUnits.Undefined, "Angle"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(AngleInfo.CreateDefault); } /// @@ -105,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; @@ -116,187 +187,154 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Angle, which is Radian. All conversions go via this value. /// - public static AngleUnit BaseUnit { get; } + public static AngleUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Angle quantity. /// - public static AngleUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Radian. /// - public static Angle Zero { get; } - - /// - public static Angle AdditiveIdentity => Zero; + public static Angle Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public AngleUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Angle.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -325,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); } @@ -333,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); } @@ -341,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); } @@ -349,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); } @@ -357,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); } @@ -365,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); } @@ -373,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); } @@ -381,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); } @@ -389,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); } @@ -397,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); } @@ -405,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); } @@ -413,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); } @@ -421,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); } @@ -429,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); } @@ -437,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); } @@ -448,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); } @@ -509,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); } /// @@ -540,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); } /// @@ -565,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")); /// @@ -573,10 +604,10 @@ public static AngleUnit ParseUnit(string str) /// Error parsing string. public static AngleUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -591,10 +622,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -610,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; } @@ -672,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Angle. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Angle), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -765,250 +790,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Angle other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Angle within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Angle other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Angle otherTyped - && (tolerance is Angle toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Angle'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Angle other, Angle tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Angle. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(AngleUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(AngleUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(AngleUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1023,137 +822,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Angle)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Angle)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Angle)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Angle)) - return this; - else if (conversionType == typeof(AngleUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Angle.Info; - else if (conversionType == typeof(BaseDimensions)) - return Angle.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Angle)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Area.g.cs b/UnitsNet/GeneratedCode/Quantities/Area.g.cs index 4a5eed40b2..b7bb0e5a1f 100644 --- a/UnitsNet/GeneratedCode/Quantities/Area.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Area.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -66,50 +61,124 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class AreaInfo: QuantityInfo + { + /// + public AreaInfo(string name, AreaUnit baseUnit, IEnumerable> unitMappings, Area zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public AreaInfo(string name, AreaUnit baseUnit, IEnumerable> unitMappings, Area zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Area.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Area", typeof(Area).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Area quantity. + /// + /// A new instance of the class with the default settings. + public static AreaInfo CreateDefault() + { + return new AreaInfo(nameof(Area), DefaultBaseUnit, GetDefaultMappings(), new Area(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Area quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static AreaInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new AreaInfo(nameof(Area), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Area(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is L^2. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); + + /// + /// The default base unit of Area is SquareMeter. All conversions, as defined in the , go via this value. + /// + public static AreaUnit DefaultBaseUnit { get; } = AreaUnit.SquareMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Area. + public static IEnumerable> GetDefaultMappings() + { + 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), + 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() { - BaseDimensions = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); - BaseUnit = AreaUnit.SquareMeter; - Units = Enum.GetValues(typeof(AreaUnit)).Cast().ToArray(); - Zero = new Area(0, BaseUnit); - Info = new QuantityInfo("Area", - new UnitInfo[] - { - new UnitInfo(AreaUnit.Acre, "Acres", BaseUnits.Undefined, "Area"), - new UnitInfo(AreaUnit.Hectare, "Hectares", BaseUnits.Undefined, "Area"), - new UnitInfo(AreaUnit.SquareCentimeter, "SquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter), "Area"), - new UnitInfo(AreaUnit.SquareDecimeter, "SquareDecimeters", new BaseUnits(length: LengthUnit.Decimeter), "Area"), - new UnitInfo(AreaUnit.SquareFoot, "SquareFeet", new BaseUnits(length: LengthUnit.Foot), "Area"), - new UnitInfo(AreaUnit.SquareInch, "SquareInches", new BaseUnits(length: LengthUnit.Inch), "Area"), - new UnitInfo(AreaUnit.SquareKilometer, "SquareKilometers", new BaseUnits(length: LengthUnit.Kilometer), "Area"), - new UnitInfo(AreaUnit.SquareMeter, "SquareMeters", new BaseUnits(length: LengthUnit.Meter), "Area"), - new UnitInfo(AreaUnit.SquareMicrometer, "SquareMicrometers", new BaseUnits(length: LengthUnit.Micrometer), "Area"), - new UnitInfo(AreaUnit.SquareMile, "SquareMiles", new BaseUnits(length: LengthUnit.Mile), "Area"), - new UnitInfo(AreaUnit.SquareMillimeter, "SquareMillimeters", new BaseUnits(length: LengthUnit.Millimeter), "Area"), - new UnitInfo(AreaUnit.SquareNauticalMile, "SquareNauticalMiles", BaseUnits.Undefined, "Area"), - new UnitInfo(AreaUnit.SquareYard, "SquareYards", new BaseUnits(length: LengthUnit.Yard), "Area"), - new UnitInfo(AreaUnit.UsSurveySquareFoot, "UsSurveySquareFeet", new BaseUnits(length: LengthUnit.UsSurveyFoot), "Area"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(AreaInfo.CreateDefault); } /// @@ -117,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; @@ -131,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); @@ -142,180 +211,149 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Area, which is SquareMeter. All conversions go via this value. /// - public static AreaUnit BaseUnit { get; } + public static AreaUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Area quantity. /// - public static AreaUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeter. /// - public static Area Zero { get; } - - /// - public static Area AdditiveIdentity => Zero; + public static Area Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public AreaUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Area.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -344,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); } @@ -352,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); } @@ -360,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); } @@ -368,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); } @@ -376,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); } @@ -384,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); } @@ -392,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); } @@ -400,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); } @@ -408,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); } @@ -416,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); } @@ -424,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); } @@ -432,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); } @@ -440,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); } @@ -448,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); } @@ -459,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); } @@ -520,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); } /// @@ -551,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); } /// @@ -576,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")); /// @@ -584,10 +615,10 @@ public static AreaUnit ParseUnit(string str) /// Error parsing string. public static AreaUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -602,10 +633,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -621,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; } @@ -662,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 * . @@ -768,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Area. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Area), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -861,248 +886,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Area other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Area within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Area other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Area otherTyped - && (tolerance is Area toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Area'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Area other, Area tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Area. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(AreaUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(AreaUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1117,137 +918,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Area)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Area)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Area)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Area)) - return this; - else if (conversionType == typeof(AreaUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Area.Info; - else if (conversionType == typeof(BaseDimensions)) - return Area.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Area)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs index 0092dc509e..8b944396cf 100644 --- a/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -51,39 +46,91 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static AreaDensity() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class AreaDensityInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(-2, 1, 0, 0, 0, 0, 0); - BaseUnit = AreaDensityUnit.KilogramPerSquareMeter; - Units = Enum.GetValues(typeof(AreaDensityUnit)).Cast().ToArray(); - Zero = new AreaDensity(0, BaseUnit); - Info = new QuantityInfo("AreaDensity", - new UnitInfo[] - { - new UnitInfo(AreaDensityUnit.GramPerSquareMeter, "GramsPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram), "AreaDensity"), - new UnitInfo(AreaDensityUnit.KilogramPerSquareMeter, "KilogramsPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram), "AreaDensity"), - new UnitInfo(AreaDensityUnit.MilligramPerSquareMeter, "MilligramsPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram), "AreaDensity"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public AreaDensityInfo(string name, AreaDensityUnit baseUnit, IEnumerable> unitMappings, AreaDensity zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public AreaDensityInfo(string name, AreaDensityUnit baseUnit, IEnumerable> unitMappings, AreaDensity zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, AreaDensity.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.AreaDensity", typeof(AreaDensity).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the AreaDensity quantity. + /// + /// A new instance of the class with the default settings. + public static AreaDensityInfo CreateDefault() + { + return new AreaDensityInfo(nameof(AreaDensity), DefaultBaseUnit, GetDefaultMappings(), new AreaDensity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the AreaDensity quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static AreaDensityInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new AreaDensityInfo(nameof(AreaDensity), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new AreaDensity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is L^-2M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, 1, 0, 0, 0, 0, 0); + + /// + /// The default base unit of AreaDensity is KilogramPerSquareMeter. All conversions, as defined in the , go via this value. + /// + public static AreaDensityUnit DefaultBaseUnit { get; } = AreaDensityUnit.KilogramPerSquareMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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), + 1000000 + ); + } + } + + static AreaDensity() + { + Info = UnitsNetSetup.CreateQuantityInfo(AreaDensityInfo.CreateDefault); } /// @@ -91,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; @@ -105,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); @@ -116,103 +163,94 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of AreaDensity, which is KilogramPerSquareMeter. All conversions go via this value. /// - public static AreaDensityUnit BaseUnit { get; } + public static AreaDensityUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the AreaDensity quantity. /// - public static AreaDensityUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerSquareMeter. /// - public static AreaDensity Zero { get; } - - /// - public static AreaDensity AdditiveIdentity => Zero; + public static AreaDensity Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public AreaDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => AreaDensity.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -241,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); } @@ -249,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); } @@ -257,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); } @@ -268,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); } @@ -329,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); } /// @@ -360,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); } /// @@ -385,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")); /// @@ -393,10 +424,10 @@ public static AreaDensityUnit ParseUnit(string str) /// Error parsing string. public static AreaDensityUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -411,10 +442,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -430,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; } @@ -480,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current AreaDensity. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(AreaDensity), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -573,226 +598,24 @@ public int CompareTo(object? obj) /// public int CompareTo(AreaDensity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another AreaDensity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(AreaDensity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is AreaDensity otherTyped - && (tolerance is AreaDensity toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'AreaDensity'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(AreaDensity other, AreaDensity tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current AreaDensity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(AreaDensityUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(AreaDensityUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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), - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -807,137 +630,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(AreaDensity)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(AreaDensity)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(AreaDensity)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(AreaDensity)) - return this; - else if (conversionType == typeof(AreaDensityUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return AreaDensity.Info; - else if (conversionType == typeof(BaseDimensions)) - return AreaDensity.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(AreaDensity)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs b/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs index 6ea9a72cb7..dde65372c8 100644 --- a/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -52,42 +47,100 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static AreaMomentOfInertia() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class AreaMomentOfInertiaInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(4, 0, 0, 0, 0, 0, 0); - BaseUnit = AreaMomentOfInertiaUnit.MeterToTheFourth; - Units = Enum.GetValues(typeof(AreaMomentOfInertiaUnit)).Cast().ToArray(); - Zero = new AreaMomentOfInertia(0, BaseUnit); - Info = new QuantityInfo("AreaMomentOfInertia", - new UnitInfo[] - { - new UnitInfo(AreaMomentOfInertiaUnit.CentimeterToTheFourth, "CentimetersToTheFourth", new BaseUnits(length: LengthUnit.Centimeter), "AreaMomentOfInertia"), - new UnitInfo(AreaMomentOfInertiaUnit.DecimeterToTheFourth, "DecimetersToTheFourth", new BaseUnits(length: LengthUnit.Decimeter), "AreaMomentOfInertia"), - new UnitInfo(AreaMomentOfInertiaUnit.FootToTheFourth, "FeetToTheFourth", new BaseUnits(length: LengthUnit.Foot), "AreaMomentOfInertia"), - new UnitInfo(AreaMomentOfInertiaUnit.InchToTheFourth, "InchesToTheFourth", new BaseUnits(length: LengthUnit.Inch), "AreaMomentOfInertia"), - new UnitInfo(AreaMomentOfInertiaUnit.MeterToTheFourth, "MetersToTheFourth", new BaseUnits(length: LengthUnit.Meter), "AreaMomentOfInertia"), - new UnitInfo(AreaMomentOfInertiaUnit.MillimeterToTheFourth, "MillimetersToTheFourth", new BaseUnits(length: LengthUnit.Millimeter), "AreaMomentOfInertia"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public AreaMomentOfInertiaInfo(string name, AreaMomentOfInertiaUnit baseUnit, IEnumerable> unitMappings, AreaMomentOfInertia zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public AreaMomentOfInertiaInfo(string name, AreaMomentOfInertiaUnit baseUnit, IEnumerable> unitMappings, AreaMomentOfInertia zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, AreaMomentOfInertia.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.AreaMomentOfInertia", typeof(AreaMomentOfInertia).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the AreaMomentOfInertia quantity. + /// + /// A new instance of the class with the default settings. + public static AreaMomentOfInertiaInfo CreateDefault() + { + return new AreaMomentOfInertiaInfo(nameof(AreaMomentOfInertia), DefaultBaseUnit, GetDefaultMappings(), new AreaMomentOfInertia(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the AreaMomentOfInertia quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static AreaMomentOfInertiaInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new AreaMomentOfInertiaInfo(nameof(AreaMomentOfInertia), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new AreaMomentOfInertia(0, DefaultBaseUnit), DefaultBaseDimensions); + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// The for is L^4. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(4, 0, 0, 0, 0, 0, 0); + + /// + /// The default base unit of AreaMomentOfInertia is MeterToTheFourth. All conversions, as defined in the , go via this value. + /// + public static AreaMomentOfInertiaUnit DefaultBaseUnit { get; } = AreaMomentOfInertiaUnit.MeterToTheFourth; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for AreaMomentOfInertia. + public static IEnumerable> GetDefaultMappings() + { + 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), + 1000000000000 + ); + } + } + + static AreaMomentOfInertia() + { + Info = UnitsNetSetup.CreateQuantityInfo(AreaMomentOfInertiaInfo.CreateDefault); } /// @@ -95,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; @@ -109,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); @@ -120,124 +173,109 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of AreaMomentOfInertia, which is MeterToTheFourth. All conversions go via this value. /// - public static AreaMomentOfInertiaUnit BaseUnit { get; } + public static AreaMomentOfInertiaUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the AreaMomentOfInertia quantity. /// - public static AreaMomentOfInertiaUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit MeterToTheFourth. /// - public static AreaMomentOfInertia Zero { get; } - - /// - public static AreaMomentOfInertia AdditiveIdentity => Zero; + public static AreaMomentOfInertia Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public AreaMomentOfInertiaUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => AreaMomentOfInertia.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -266,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); } @@ -274,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); } @@ -282,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); } @@ -290,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); } @@ -298,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); } @@ -306,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); } @@ -317,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); } @@ -378,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); } /// @@ -409,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); } /// @@ -434,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")); /// @@ -442,10 +473,10 @@ public static AreaMomentOfInertiaUnit ParseUnit(string str) /// Error parsing string. public static AreaMomentOfInertiaUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -460,10 +491,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -479,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; } @@ -535,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current AreaMomentOfInertia. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(AreaMomentOfInertia), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -628,232 +653,24 @@ public int CompareTo(object? obj) /// public int CompareTo(AreaMomentOfInertia other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another AreaMomentOfInertia within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(AreaMomentOfInertia other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is AreaMomentOfInertia otherTyped - && (tolerance is AreaMomentOfInertia toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'AreaMomentOfInertia'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(AreaMomentOfInertia other, AreaMomentOfInertia tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current AreaMomentOfInertia. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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)); + #region Conversion Methods (explicit implementations for netstandard2.0) - 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 AreaMomentOfInertiaUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AreaMomentOfInertiaUnit)} 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(AreaMomentOfInertiaUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(AreaMomentOfInertiaUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -868,137 +685,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(AreaMomentOfInertia)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(AreaMomentOfInertia)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(AreaMomentOfInertia)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(AreaMomentOfInertia)) - return this; - else if (conversionType == typeof(AreaMomentOfInertiaUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return AreaMomentOfInertia.Info; - else if (conversionType == typeof(BaseDimensions)) - return AreaMomentOfInertia.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(AreaMomentOfInertia)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs b/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs index f073a23c80..97ca08c2d4 100644 --- a/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,62 +46,160 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class BitRateInfo: QuantityInfo + { + /// + public BitRateInfo(string name, BitRateUnit baseUnit, IEnumerable> unitMappings, BitRate zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public BitRateInfo(string name, BitRateUnit baseUnit, IEnumerable> unitMappings, BitRate zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, BitRate.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.BitRate", typeof(BitRate).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the BitRate quantity. + /// + /// A new instance of the class with the default settings. + public static BitRateInfo CreateDefault() + { + return new BitRateInfo(nameof(BitRate), DefaultBaseUnit, GetDefaultMappings(), new BitRate(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the BitRate quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static BitRateInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new BitRateInfo(nameof(BitRate), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new BitRate(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-1. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); + + /// + /// The default base unit of BitRate is BitPerSecond. All conversions, as defined in the , go via this value. + /// + public static BitRateUnit DefaultBaseUnit { get; } = BitRateUnit.BitPerSecond; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for BitRate. + public static IEnumerable> GetDefaultMappings() + { + yield return new (BitRateUnit.BitPerSecond, "BitPerSecond", "BitsPerSecond", new BaseUnits(time: DurationUnit.Second)); + 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.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.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.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.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.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.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.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.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.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.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.TerabitPerSecond, "TerabitPerSecond", "TerabitsPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 1000000000000) + ); + yield return new (BitRateUnit.TerabytePerSecond, "TerabytePerSecond", "TerabytesPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 8000000000000) + ); + } + } + static BitRate() { - BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); - BaseUnit = BitRateUnit.BitPerSecond; - Units = Enum.GetValues(typeof(BitRateUnit)).Cast().ToArray(); - Zero = new BitRate(0, BaseUnit); - Info = new QuantityInfo("BitRate", - new UnitInfo[] - { - new UnitInfo(BitRateUnit.BitPerSecond, "BitsPerSecond", new BaseUnits(time: DurationUnit.Second), "BitRate"), - new UnitInfo(BitRateUnit.BytePerSecond, "BytesPerSecond", BaseUnits.Undefined, "BitRate"), - new UnitInfo(BitRateUnit.ExabitPerSecond, "ExabitsPerSecond", BaseUnits.Undefined, "BitRate"), - new UnitInfo(BitRateUnit.ExabytePerSecond, "ExabytesPerSecond", BaseUnits.Undefined, "BitRate"), - new UnitInfo(BitRateUnit.ExbibitPerSecond, "ExbibitsPerSecond", BaseUnits.Undefined, "BitRate"), - new UnitInfo(BitRateUnit.ExbibytePerSecond, "ExbibytesPerSecond", BaseUnits.Undefined, "BitRate"), - new UnitInfo(BitRateUnit.GibibitPerSecond, "GibibitsPerSecond", BaseUnits.Undefined, "BitRate"), - new UnitInfo(BitRateUnit.GibibytePerSecond, "GibibytesPerSecond", BaseUnits.Undefined, "BitRate"), - new UnitInfo(BitRateUnit.GigabitPerSecond, "GigabitsPerSecond", new BaseUnits(time: DurationUnit.Nanosecond), "BitRate"), - new UnitInfo(BitRateUnit.GigabytePerSecond, "GigabytesPerSecond", BaseUnits.Undefined, "BitRate"), - new UnitInfo(BitRateUnit.KibibitPerSecond, "KibibitsPerSecond", BaseUnits.Undefined, "BitRate"), - new UnitInfo(BitRateUnit.KibibytePerSecond, "KibibytesPerSecond", BaseUnits.Undefined, "BitRate"), - new UnitInfo(BitRateUnit.KilobitPerSecond, "KilobitsPerSecond", new BaseUnits(time: DurationUnit.Millisecond), "BitRate"), - new UnitInfo(BitRateUnit.KilobytePerSecond, "KilobytesPerSecond", BaseUnits.Undefined, "BitRate"), - new UnitInfo(BitRateUnit.MebibitPerSecond, "MebibitsPerSecond", BaseUnits.Undefined, "BitRate"), - new UnitInfo(BitRateUnit.MebibytePerSecond, "MebibytesPerSecond", BaseUnits.Undefined, "BitRate"), - new UnitInfo(BitRateUnit.MegabitPerSecond, "MegabitsPerSecond", new BaseUnits(time: DurationUnit.Microsecond), "BitRate"), - new UnitInfo(BitRateUnit.MegabytePerSecond, "MegabytesPerSecond", BaseUnits.Undefined, "BitRate"), - new UnitInfo(BitRateUnit.PebibitPerSecond, "PebibitsPerSecond", BaseUnits.Undefined, "BitRate"), - new UnitInfo(BitRateUnit.PebibytePerSecond, "PebibytesPerSecond", BaseUnits.Undefined, "BitRate"), - new UnitInfo(BitRateUnit.PetabitPerSecond, "PetabitsPerSecond", BaseUnits.Undefined, "BitRate"), - new UnitInfo(BitRateUnit.PetabytePerSecond, "PetabytesPerSecond", BaseUnits.Undefined, "BitRate"), - new UnitInfo(BitRateUnit.TebibitPerSecond, "TebibitsPerSecond", BaseUnits.Undefined, "BitRate"), - new UnitInfo(BitRateUnit.TebibytePerSecond, "TebibytesPerSecond", BaseUnits.Undefined, "BitRate"), - new UnitInfo(BitRateUnit.TerabitPerSecond, "TerabitsPerSecond", BaseUnits.Undefined, "BitRate"), - new UnitInfo(BitRateUnit.TerabytePerSecond, "TerabytesPerSecond", BaseUnits.Undefined, "BitRate"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(BitRateInfo.CreateDefault); } /// @@ -114,7 +207,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; @@ -128,7 +221,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); @@ -139,264 +232,209 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of BitRate, which is BitPerSecond. All conversions go via this value. /// - public static BitRateUnit BaseUnit { get; } + public static BitRateUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the BitRate quantity. /// - public static BitRateUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit BitPerSecond. /// - public static BitRate Zero { get; } - - /// - public static BitRate AdditiveIdentity => Zero; + public static BitRate Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public BitRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => BitRate.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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 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 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 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 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 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 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 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 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 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 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 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); #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.ExbibitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.ExbibytePerSecond, 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.GigabitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.GigabytePerSecond, 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.KilobitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.KilobytePerSecond, 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.MegabitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.MegabytePerSecond, 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.PetabitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.PetabytePerSecond, 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.TerabitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.TerabytePerSecond, 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.ExbibitPerSecond, quantity => quantity.ToUnit(BitRateUnit.ExbibitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.ExbibytePerSecond, quantity => quantity.ToUnit(BitRateUnit.ExbibytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.GibibitPerSecond, quantity => quantity.ToUnit(BitRateUnit.GibibitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.GibibytePerSecond, quantity => quantity.ToUnit(BitRateUnit.GibibytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.GigabitPerSecond, quantity => quantity.ToUnit(BitRateUnit.GigabitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.GigabytePerSecond, quantity => quantity.ToUnit(BitRateUnit.GigabytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.KibibitPerSecond, quantity => quantity.ToUnit(BitRateUnit.KibibitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.KibibytePerSecond, quantity => quantity.ToUnit(BitRateUnit.KibibytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.KilobitPerSecond, quantity => quantity.ToUnit(BitRateUnit.KilobitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.KilobytePerSecond, quantity => quantity.ToUnit(BitRateUnit.KilobytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.MebibitPerSecond, quantity => quantity.ToUnit(BitRateUnit.MebibitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.MebibytePerSecond, quantity => quantity.ToUnit(BitRateUnit.MebibytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.MegabitPerSecond, quantity => quantity.ToUnit(BitRateUnit.MegabitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.MegabytePerSecond, quantity => quantity.ToUnit(BitRateUnit.MegabytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.PebibitPerSecond, quantity => quantity.ToUnit(BitRateUnit.PebibitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.PebibytePerSecond, quantity => quantity.ToUnit(BitRateUnit.PebibytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.PetabitPerSecond, quantity => quantity.ToUnit(BitRateUnit.PetabitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.PetabytePerSecond, quantity => quantity.ToUnit(BitRateUnit.PetabytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.TebibitPerSecond, quantity => quantity.ToUnit(BitRateUnit.TebibitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.TebibytePerSecond, quantity => quantity.ToUnit(BitRateUnit.TebibytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.TerabitPerSecond, quantity => quantity.ToUnit(BitRateUnit.TerabitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.TerabytePerSecond, quantity => quantity.ToUnit(BitRateUnit.TerabytePerSecond)); - } - /// /// Get unit abbreviation string. /// @@ -425,7 +463,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); } @@ -433,7 +471,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); } @@ -441,7 +479,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); } @@ -449,7 +487,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); } @@ -457,7 +495,7 @@ public static BitRate FromExabytesPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromExbibitsPerSecond(double value) + public static BitRate FromExbibitsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.ExbibitPerSecond); } @@ -465,7 +503,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); } @@ -473,7 +511,7 @@ public static BitRate FromExbibytesPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromGibibitsPerSecond(double value) + public static BitRate FromGibibitsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.GibibitPerSecond); } @@ -481,7 +519,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); } @@ -489,7 +527,7 @@ public static BitRate FromGibibytesPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromGigabitsPerSecond(double value) + public static BitRate FromGigabitsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.GigabitPerSecond); } @@ -497,7 +535,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); } @@ -505,7 +543,7 @@ public static BitRate FromGigabytesPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromKibibitsPerSecond(double value) + public static BitRate FromKibibitsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.KibibitPerSecond); } @@ -513,7 +551,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); } @@ -521,7 +559,7 @@ public static BitRate FromKibibytesPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromKilobitsPerSecond(double value) + public static BitRate FromKilobitsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.KilobitPerSecond); } @@ -529,7 +567,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); } @@ -537,7 +575,7 @@ public static BitRate FromKilobytesPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromMebibitsPerSecond(double value) + public static BitRate FromMebibitsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.MebibitPerSecond); } @@ -545,7 +583,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); } @@ -553,7 +591,7 @@ public static BitRate FromMebibytesPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromMegabitsPerSecond(double value) + public static BitRate FromMegabitsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.MegabitPerSecond); } @@ -561,7 +599,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); } @@ -569,7 +607,7 @@ public static BitRate FromMegabytesPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromPebibitsPerSecond(double value) + public static BitRate FromPebibitsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.PebibitPerSecond); } @@ -577,7 +615,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); } @@ -585,7 +623,7 @@ public static BitRate FromPebibytesPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromPetabitsPerSecond(double value) + public static BitRate FromPetabitsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.PetabitPerSecond); } @@ -593,7 +631,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); } @@ -601,7 +639,7 @@ public static BitRate FromPetabytesPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromTebibitsPerSecond(double value) + public static BitRate FromTebibitsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.TebibitPerSecond); } @@ -609,7 +647,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); } @@ -617,7 +655,7 @@ public static BitRate FromTebibytesPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromTerabitsPerSecond(double value) + public static BitRate FromTerabitsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.TerabitPerSecond); } @@ -625,7 +663,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); } @@ -636,7 +674,7 @@ public static BitRate FromTerabytesPerSecond(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); } @@ -697,10 +735,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); } /// @@ -728,11 +763,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); } /// @@ -753,7 +784,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")); /// @@ -761,10 +792,10 @@ public static BitRateUnit ParseUnit(string str) /// Error parsing string. public static BitRateUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -779,10 +810,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -798,35 +829,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; } @@ -838,88 +869,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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current BitRate. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(BitRate), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -931,272 +956,24 @@ public int CompareTo(object? obj) /// public int CompareTo(BitRate other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another BitRate within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(BitRate other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is BitRate otherTyped - && (tolerance is BitRate toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'BitRate'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(BitRate other, BitRate tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current BitRate. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(BitRateUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - /// 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); - } + IQuantity IQuantity.ToUnit(BitRateUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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.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.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.GigabitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * 1e9d, BitRateUnit.BitPerSecond), - (BitRateUnit.GigabytePerSecond, 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.KilobitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * 1e3d, BitRateUnit.BitPerSecond), - (BitRateUnit.KilobytePerSecond, 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.MegabitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * 1e6d, BitRateUnit.BitPerSecond), - (BitRateUnit.MegabytePerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8) * 1e6d, 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.PetabitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * 1e15d, BitRateUnit.BitPerSecond), - (BitRateUnit.PetabytePerSecond, 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.TerabitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * 1e12d, BitRateUnit.BitPerSecond), - (BitRateUnit.TerabytePerSecond, 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.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.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.GigabitPerSecond) => new BitRate((_value) / 1e9d, BitRateUnit.GigabitPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.GigabytePerSecond) => new BitRate((_value / 8) / 1e9d, BitRateUnit.GigabytePerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.KibibitPerSecond) => new BitRate((_value) / 1024d, BitRateUnit.KibibitPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.KibibytePerSecond) => new BitRate((_value / 8) / 1024d, BitRateUnit.KibibytePerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.KilobitPerSecond) => new BitRate((_value) / 1e3d, BitRateUnit.KilobitPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.KilobytePerSecond) => new BitRate((_value / 8) / 1e3d, BitRateUnit.KilobytePerSecond), - (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.MegabitPerSecond) => new BitRate((_value) / 1e6d, BitRateUnit.MegabitPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.MegabytePerSecond) => new BitRate((_value / 8) / 1e6d, BitRateUnit.MegabytePerSecond), - (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.PetabitPerSecond) => new BitRate((_value) / 1e15d, BitRateUnit.PetabitPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.PetabytePerSecond) => new BitRate((_value / 8) / 1e15d, BitRateUnit.PetabytePerSecond), - (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.TerabitPerSecond) => new BitRate((_value) / 1e12d, BitRateUnit.TerabitPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.TerabytePerSecond) => new BitRate((_value / 8) / 1e12d, BitRateUnit.TerabytePerSecond), - - _ => 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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(BitRateUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1211,137 +988,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(BitRate)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(BitRate)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(BitRate)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(BitRate)) - return this; - else if (conversionType == typeof(BitRateUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return BitRate.Info; - else if (conversionType == typeof(BaseDimensions)) - return BitRate.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(BitRate)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs b/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs index 3a1c2d2deb..ab71bad1ab 100644 --- a/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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, @@ -52,39 +47,91 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static BrakeSpecificFuelConsumption() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class BrakeSpecificFuelConsumptionInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(-2, 0, 2, 0, 0, 0, 0); - BaseUnit = BrakeSpecificFuelConsumptionUnit.KilogramPerJoule; - Units = Enum.GetValues(typeof(BrakeSpecificFuelConsumptionUnit)).Cast().ToArray(); - Zero = new BrakeSpecificFuelConsumption(0, BaseUnit); - Info = new QuantityInfo("BrakeSpecificFuelConsumption", - new UnitInfo[] - { - new UnitInfo(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour, "GramsPerKiloWattHour", BaseUnits.Undefined, "BrakeSpecificFuelConsumption"), - new UnitInfo(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, "KilogramsPerJoule", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second), "BrakeSpecificFuelConsumption"), - new UnitInfo(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, "PoundsPerMechanicalHorsepowerHour", BaseUnits.Undefined, "BrakeSpecificFuelConsumption"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public BrakeSpecificFuelConsumptionInfo(string name, BrakeSpecificFuelConsumptionUnit baseUnit, IEnumerable> unitMappings, BrakeSpecificFuelConsumption zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public BrakeSpecificFuelConsumptionInfo(string name, BrakeSpecificFuelConsumptionUnit baseUnit, IEnumerable> unitMappings, BrakeSpecificFuelConsumption zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, BrakeSpecificFuelConsumption.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.BrakeSpecificFuelConsumption", typeof(BrakeSpecificFuelConsumption).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the BrakeSpecificFuelConsumption quantity. + /// + /// A new instance of the class with the default settings. + public static BrakeSpecificFuelConsumptionInfo CreateDefault() + { + return new BrakeSpecificFuelConsumptionInfo(nameof(BrakeSpecificFuelConsumption), DefaultBaseUnit, GetDefaultMappings(), new BrakeSpecificFuelConsumption(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the BrakeSpecificFuelConsumption quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static BrakeSpecificFuelConsumptionInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new BrakeSpecificFuelConsumptionInfo(nameof(BrakeSpecificFuelConsumption), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new BrakeSpecificFuelConsumption(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^2L^-2. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, 0, 2, 0, 0, 0, 0); + + /// + /// The default base unit of BrakeSpecificFuelConsumption is KilogramPerJoule. All conversions, as defined in the , go via this value. + /// + public static BrakeSpecificFuelConsumptionUnit DefaultBaseUnit { get; } = BrakeSpecificFuelConsumptionUnit.KilogramPerJoule; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for BrakeSpecificFuelConsumption. + public static IEnumerable> GetDefaultMappings() + { + 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, + new QuantityValue(191751395532579, 32399455) + ); + } + } + + static BrakeSpecificFuelConsumption() + { + Info = UnitsNetSetup.CreateQuantityInfo(BrakeSpecificFuelConsumptionInfo.CreateDefault); } /// @@ -92,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; @@ -106,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); @@ -117,103 +164,94 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of BrakeSpecificFuelConsumption, which is KilogramPerJoule. All conversions go via this value. /// - public static BrakeSpecificFuelConsumptionUnit BaseUnit { get; } + public static BrakeSpecificFuelConsumptionUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the BrakeSpecificFuelConsumption quantity. /// - public static BrakeSpecificFuelConsumptionUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerJoule. /// - public static BrakeSpecificFuelConsumption Zero { get; } - - /// - public static BrakeSpecificFuelConsumption AdditiveIdentity => Zero; + public static BrakeSpecificFuelConsumption Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public BrakeSpecificFuelConsumptionUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => BrakeSpecificFuelConsumption.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -242,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); } @@ -250,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); } @@ -258,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); } @@ -269,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); } @@ -330,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); } /// @@ -361,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); } /// @@ -386,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")); /// @@ -394,10 +425,10 @@ public static BrakeSpecificFuelConsumptionUnit ParseUnit(string str) /// Error parsing string. public static BrakeSpecificFuelConsumptionUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -412,10 +443,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -431,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; } @@ -474,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; } @@ -493,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current BrakeSpecificFuelConsumption. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(BrakeSpecificFuelConsumption), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -586,226 +611,24 @@ public int CompareTo(object? obj) /// public int CompareTo(BrakeSpecificFuelConsumption other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another BrakeSpecificFuelConsumption within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(BrakeSpecificFuelConsumption other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is BrakeSpecificFuelConsumption otherTyped - && (tolerance is BrakeSpecificFuelConsumption toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'BrakeSpecificFuelConsumption'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(BrakeSpecificFuelConsumption other, BrakeSpecificFuelConsumption tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current BrakeSpecificFuelConsumption. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(BrakeSpecificFuelConsumptionUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(BrakeSpecificFuelConsumptionUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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), - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -820,137 +643,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(BrakeSpecificFuelConsumption)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(BrakeSpecificFuelConsumption)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(BrakeSpecificFuelConsumption)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(BrakeSpecificFuelConsumption)) - return this; - else if (conversionType == typeof(BrakeSpecificFuelConsumptionUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return BrakeSpecificFuelConsumption.Info; - else if (conversionType == typeof(BaseDimensions)) - return BrakeSpecificFuelConsumption.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(BrakeSpecificFuelConsumption)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs b/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs index ac827c70b0..65becc09e7 100644 --- a/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -51,42 +46,100 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static CoefficientOfThermalExpansion() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class CoefficientOfThermalExpansionInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(0, 0, 0, 0, -1, 0, 0); - BaseUnit = CoefficientOfThermalExpansionUnit.PerKelvin; - Units = Enum.GetValues(typeof(CoefficientOfThermalExpansionUnit)).Cast().ToArray(); - Zero = new CoefficientOfThermalExpansion(0, BaseUnit); - Info = new QuantityInfo("CoefficientOfThermalExpansion", - new UnitInfo[] - { - new UnitInfo(CoefficientOfThermalExpansionUnit.PerDegreeCelsius, "PerDegreeCelsius", new BaseUnits(temperature: TemperatureUnit.DegreeCelsius), "CoefficientOfThermalExpansion"), - new UnitInfo(CoefficientOfThermalExpansionUnit.PerDegreeFahrenheit, "PerDegreeFahrenheit", new BaseUnits(temperature: TemperatureUnit.DegreeFahrenheit), "CoefficientOfThermalExpansion"), - new UnitInfo(CoefficientOfThermalExpansionUnit.PerKelvin, "PerKelvin", new BaseUnits(temperature: TemperatureUnit.Kelvin), "CoefficientOfThermalExpansion"), - new UnitInfo(CoefficientOfThermalExpansionUnit.PpmPerDegreeCelsius, "PpmPerDegreeCelsius", BaseUnits.Undefined, "CoefficientOfThermalExpansion"), - new UnitInfo(CoefficientOfThermalExpansionUnit.PpmPerDegreeFahrenheit, "PpmPerDegreeFahrenheit", BaseUnits.Undefined, "CoefficientOfThermalExpansion"), - new UnitInfo(CoefficientOfThermalExpansionUnit.PpmPerKelvin, "PpmPerKelvin", BaseUnits.Undefined, "CoefficientOfThermalExpansion"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public CoefficientOfThermalExpansionInfo(string name, CoefficientOfThermalExpansionUnit baseUnit, IEnumerable> unitMappings, CoefficientOfThermalExpansion zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public CoefficientOfThermalExpansionInfo(string name, CoefficientOfThermalExpansionUnit baseUnit, IEnumerable> unitMappings, CoefficientOfThermalExpansion zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, CoefficientOfThermalExpansion.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.CoefficientOfThermalExpansion", typeof(CoefficientOfThermalExpansion).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the CoefficientOfThermalExpansion quantity. + /// + /// A new instance of the class with the default settings. + public static CoefficientOfThermalExpansionInfo CreateDefault() + { + return new CoefficientOfThermalExpansionInfo(nameof(CoefficientOfThermalExpansion), DefaultBaseUnit, GetDefaultMappings(), new CoefficientOfThermalExpansion(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the CoefficientOfThermalExpansion quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static CoefficientOfThermalExpansionInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new CoefficientOfThermalExpansionInfo(nameof(CoefficientOfThermalExpansion), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new CoefficientOfThermalExpansion(0, DefaultBaseUnit), DefaultBaseDimensions); + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// The for is Θ^-1. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, 0, 0, -1, 0, 0); + + /// + /// The default base unit of CoefficientOfThermalExpansion is PerKelvin. All conversions, as defined in the , go via this value. + /// + public static CoefficientOfThermalExpansionUnit DefaultBaseUnit { get; } = CoefficientOfThermalExpansionUnit.PerKelvin; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for CoefficientOfThermalExpansion. + public static IEnumerable> GetDefaultMappings() + { + 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, + 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 = UnitsNetSetup.CreateQuantityInfo(CoefficientOfThermalExpansionInfo.CreateDefault); } /// @@ -94,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; @@ -108,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); @@ -119,124 +172,109 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of CoefficientOfThermalExpansion, which is PerKelvin. All conversions go via this value. /// - public static CoefficientOfThermalExpansionUnit BaseUnit { get; } + public static CoefficientOfThermalExpansionUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the CoefficientOfThermalExpansion quantity. /// - public static CoefficientOfThermalExpansionUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit PerKelvin. /// - public static CoefficientOfThermalExpansion Zero { get; } - - /// - public static CoefficientOfThermalExpansion AdditiveIdentity => Zero; + public static CoefficientOfThermalExpansion Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public CoefficientOfThermalExpansionUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => CoefficientOfThermalExpansion.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -265,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); } @@ -273,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); } @@ -281,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); } @@ -289,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); } @@ -297,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); } @@ -305,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); } @@ -316,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); } @@ -377,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); } /// @@ -408,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); } /// @@ -433,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")); /// @@ -441,10 +472,10 @@ public static CoefficientOfThermalExpansionUnit ParseUnit(string str) /// Error parsing string. public static CoefficientOfThermalExpansionUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -459,10 +490,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -478,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; } @@ -528,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current CoefficientOfThermalExpansion. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(CoefficientOfThermalExpansion), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -621,232 +646,24 @@ public int CompareTo(object? obj) /// public int CompareTo(CoefficientOfThermalExpansion other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another CoefficientOfThermalExpansion within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(CoefficientOfThermalExpansion other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is CoefficientOfThermalExpansion otherTyped - && (tolerance is CoefficientOfThermalExpansion toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'CoefficientOfThermalExpansion'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(CoefficientOfThermalExpansion other, CoefficientOfThermalExpansion tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current CoefficientOfThermalExpansion. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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)); + #region Conversion Methods (explicit implementations for netstandard2.0) - 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 CoefficientOfThermalExpansionUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(CoefficientOfThermalExpansionUnit)} 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(CoefficientOfThermalExpansionUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(CoefficientOfThermalExpansionUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -861,137 +678,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(CoefficientOfThermalExpansion)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(CoefficientOfThermalExpansion)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(CoefficientOfThermalExpansion)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(CoefficientOfThermalExpansion)) - return this; - else if (conversionType == typeof(CoefficientOfThermalExpansionUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return CoefficientOfThermalExpansion.Info; - else if (conversionType == typeof(BaseDimensions)) - return CoefficientOfThermalExpansion.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(CoefficientOfThermalExpansion)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Compressibility.g.cs b/UnitsNet/GeneratedCode/Quantities/Compressibility.g.cs index 4c83b57d46..12fe8f76e3 100644 --- a/UnitsNet/GeneratedCode/Quantities/Compressibility.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Compressibility.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -48,43 +43,103 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static Compressibility() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class CompressibilityInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(1, -1, 2, 0, 0, 0, 0); - BaseUnit = CompressibilityUnit.InversePascal; - Units = Enum.GetValues(typeof(CompressibilityUnit)).Cast().ToArray(); - Zero = new Compressibility(0, BaseUnit); - Info = new QuantityInfo("Compressibility", - new UnitInfo[] - { - new UnitInfo(CompressibilityUnit.InverseAtmosphere, "InverseAtmospheres", BaseUnits.Undefined, "Compressibility"), - new UnitInfo(CompressibilityUnit.InverseBar, "InverseBars", BaseUnits.Undefined, "Compressibility"), - new UnitInfo(CompressibilityUnit.InverseKilopascal, "InverseKilopascals", BaseUnits.Undefined, "Compressibility"), - new UnitInfo(CompressibilityUnit.InverseMegapascal, "InverseMegapascals", BaseUnits.Undefined, "Compressibility"), - new UnitInfo(CompressibilityUnit.InverseMillibar, "InverseMillibars", BaseUnits.Undefined, "Compressibility"), - new UnitInfo(CompressibilityUnit.InversePascal, "InversePascals", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Compressibility"), - new UnitInfo(CompressibilityUnit.InversePoundForcePerSquareInch, "InversePoundsForcePerSquareInch", BaseUnits.Undefined, "Compressibility"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public CompressibilityInfo(string name, CompressibilityUnit baseUnit, IEnumerable> unitMappings, Compressibility zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public CompressibilityInfo(string name, CompressibilityUnit baseUnit, IEnumerable> unitMappings, Compressibility zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Compressibility.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Compressibility", typeof(Compressibility).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Compressibility quantity. + /// + /// A new instance of the class with the default settings. + public static CompressibilityInfo CreateDefault() + { + return new CompressibilityInfo(nameof(Compressibility), DefaultBaseUnit, GetDefaultMappings(), new Compressibility(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Compressibility quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static CompressibilityInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new CompressibilityInfo(nameof(Compressibility), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Compressibility(0, DefaultBaseUnit), DefaultBaseDimensions); + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// The for is T^2LM^-1. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, -1, 2, 0, 0, 0, 0); + + /// + /// The default base unit of Compressibility is InversePascal. All conversions, as defined in the , go via this value. + /// + public static CompressibilityUnit DefaultBaseUnit { get; } = CompressibilityUnit.InversePascal; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Compressibility. + public static IEnumerable> GetDefaultMappings() + { + 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, + new QuantityValue(1000000000000, 6894757293168361) + ); + } + } + + static Compressibility() + { + Info = UnitsNetSetup.CreateQuantityInfo(CompressibilityInfo.CreateDefault); } /// @@ -92,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; @@ -106,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); @@ -117,131 +172,114 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Compressibility, which is InversePascal. All conversions go via this value. /// - public static CompressibilityUnit BaseUnit { get; } + public static CompressibilityUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Compressibility quantity. /// - public static CompressibilityUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit InversePascal. /// - public static Compressibility Zero { get; } - - /// - public static Compressibility AdditiveIdentity => Zero; + public static Compressibility Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public CompressibilityUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Compressibility.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -270,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); } @@ -278,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); } @@ -286,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); } @@ -294,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); } @@ -302,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); } @@ -310,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); } @@ -318,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); } @@ -329,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); } @@ -390,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); } /// @@ -421,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); } /// @@ -446,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")); /// @@ -454,10 +485,10 @@ public static CompressibilityUnit ParseUnit(string str) /// Error parsing string. public static CompressibilityUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -472,10 +503,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -491,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; } @@ -531,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Compressibility. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Compressibility), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -624,234 +649,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Compressibility other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Compressibility within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Compressibility other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Compressibility otherTyped - && (tolerance is Compressibility toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Compressibility'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Compressibility other, Compressibility tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Compressibility. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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)); + #region Conversion Methods (explicit implementations for netstandard2.0) - 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 CompressibilityUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(CompressibilityUnit)} 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(CompressibilityUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(CompressibilityUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -866,137 +681,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Compressibility)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Compressibility)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Compressibility)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Compressibility)) - return this; - else if (conversionType == typeof(CompressibilityUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Compressibility.Info; - else if (conversionType == typeof(BaseDimensions)) - return Compressibility.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Compressibility)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Density.g.cs b/UnitsNet/GeneratedCode/Quantities/Density.g.cs index 10d87c4116..3c5a93b1aa 100644 --- a/UnitsNet/GeneratedCode/Quantities/Density.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Density.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -60,92 +55,250 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class DensityInfo: QuantityInfo + { + /// + public DensityInfo(string name, DensityUnit baseUnit, IEnumerable> unitMappings, Density zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public DensityInfo(string name, DensityUnit baseUnit, IEnumerable> unitMappings, Density zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Density.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Density", typeof(Density).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Density quantity. + /// + /// A new instance of the class with the default settings. + public static DensityInfo CreateDefault() + { + return new DensityInfo(nameof(Density), DefaultBaseUnit, GetDefaultMappings(), new Density(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Density quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static DensityInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new DensityInfo(nameof(Density), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Density(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is L^-3M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-3, 1, 0, 0, 0, 0, 0); + + /// + /// The default base unit of Density is KilogramPerCubicMeter. All conversions, as defined in the , go via this value. + /// + public static DensityUnit DefaultBaseUnit { get; } = DensityUnit.KilogramPerCubicMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Density. + public static IEnumerable> GetDefaultMappings() + { + 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), + 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() { - BaseDimensions = new BaseDimensions(-3, 1, 0, 0, 0, 0, 0); - BaseUnit = DensityUnit.KilogramPerCubicMeter; - Units = Enum.GetValues(typeof(DensityUnit)).Cast().ToArray(); - Zero = new Density(0, BaseUnit); - Info = new QuantityInfo("Density", - new UnitInfo[] - { - new UnitInfo(DensityUnit.CentigramPerDeciliter, "CentigramsPerDeciliter", BaseUnits.Undefined, "Density"), - new UnitInfo(DensityUnit.CentigramPerLiter, "CentigramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Centigram), "Density"), - new UnitInfo(DensityUnit.CentigramPerMilliliter, "CentigramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Centigram), "Density"), - new UnitInfo(DensityUnit.DecigramPerDeciliter, "DecigramsPerDeciliter", BaseUnits.Undefined, "Density"), - new UnitInfo(DensityUnit.DecigramPerLiter, "DecigramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Decigram), "Density"), - new UnitInfo(DensityUnit.DecigramPerMilliliter, "DecigramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Decigram), "Density"), - new UnitInfo(DensityUnit.FemtogramPerDeciliter, "FemtogramsPerDeciliter", BaseUnits.Undefined, "Density"), - new UnitInfo(DensityUnit.FemtogramPerLiter, "FemtogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Femtogram), "Density"), - new UnitInfo(DensityUnit.FemtogramPerMilliliter, "FemtogramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Femtogram), "Density"), - new UnitInfo(DensityUnit.GramPerCubicCentimeter, "GramsPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram), "Density"), - new UnitInfo(DensityUnit.GramPerCubicFoot, "GramsPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Gram), "Density"), - new UnitInfo(DensityUnit.GramPerCubicInch, "GramsPerCubicInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Gram), "Density"), - new UnitInfo(DensityUnit.GramPerCubicMeter, "GramsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram), "Density"), - new UnitInfo(DensityUnit.GramPerCubicMillimeter, "GramsPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Gram), "Density"), - new UnitInfo(DensityUnit.GramPerDeciliter, "GramsPerDeciliter", BaseUnits.Undefined, "Density"), - new UnitInfo(DensityUnit.GramPerLiter, "GramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Gram), "Density"), - new UnitInfo(DensityUnit.GramPerMilliliter, "GramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram), "Density"), - new UnitInfo(DensityUnit.KilogramPerCubicCentimeter, "KilogramsPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilogram), "Density"), - new UnitInfo(DensityUnit.KilogramPerCubicMeter, "KilogramsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram), "Density"), - new UnitInfo(DensityUnit.KilogramPerCubicMillimeter, "KilogramsPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram), "Density"), - new UnitInfo(DensityUnit.KilogramPerLiter, "KilogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilogram), "Density"), - new UnitInfo(DensityUnit.KilopoundPerCubicFoot, "KilopoundsPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Kilopound), "Density"), - new UnitInfo(DensityUnit.KilopoundPerCubicInch, "KilopoundsPerCubicInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Kilopound), "Density"), - new UnitInfo(DensityUnit.KilopoundPerCubicYard, "KilopoundsPerCubicYard", new BaseUnits(length: LengthUnit.Yard, mass: MassUnit.Kilopound), "Density"), - new UnitInfo(DensityUnit.MicrogramPerCubicMeter, "MicrogramsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram), "Density"), - new UnitInfo(DensityUnit.MicrogramPerDeciliter, "MicrogramsPerDeciliter", BaseUnits.Undefined, "Density"), - new UnitInfo(DensityUnit.MicrogramPerLiter, "MicrogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Microgram), "Density"), - new UnitInfo(DensityUnit.MicrogramPerMilliliter, "MicrogramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Microgram), "Density"), - new UnitInfo(DensityUnit.MilligramPerCubicMeter, "MilligramsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram), "Density"), - new UnitInfo(DensityUnit.MilligramPerDeciliter, "MilligramsPerDeciliter", BaseUnits.Undefined, "Density"), - new UnitInfo(DensityUnit.MilligramPerLiter, "MilligramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Milligram), "Density"), - new UnitInfo(DensityUnit.MilligramPerMilliliter, "MilligramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Milligram), "Density"), - new UnitInfo(DensityUnit.NanogramPerDeciliter, "NanogramsPerDeciliter", BaseUnits.Undefined, "Density"), - new UnitInfo(DensityUnit.NanogramPerLiter, "NanogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Nanogram), "Density"), - new UnitInfo(DensityUnit.NanogramPerMilliliter, "NanogramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Nanogram), "Density"), - new UnitInfo(DensityUnit.PicogramPerDeciliter, "PicogramsPerDeciliter", BaseUnits.Undefined, "Density"), - new UnitInfo(DensityUnit.PicogramPerLiter, "PicogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Picogram), "Density"), - new UnitInfo(DensityUnit.PicogramPerMilliliter, "PicogramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Picogram), "Density"), - new UnitInfo(DensityUnit.PoundPerCubicCentimeter, "PoundsPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Pound), "Density"), - new UnitInfo(DensityUnit.PoundPerCubicFoot, "PoundsPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Pound), "Density"), - new UnitInfo(DensityUnit.PoundPerCubicInch, "PoundsPerCubicInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Pound), "Density"), - new UnitInfo(DensityUnit.PoundPerCubicMeter, "PoundsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Pound), "Density"), - new UnitInfo(DensityUnit.PoundPerCubicMillimeter, "PoundsPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Pound), "Density"), - new UnitInfo(DensityUnit.PoundPerCubicYard, "PoundsPerCubicYard", new BaseUnits(length: LengthUnit.Yard, mass: MassUnit.Pound), "Density"), - new UnitInfo(DensityUnit.PoundPerImperialGallon, "PoundsPerImperialGallon", BaseUnits.Undefined, "Density"), - new UnitInfo(DensityUnit.PoundPerUSGallon, "PoundsPerUSGallon", BaseUnits.Undefined, "Density"), - new UnitInfo(DensityUnit.SlugPerCubicCentimeter, "SlugsPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Slug), "Density"), - new UnitInfo(DensityUnit.SlugPerCubicFoot, "SlugsPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Slug), "Density"), - new UnitInfo(DensityUnit.SlugPerCubicInch, "SlugsPerCubicInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Slug), "Density"), - new UnitInfo(DensityUnit.SlugPerCubicMeter, "SlugsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Slug), "Density"), - new UnitInfo(DensityUnit.SlugPerCubicMillimeter, "SlugsPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Slug), "Density"), - new UnitInfo(DensityUnit.TonnePerCubicCentimeter, "TonnesPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Tonne), "Density"), - new UnitInfo(DensityUnit.TonnePerCubicFoot, "TonnesPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Tonne), "Density"), - new UnitInfo(DensityUnit.TonnePerCubicInch, "TonnesPerCubicInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Tonne), "Density"), - new UnitInfo(DensityUnit.TonnePerCubicMeter, "TonnesPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Tonne), "Density"), - new UnitInfo(DensityUnit.TonnePerCubicMillimeter, "TonnesPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Tonne), "Density"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(DensityInfo.CreateDefault); } /// @@ -153,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; @@ -167,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); @@ -178,474 +331,359 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Density, which is KilogramPerCubicMeter. All conversions go via this value. /// - public static DensityUnit BaseUnit { get; } + public static DensityUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Density quantity. /// - public static DensityUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerCubicMeter. /// - public static Density Zero { get; } - - /// - public static Density AdditiveIdentity => Zero; + public static Density Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public DensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Density.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -674,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); } @@ -682,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); } @@ -690,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); } @@ -698,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); } @@ -706,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); } @@ -714,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); } @@ -722,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); } @@ -730,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); } @@ -738,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); } @@ -746,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); } @@ -754,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); } @@ -762,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); } @@ -770,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); } @@ -778,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); } @@ -786,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); } @@ -794,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); } @@ -802,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); } @@ -810,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); } @@ -818,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); } @@ -826,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); } @@ -834,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); } @@ -842,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); } @@ -850,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); } @@ -858,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); } @@ -866,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); } @@ -874,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); } @@ -882,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); } @@ -890,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); } @@ -898,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); } @@ -906,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); } @@ -914,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); } @@ -922,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); } @@ -930,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); } @@ -938,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); } @@ -946,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); } @@ -954,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); } @@ -962,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); } @@ -970,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); } @@ -978,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); } @@ -986,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); } @@ -994,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); } @@ -1002,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); } @@ -1010,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); } @@ -1018,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); } @@ -1026,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); } @@ -1034,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); } @@ -1042,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); } @@ -1050,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); } @@ -1058,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); } @@ -1066,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); } @@ -1074,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); } @@ -1082,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); } @@ -1090,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); } @@ -1098,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); } @@ -1106,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); } @@ -1114,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); } @@ -1125,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); } @@ -1186,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); } /// @@ -1217,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); } /// @@ -1242,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")); /// @@ -1250,10 +1281,10 @@ public static DensityUnit ParseUnit(string str) /// Error parsing string. public static DensityUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -1268,10 +1299,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -1287,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; } @@ -1328,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 * . @@ -1380,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Density. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Density), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -1473,332 +1498,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Density other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Density within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Density other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Density otherTyped - && (tolerance is Density toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Density'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Density other, Density tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Density. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(DensityUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - /// 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 NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } + IQuantity IQuantity.ToUnit(DensityUnit unit) => this.ToUnit(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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(DensityUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1813,137 +1530,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Density)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Density)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Density)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Density)) - return this; - else if (conversionType == typeof(DensityUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Density.Info; - else if (conversionType == typeof(BaseDimensions)) - return Density.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Density)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/DoseAreaProduct.g.cs b/UnitsNet/GeneratedCode/Quantities/DoseAreaProduct.g.cs index abeb8f0ed7..c6e6dc10dc 100644 --- a/UnitsNet/GeneratedCode/Quantities/DoseAreaProduct.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/DoseAreaProduct.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,56 +46,142 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class DoseAreaProductInfo: QuantityInfo + { + /// + public DoseAreaProductInfo(string name, DoseAreaProductUnit baseUnit, IEnumerable> unitMappings, DoseAreaProduct zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public DoseAreaProductInfo(string name, DoseAreaProductUnit baseUnit, IEnumerable> unitMappings, DoseAreaProduct zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, DoseAreaProduct.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.DoseAreaProduct", typeof(DoseAreaProduct).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the DoseAreaProduct quantity. + /// + /// A new instance of the class with the default settings. + public static DoseAreaProductInfo CreateDefault() + { + return new DoseAreaProductInfo(nameof(DoseAreaProduct), DefaultBaseUnit, GetDefaultMappings(), new DoseAreaProduct(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the DoseAreaProduct quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static DoseAreaProductInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new DoseAreaProductInfo(nameof(DoseAreaProduct), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new DoseAreaProduct(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-2L^4. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(4, 0, -2, 0, 0, 0, 0); + + /// + /// The default base unit of DoseAreaProduct is GraySquareMeter. All conversions, as defined in the , go via this value. + /// + public static DoseAreaProductUnit DefaultBaseUnit { get; } = DoseAreaProductUnit.GraySquareMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for DoseAreaProduct. + public static IEnumerable> GetDefaultMappings() + { + 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.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.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.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.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.MilligraySquareMillimeter, "MilligraySquareMillimeter", "MilligraySquareMillimeters", BaseUnits.Undefined, + 1000000000 + ); + } + } + static DoseAreaProduct() { - BaseDimensions = new BaseDimensions(4, 0, -2, 0, 0, 0, 0); - BaseUnit = DoseAreaProductUnit.GraySquareMeter; - Units = Enum.GetValues(typeof(DoseAreaProductUnit)).Cast().ToArray(); - Zero = new DoseAreaProduct(0, BaseUnit); - Info = new QuantityInfo("DoseAreaProduct", - new UnitInfo[] - { - new UnitInfo(DoseAreaProductUnit.CentigraySquareCentimeter, "CentigraySquareCentimeters", BaseUnits.Undefined, "DoseAreaProduct"), - new UnitInfo(DoseAreaProductUnit.CentigraySquareDecimeter, "CentigraySquareDecimeters", BaseUnits.Undefined, "DoseAreaProduct"), - new UnitInfo(DoseAreaProductUnit.CentigraySquareMeter, "CentigraySquareMeters", BaseUnits.Undefined, "DoseAreaProduct"), - new UnitInfo(DoseAreaProductUnit.CentigraySquareMillimeter, "CentigraySquareMillimeters", BaseUnits.Undefined, "DoseAreaProduct"), - new UnitInfo(DoseAreaProductUnit.DecigraySquareCentimeter, "DecigraySquareCentimeters", BaseUnits.Undefined, "DoseAreaProduct"), - new UnitInfo(DoseAreaProductUnit.DecigraySquareDecimeter, "DecigraySquareDecimeters", BaseUnits.Undefined, "DoseAreaProduct"), - new UnitInfo(DoseAreaProductUnit.DecigraySquareMeter, "DecigraySquareMeters", BaseUnits.Undefined, "DoseAreaProduct"), - new UnitInfo(DoseAreaProductUnit.DecigraySquareMillimeter, "DecigraySquareMillimeters", BaseUnits.Undefined, "DoseAreaProduct"), - new UnitInfo(DoseAreaProductUnit.GraySquareCentimeter, "GraySquareCentimeters", BaseUnits.Undefined, "DoseAreaProduct"), - new UnitInfo(DoseAreaProductUnit.GraySquareDecimeter, "GraySquareDecimeters", BaseUnits.Undefined, "DoseAreaProduct"), - new UnitInfo(DoseAreaProductUnit.GraySquareMeter, "GraySquareMeters", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second), "DoseAreaProduct"), - new UnitInfo(DoseAreaProductUnit.GraySquareMillimeter, "GraySquareMillimeters", BaseUnits.Undefined, "DoseAreaProduct"), - new UnitInfo(DoseAreaProductUnit.MicrograySquareCentimeter, "MicrograySquareCentimeters", BaseUnits.Undefined, "DoseAreaProduct"), - new UnitInfo(DoseAreaProductUnit.MicrograySquareDecimeter, "MicrograySquareDecimeters", BaseUnits.Undefined, "DoseAreaProduct"), - new UnitInfo(DoseAreaProductUnit.MicrograySquareMeter, "MicrograySquareMeters", BaseUnits.Undefined, "DoseAreaProduct"), - new UnitInfo(DoseAreaProductUnit.MicrograySquareMillimeter, "MicrograySquareMillimeters", BaseUnits.Undefined, "DoseAreaProduct"), - new UnitInfo(DoseAreaProductUnit.MilligraySquareCentimeter, "MilligraySquareCentimeters", BaseUnits.Undefined, "DoseAreaProduct"), - new UnitInfo(DoseAreaProductUnit.MilligraySquareDecimeter, "MilligraySquareDecimeters", BaseUnits.Undefined, "DoseAreaProduct"), - new UnitInfo(DoseAreaProductUnit.MilligraySquareMeter, "MilligraySquareMeters", BaseUnits.Undefined, "DoseAreaProduct"), - new UnitInfo(DoseAreaProductUnit.MilligraySquareMillimeter, "MilligraySquareMillimeters", BaseUnits.Undefined, "DoseAreaProduct"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(DoseAreaProductInfo.CreateDefault); } /// @@ -108,7 +189,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; @@ -122,7 +203,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); @@ -133,222 +214,179 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of DoseAreaProduct, which is GraySquareMeter. All conversions go via this value. /// - public static DoseAreaProductUnit BaseUnit { get; } + public static DoseAreaProductUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the DoseAreaProduct quantity. /// - public static DoseAreaProductUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit GraySquareMeter. /// - public static DoseAreaProduct Zero { get; } - - /// - public static DoseAreaProduct AdditiveIdentity => Zero; + public static DoseAreaProduct Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public DoseAreaProductUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => DoseAreaProduct.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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 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 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 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 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 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.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.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.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.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.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.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.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.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.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.MilligraySquareMillimeter, quantity => quantity.ToUnit(DoseAreaProductUnit.MilligraySquareMillimeter)); - } - /// /// Get unit abbreviation string. /// @@ -377,7 +415,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); } @@ -385,7 +423,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); } @@ -393,7 +431,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); } @@ -401,7 +439,7 @@ public static DoseAreaProduct FromCentigraySquareMeters(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromCentigraySquareMillimeters(double value) + public static DoseAreaProduct FromCentigraySquareMillimeters(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.CentigraySquareMillimeter); } @@ -409,7 +447,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); } @@ -417,7 +455,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); } @@ -425,7 +463,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); } @@ -433,7 +471,7 @@ public static DoseAreaProduct FromDecigraySquareMeters(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromDecigraySquareMillimeters(double value) + public static DoseAreaProduct FromDecigraySquareMillimeters(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.DecigraySquareMillimeter); } @@ -441,7 +479,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); } @@ -449,7 +487,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); } @@ -457,7 +495,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); } @@ -465,7 +503,7 @@ public static DoseAreaProduct FromGraySquareMeters(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromGraySquareMillimeters(double value) + public static DoseAreaProduct FromGraySquareMillimeters(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.GraySquareMillimeter); } @@ -473,7 +511,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); } @@ -481,7 +519,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); } @@ -489,7 +527,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); } @@ -497,7 +535,7 @@ public static DoseAreaProduct FromMicrograySquareMeters(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromMicrograySquareMillimeters(double value) + public static DoseAreaProduct FromMicrograySquareMillimeters(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.MicrograySquareMillimeter); } @@ -505,7 +543,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); } @@ -513,7 +551,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); } @@ -521,7 +559,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); } @@ -529,7 +567,7 @@ public static DoseAreaProduct FromMilligraySquareMeters(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromMilligraySquareMillimeters(double value) + public static DoseAreaProduct FromMilligraySquareMillimeters(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.MilligraySquareMillimeter); } @@ -540,7 +578,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); } @@ -601,10 +639,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); } /// @@ -632,11 +667,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); } /// @@ -657,7 +688,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")); /// @@ -665,10 +696,10 @@ public static DoseAreaProductUnit ParseUnit(string str) /// Error parsing string. public static DoseAreaProductUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -683,10 +714,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -702,35 +733,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; } @@ -742,88 +773,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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current DoseAreaProduct. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(DoseAreaProduct), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -835,260 +860,24 @@ public int CompareTo(object? obj) /// public int CompareTo(DoseAreaProduct other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another DoseAreaProduct within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(DoseAreaProduct other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is DoseAreaProduct otherTyped - && (tolerance is DoseAreaProduct toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'DoseAreaProduct'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(DoseAreaProduct other, DoseAreaProduct tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current DoseAreaProduct. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(DoseAreaProductUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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.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.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.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.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.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.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.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.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.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.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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(DoseAreaProductUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1103,137 +892,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(DoseAreaProduct)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(DoseAreaProduct)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(DoseAreaProduct)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(DoseAreaProduct)) - return this; - else if (conversionType == typeof(DoseAreaProductUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return DoseAreaProduct.Info; - else if (conversionType == typeof(BaseDimensions)) - return DoseAreaProduct.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(DoseAreaProduct)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Duration.g.cs b/UnitsNet/GeneratedCode/Quantities/Duration.g.cs index 56545f36f8..2ee66abb17 100644 --- a/UnitsNet/GeneratedCode/Quantities/Duration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Duration.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -65,48 +60,118 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class DurationInfo: QuantityInfo + { + /// + public DurationInfo(string name, DurationUnit baseUnit, IEnumerable> unitMappings, Duration zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public DurationInfo(string name, DurationUnit baseUnit, IEnumerable> unitMappings, Duration zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Duration.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Duration", typeof(Duration).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Duration quantity. + /// + /// A new instance of the class with the default settings. + public static DurationInfo CreateDefault() + { + return new DurationInfo(nameof(Duration), DefaultBaseUnit, GetDefaultMappings(), new Duration(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Duration quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static DurationInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new DurationInfo(nameof(Duration), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Duration(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, 1, 0, 0, 0, 0); + + /// + /// The default base unit of Duration is Second. All conversions, as defined in the , go via this value. + /// + public static DurationUnit DefaultBaseUnit { get; } = DurationUnit.Second; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Duration. + public static IEnumerable> GetDefaultMappings() + { + 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.Second, "Second", "Seconds", new BaseUnits(time: DurationUnit.Second)); + 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() { - BaseDimensions = new BaseDimensions(0, 0, 1, 0, 0, 0, 0); - BaseUnit = DurationUnit.Second; - Units = Enum.GetValues(typeof(DurationUnit)).Cast().ToArray(); - Zero = new Duration(0, BaseUnit); - Info = new QuantityInfo("Duration", - new UnitInfo[] - { - new UnitInfo(DurationUnit.Day, "Days", new BaseUnits(time: DurationUnit.Day), "Duration"), - new UnitInfo(DurationUnit.Hour, "Hours", new BaseUnits(time: DurationUnit.Hour), "Duration"), - new UnitInfo(DurationUnit.JulianYear, "JulianYears", new BaseUnits(time: DurationUnit.JulianYear), "Duration"), - new UnitInfo(DurationUnit.Microsecond, "Microseconds", new BaseUnits(time: DurationUnit.Microsecond), "Duration"), - new UnitInfo(DurationUnit.Millisecond, "Milliseconds", new BaseUnits(time: DurationUnit.Millisecond), "Duration"), - new UnitInfo(DurationUnit.Minute, "Minutes", new BaseUnits(time: DurationUnit.Minute), "Duration"), - new UnitInfo(DurationUnit.Month30, "Months30", new BaseUnits(time: DurationUnit.Month30), "Duration"), - new UnitInfo(DurationUnit.Nanosecond, "Nanoseconds", new BaseUnits(time: DurationUnit.Nanosecond), "Duration"), - new UnitInfo(DurationUnit.Second, "Seconds", new BaseUnits(time: DurationUnit.Second), "Duration"), - new UnitInfo(DurationUnit.Sol, "Sols", new BaseUnits(time: DurationUnit.Sol), "Duration"), - new UnitInfo(DurationUnit.Week, "Weeks", new BaseUnits(time: DurationUnit.Week), "Duration"), - new UnitInfo(DurationUnit.Year365, "Years365", new BaseUnits(time: DurationUnit.Year365), "Duration"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(DurationInfo.CreateDefault); } /// @@ -114,7 +179,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; @@ -128,7 +193,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); @@ -139,166 +204,139 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Duration, which is Second. All conversions go via this value. /// - public static DurationUnit BaseUnit { get; } + public static DurationUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Duration quantity. /// - public static DurationUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Second. /// - public static Duration Zero { get; } - - /// - public static Duration AdditiveIdentity => Zero; + public static Duration Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public DurationUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Duration.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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 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.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.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. /// @@ -327,7 +365,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); } @@ -335,7 +373,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); } @@ -343,7 +381,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); } @@ -351,7 +389,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); } @@ -359,7 +397,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); } @@ -367,7 +405,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); } @@ -375,7 +413,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); } @@ -383,7 +421,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); } @@ -391,7 +429,7 @@ public static Duration FromNanoseconds(double value) /// /// Creates a from . /// - public static Duration FromSeconds(double value) + public static Duration FromSeconds(QuantityValue value) { return new Duration(value, DurationUnit.Second); } @@ -399,7 +437,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); } @@ -407,7 +445,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); } @@ -415,7 +453,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); } @@ -426,7 +464,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); } @@ -487,10 +525,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); } /// @@ -518,11 +553,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); } /// @@ -543,7 +574,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")); /// @@ -551,10 +582,10 @@ public static DurationUnit ParseUnit(string str) /// Error parsing string. public static DurationUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -569,10 +600,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -588,35 +619,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; } @@ -722,88 +753,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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Duration. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Duration), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -815,244 +840,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Duration other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Duration within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Duration other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Duration otherTyped - && (tolerance is Duration toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Duration'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Duration other, Duration tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Duration. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(DurationUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - 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 NotImplementedException($"Can not 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.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.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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(DurationUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(DurationUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1067,137 +872,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Duration)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Duration)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Duration)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Duration)) - return this; - else if (conversionType == typeof(DurationUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Duration.Info; - else if (conversionType == typeof(BaseDimensions)) - return Duration.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Duration)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs b/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs index 179bc68925..c6e1222ef6 100644 --- a/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -55,46 +50,112 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class DynamicViscosityInfo: QuantityInfo + { + /// + public DynamicViscosityInfo(string name, DynamicViscosityUnit baseUnit, IEnumerable> unitMappings, DynamicViscosity zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public DynamicViscosityInfo(string name, DynamicViscosityUnit baseUnit, IEnumerable> unitMappings, DynamicViscosity zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, DynamicViscosity.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.DynamicViscosity", typeof(DynamicViscosity).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the DynamicViscosity quantity. + /// + /// A new instance of the class with the default settings. + public static DynamicViscosityInfo CreateDefault() + { + return new DynamicViscosityInfo(nameof(DynamicViscosity), DefaultBaseUnit, GetDefaultMappings(), new DynamicViscosity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the DynamicViscosity quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static DynamicViscosityInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new DynamicViscosityInfo(nameof(DynamicViscosity), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new DynamicViscosity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-1L^-1M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-1, 1, -1, 0, 0, 0, 0); + + /// + /// The default base unit of DynamicViscosity is NewtonSecondPerMeterSquared. All conversions, as defined in the , go via this value. + /// + public static DynamicViscosityUnit DefaultBaseUnit { get; } = DynamicViscosityUnit.NewtonSecondPerMeterSquared; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for DynamicViscosity. + public static IEnumerable> GetDefaultMappings() + { + 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, + 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() { - BaseDimensions = new BaseDimensions(-1, 1, -1, 0, 0, 0, 0); - BaseUnit = DynamicViscosityUnit.NewtonSecondPerMeterSquared; - Units = Enum.GetValues(typeof(DynamicViscosityUnit)).Cast().ToArray(); - Zero = new DynamicViscosity(0, BaseUnit); - Info = new QuantityInfo("DynamicViscosity", - new UnitInfo[] - { - new UnitInfo(DynamicViscosityUnit.Centipoise, "Centipoise", BaseUnits.Undefined, "DynamicViscosity"), - new UnitInfo(DynamicViscosityUnit.MicropascalSecond, "MicropascalSeconds", BaseUnits.Undefined, "DynamicViscosity"), - new UnitInfo(DynamicViscosityUnit.MillipascalSecond, "MillipascalSeconds", BaseUnits.Undefined, "DynamicViscosity"), - new UnitInfo(DynamicViscosityUnit.NewtonSecondPerMeterSquared, "NewtonSecondsPerMeterSquared", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "DynamicViscosity"), - new UnitInfo(DynamicViscosityUnit.PascalSecond, "PascalSeconds", BaseUnits.Undefined, "DynamicViscosity"), - new UnitInfo(DynamicViscosityUnit.Poise, "Poise", BaseUnits.Undefined, "DynamicViscosity"), - new UnitInfo(DynamicViscosityUnit.PoundForceSecondPerSquareFoot, "PoundsForceSecondPerSquareFoot", BaseUnits.Undefined, "DynamicViscosity"), - new UnitInfo(DynamicViscosityUnit.PoundForceSecondPerSquareInch, "PoundsForceSecondPerSquareInch", BaseUnits.Undefined, "DynamicViscosity"), - new UnitInfo(DynamicViscosityUnit.PoundPerFootSecond, "PoundsPerFootSecond", BaseUnits.Undefined, "DynamicViscosity"), - new UnitInfo(DynamicViscosityUnit.Reyn, "Reyns", BaseUnits.Undefined, "DynamicViscosity"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(DynamicViscosityInfo.CreateDefault); } /// @@ -102,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; @@ -116,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); @@ -127,152 +188,129 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of DynamicViscosity, which is NewtonSecondPerMeterSquared. All conversions go via this value. /// - public static DynamicViscosityUnit BaseUnit { get; } + public static DynamicViscosityUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the DynamicViscosity quantity. /// - public static DynamicViscosityUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit NewtonSecondPerMeterSquared. /// - public static DynamicViscosity Zero { get; } - - /// - public static DynamicViscosity AdditiveIdentity => Zero; + public static DynamicViscosity Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public DynamicViscosityUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => DynamicViscosity.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -301,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); } @@ -309,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); } @@ -317,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); } @@ -325,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); } @@ -333,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); } @@ -341,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); } @@ -349,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); } @@ -357,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); } @@ -365,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); } @@ -373,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); } @@ -384,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); } @@ -445,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); } /// @@ -476,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); } /// @@ -501,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")); /// @@ -509,10 +540,10 @@ public static DynamicViscosityUnit ParseUnit(string str) /// Error parsing string. public static DynamicViscosityUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -527,10 +558,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -546,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; } @@ -602,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current DynamicViscosity. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(DynamicViscosity), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -695,240 +720,24 @@ public int CompareTo(object? obj) /// public int CompareTo(DynamicViscosity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another DynamicViscosity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(DynamicViscosity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is DynamicViscosity otherTyped - && (tolerance is DynamicViscosity toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'DynamicViscosity'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(DynamicViscosity other, DynamicViscosity tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current DynamicViscosity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(DynamicViscosityUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(DynamicViscosityUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -943,137 +752,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(DynamicViscosity)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(DynamicViscosity)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(DynamicViscosity)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(DynamicViscosity)) - return this; - else if (conversionType == typeof(DynamicViscosityUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return DynamicViscosity.Info; - else if (conversionType == typeof(BaseDimensions)) - return DynamicViscosity.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(DynamicViscosity)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs index 17dce29980..46c0affed2 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -43,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 @@ -52,52 +47,130 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ElectricAdmittanceInfo: QuantityInfo + { + /// + public ElectricAdmittanceInfo(string name, ElectricAdmittanceUnit baseUnit, IEnumerable> unitMappings, ElectricAdmittance zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ElectricAdmittanceInfo(string name, ElectricAdmittanceUnit baseUnit, IEnumerable> unitMappings, ElectricAdmittance zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ElectricAdmittance.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ElectricAdmittance", typeof(ElectricAdmittance).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricAdmittance quantity. + /// + /// A new instance of the class with the default settings. + public static ElectricAdmittanceInfo CreateDefault() + { + return new ElectricAdmittanceInfo(nameof(ElectricAdmittance), DefaultBaseUnit, GetDefaultMappings(), new ElectricAdmittance(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricAdmittance quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ElectricAdmittanceInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ElectricAdmittanceInfo(nameof(ElectricAdmittance), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ElectricAdmittance(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^3L^-2M^-1I^2. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, -1, 3, 2, 0, 0, 0); + + /// + /// The default base unit of ElectricAdmittance is Siemens. All conversions, as defined in the , go via this value. + /// + public static ElectricAdmittanceUnit DefaultBaseUnit { get; } = ElectricAdmittanceUnit.Siemens; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for ElectricAdmittance. + public static IEnumerable> GetDefaultMappings() + { + 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, + 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() { - BaseDimensions = new BaseDimensions(-2, -1, 3, 2, 0, 0, 0); - BaseUnit = ElectricAdmittanceUnit.Siemens; - Units = Enum.GetValues(typeof(ElectricAdmittanceUnit)).Cast().ToArray(); - Zero = new ElectricAdmittance(0, BaseUnit); - Info = new QuantityInfo("ElectricAdmittance", - new UnitInfo[] - { - new UnitInfo(ElectricAdmittanceUnit.Gigamho, "Gigamhos", BaseUnits.Undefined, "ElectricAdmittance"), - new UnitInfo(ElectricAdmittanceUnit.Gigasiemens, "Gigasiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricAdmittance"), - new UnitInfo(ElectricAdmittanceUnit.Kilomho, "Kilomhos", BaseUnits.Undefined, "ElectricAdmittance"), - new UnitInfo(ElectricAdmittanceUnit.Kilosiemens, "Kilosiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricAdmittance"), - new UnitInfo(ElectricAdmittanceUnit.Megamho, "Megamhos", BaseUnits.Undefined, "ElectricAdmittance"), - new UnitInfo(ElectricAdmittanceUnit.Megasiemens, "Megasiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricAdmittance"), - new UnitInfo(ElectricAdmittanceUnit.Mho, "Mhos", BaseUnits.Undefined, "ElectricAdmittance"), - new UnitInfo(ElectricAdmittanceUnit.Micromho, "Micromhos", BaseUnits.Undefined, "ElectricAdmittance"), - new UnitInfo(ElectricAdmittanceUnit.Microsiemens, "Microsiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere), "ElectricAdmittance"), - new UnitInfo(ElectricAdmittanceUnit.Millimho, "Millimhos", BaseUnits.Undefined, "ElectricAdmittance"), - new UnitInfo(ElectricAdmittanceUnit.Millisiemens, "Millisiemens", BaseUnits.Undefined, "ElectricAdmittance"), - new UnitInfo(ElectricAdmittanceUnit.Nanomho, "Nanomhos", BaseUnits.Undefined, "ElectricAdmittance"), - new UnitInfo(ElectricAdmittanceUnit.Nanosiemens, "Nanosiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond, current: ElectricCurrentUnit.Ampere), "ElectricAdmittance"), - new UnitInfo(ElectricAdmittanceUnit.Siemens, "Siemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricAdmittance"), - new UnitInfo(ElectricAdmittanceUnit.Teramho, "Teramhos", BaseUnits.Undefined, "ElectricAdmittance"), - new UnitInfo(ElectricAdmittanceUnit.Terasiemens, "Terasiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Nanogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricAdmittance"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricAdmittanceInfo.CreateDefault); } /// @@ -105,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; @@ -119,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); @@ -130,194 +203,159 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ElectricAdmittance, which is Siemens. All conversions go via this value. /// - public static ElectricAdmittanceUnit BaseUnit { get; } + public static ElectricAdmittanceUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ElectricAdmittance quantity. /// - public static ElectricAdmittanceUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Siemens. /// - public static ElectricAdmittance Zero { get; } - - /// - public static ElectricAdmittance AdditiveIdentity => Zero; + public static ElectricAdmittance Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ElectricAdmittanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ElectricAdmittance.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -346,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); } @@ -354,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); } @@ -362,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); } @@ -370,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); } @@ -378,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); } @@ -386,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); } @@ -394,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); } @@ -402,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); } @@ -410,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); } @@ -418,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); } @@ -426,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); } @@ -434,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); } @@ -442,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); } @@ -450,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); } @@ -458,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); } @@ -466,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); } @@ -477,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); } @@ -538,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); } /// @@ -569,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); } /// @@ -594,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")); /// @@ -602,10 +633,10 @@ public static ElectricAdmittanceUnit ParseUnit(string str) /// Error parsing string. public static ElectricAdmittanceUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -620,10 +651,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -639,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; } @@ -679,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ElectricAdmittance. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ElectricAdmittance), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -772,252 +797,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricAdmittance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ElectricAdmittance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ElectricAdmittance other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ElectricAdmittance otherTyped - && (tolerance is ElectricAdmittance toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ElectricAdmittance'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ElectricAdmittance other, ElectricAdmittance tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricAdmittance. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(ElectricAdmittanceUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(ElectricAdmittanceUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(ElectricAdmittanceUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1032,137 +829,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricAdmittance)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricAdmittance)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricAdmittance)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ElectricAdmittance)) - return this; - else if (conversionType == typeof(ElectricAdmittanceUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ElectricAdmittance.Info; - else if (conversionType == typeof(BaseDimensions)) - return ElectricAdmittance.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ElectricAdmittance)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricApparentEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricApparentEnergy.g.cs index 9145550d66..bdf01d5757 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricApparentEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricApparentEnergy.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -48,39 +43,91 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static ElectricApparentEnergy() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ElectricApparentEnergyInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); - BaseUnit = ElectricApparentEnergyUnit.VoltampereHour; - Units = Enum.GetValues(typeof(ElectricApparentEnergyUnit)).Cast().ToArray(); - Zero = new ElectricApparentEnergy(0, BaseUnit); - Info = new QuantityInfo("ElectricApparentEnergy", - new UnitInfo[] - { - new UnitInfo(ElectricApparentEnergyUnit.KilovoltampereHour, "KilovoltampereHours", BaseUnits.Undefined, "ElectricApparentEnergy"), - new UnitInfo(ElectricApparentEnergyUnit.MegavoltampereHour, "MegavoltampereHours", BaseUnits.Undefined, "ElectricApparentEnergy"), - new UnitInfo(ElectricApparentEnergyUnit.VoltampereHour, "VoltampereHours", BaseUnits.Undefined, "ElectricApparentEnergy"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public ElectricApparentEnergyInfo(string name, ElectricApparentEnergyUnit baseUnit, IEnumerable> unitMappings, ElectricApparentEnergy zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ElectricApparentEnergyInfo(string name, ElectricApparentEnergyUnit baseUnit, IEnumerable> unitMappings, ElectricApparentEnergy zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ElectricApparentEnergy.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ElectricApparentEnergy", typeof(ElectricApparentEnergy).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the ElectricApparentEnergy quantity. + /// + /// A new instance of the class with the default settings. + public static ElectricApparentEnergyInfo CreateDefault() + { + return new ElectricApparentEnergyInfo(nameof(ElectricApparentEnergy), DefaultBaseUnit, GetDefaultMappings(), new ElectricApparentEnergy(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricApparentEnergy quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ElectricApparentEnergyInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ElectricApparentEnergyInfo(nameof(ElectricApparentEnergy), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ElectricApparentEnergy(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-2L^2M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); + + /// + /// The default base unit of ElectricApparentEnergy is VoltampereHour. All conversions, as defined in the , go via this value. + /// + public static ElectricApparentEnergyUnit DefaultBaseUnit { get; } = ElectricApparentEnergyUnit.VoltampereHour; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for ElectricApparentEnergy. + public static IEnumerable> GetDefaultMappings() + { + 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 = UnitsNetSetup.CreateQuantityInfo(ElectricApparentEnergyInfo.CreateDefault); } /// @@ -88,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; @@ -102,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); @@ -113,103 +160,94 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ElectricApparentEnergy, which is VoltampereHour. All conversions go via this value. /// - public static ElectricApparentEnergyUnit BaseUnit { get; } + public static ElectricApparentEnergyUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ElectricApparentEnergy quantity. /// - public static ElectricApparentEnergyUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereHour. /// - public static ElectricApparentEnergy Zero { get; } - - /// - public static ElectricApparentEnergy AdditiveIdentity => Zero; + public static ElectricApparentEnergy Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ElectricApparentEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ElectricApparentEnergy.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -238,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); } @@ -246,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); } @@ -254,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); } @@ -265,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); } @@ -326,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); } /// @@ -357,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); } /// @@ -382,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")); /// @@ -390,10 +421,10 @@ public static ElectricApparentEnergyUnit ParseUnit(string str) /// Error parsing string. public static ElectricApparentEnergyUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -408,10 +439,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -427,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; } @@ -467,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ElectricApparentEnergy. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ElectricApparentEnergy), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -560,226 +585,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricApparentEnergy other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ElectricApparentEnergy within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ElectricApparentEnergy other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ElectricApparentEnergy otherTyped - && (tolerance is ElectricApparentEnergy toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ElectricApparentEnergy'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ElectricApparentEnergy other, ElectricApparentEnergy tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricApparentEnergy. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(ElectricApparentEnergyUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(ElectricApparentEnergyUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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), - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -794,137 +617,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricApparentEnergy)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricApparentEnergy)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricApparentEnergy)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ElectricApparentEnergy)) - return this; - else if (conversionType == typeof(ElectricApparentEnergyUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ElectricApparentEnergy.Info; - else if (conversionType == typeof(BaseDimensions)) - return ElectricApparentEnergy.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ElectricApparentEnergy)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricApparentPower.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricApparentPower.g.cs index 6358382f46..69c29293d9 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricApparentPower.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricApparentPower.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,42 +46,100 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static ElectricApparentPower() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ElectricApparentPowerInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); - BaseUnit = ElectricApparentPowerUnit.Voltampere; - Units = Enum.GetValues(typeof(ElectricApparentPowerUnit)).Cast().ToArray(); - Zero = new ElectricApparentPower(0, BaseUnit); - Info = new QuantityInfo("ElectricApparentPower", - new UnitInfo[] - { - new UnitInfo(ElectricApparentPowerUnit.Gigavoltampere, "Gigavoltamperes", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond), "ElectricApparentPower"), - new UnitInfo(ElectricApparentPowerUnit.Kilovoltampere, "Kilovoltamperes", BaseUnits.Undefined, "ElectricApparentPower"), - new UnitInfo(ElectricApparentPowerUnit.Megavoltampere, "Megavoltamperes", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "ElectricApparentPower"), - new UnitInfo(ElectricApparentPowerUnit.Microvoltampere, "Microvoltamperes", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second), "ElectricApparentPower"), - new UnitInfo(ElectricApparentPowerUnit.Millivoltampere, "Millivoltamperes", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second), "ElectricApparentPower"), - new UnitInfo(ElectricApparentPowerUnit.Voltampere, "Voltamperes", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "ElectricApparentPower"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public ElectricApparentPowerInfo(string name, ElectricApparentPowerUnit baseUnit, IEnumerable> unitMappings, ElectricApparentPower zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ElectricApparentPowerInfo(string name, ElectricApparentPowerUnit baseUnit, IEnumerable> unitMappings, ElectricApparentPower zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ElectricApparentPower.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ElectricApparentPower", typeof(ElectricApparentPower).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricApparentPower quantity. + /// + /// A new instance of the class with the default settings. + public static ElectricApparentPowerInfo CreateDefault() + { + return new ElectricApparentPowerInfo(nameof(ElectricApparentPower), DefaultBaseUnit, GetDefaultMappings(), new ElectricApparentPower(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricApparentPower quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ElectricApparentPowerInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ElectricApparentPowerInfo(nameof(ElectricApparentPower), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ElectricApparentPower(0, DefaultBaseUnit), DefaultBaseDimensions); + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// The for is T^-3L^2M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); + + /// + /// The default base unit of ElectricApparentPower is Voltampere. All conversions, as defined in the , go via this value. + /// + public static ElectricApparentPowerUnit DefaultBaseUnit { get; } = ElectricApparentPowerUnit.Voltampere; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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 = UnitsNetSetup.CreateQuantityInfo(ElectricApparentPowerInfo.CreateDefault); } /// @@ -94,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; @@ -108,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); @@ -119,124 +172,109 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ElectricApparentPower, which is Voltampere. All conversions go via this value. /// - public static ElectricApparentPowerUnit BaseUnit { get; } + public static ElectricApparentPowerUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ElectricApparentPower quantity. /// - public static ElectricApparentPowerUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Voltampere. /// - public static ElectricApparentPower Zero { get; } - - /// - public static ElectricApparentPower AdditiveIdentity => Zero; + public static ElectricApparentPower Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ElectricApparentPowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ElectricApparentPower.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -265,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); } @@ -273,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); } @@ -281,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); } @@ -289,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); } @@ -297,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); } @@ -305,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); } @@ -316,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); } @@ -377,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); } /// @@ -408,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); } /// @@ -433,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")); /// @@ -441,10 +472,10 @@ public static ElectricApparentPowerUnit ParseUnit(string str) /// Error parsing string. public static ElectricApparentPowerUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -459,10 +490,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -478,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; } @@ -518,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ElectricApparentPower. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ElectricApparentPower), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -611,232 +636,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricApparentPower other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ElectricApparentPower within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ElectricApparentPower other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ElectricApparentPower otherTyped - && (tolerance is ElectricApparentPower toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ElectricApparentPower'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ElectricApparentPower other, ElectricApparentPower tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricApparentPower. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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)); + #region Conversion Methods (explicit implementations for netstandard2.0) - 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 ElectricApparentPowerUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricApparentPowerUnit)} 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(ElectricApparentPowerUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(ElectricApparentPowerUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -851,137 +668,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricApparentPower)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricApparentPower)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricApparentPower)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ElectricApparentPower)) - return this; - else if (conversionType == typeof(ElectricApparentPowerUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ElectricApparentPower.Info; - else if (conversionType == typeof(BaseDimensions)) - return ElectricApparentPower.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ElectricApparentPower)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCapacitance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCapacitance.g.cs index e3f0778380..653b7d8ee2 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCapacitance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCapacitance.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,43 +46,103 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static ElectricCapacitance() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ElectricCapacitanceInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(-2, -1, 4, 2, 0, 0, 0); - BaseUnit = ElectricCapacitanceUnit.Farad; - Units = Enum.GetValues(typeof(ElectricCapacitanceUnit)).Cast().ToArray(); - Zero = new ElectricCapacitance(0, BaseUnit); - Info = new QuantityInfo("ElectricCapacitance", - new UnitInfo[] - { - new UnitInfo(ElectricCapacitanceUnit.Farad, "Farads", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricCapacitance"), - new UnitInfo(ElectricCapacitanceUnit.Kilofarad, "Kilofarads", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricCapacitance"), - new UnitInfo(ElectricCapacitanceUnit.Megafarad, "Megafarads", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricCapacitance"), - new UnitInfo(ElectricCapacitanceUnit.Microfarad, "Microfarads", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere), "ElectricCapacitance"), - new UnitInfo(ElectricCapacitanceUnit.Millifarad, "Millifarads", BaseUnits.Undefined, "ElectricCapacitance"), - new UnitInfo(ElectricCapacitanceUnit.Nanofarad, "Nanofarads", BaseUnits.Undefined, "ElectricCapacitance"), - new UnitInfo(ElectricCapacitanceUnit.Picofarad, "Picofarads", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Microampere), "ElectricCapacitance"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public ElectricCapacitanceInfo(string name, ElectricCapacitanceUnit baseUnit, IEnumerable> unitMappings, ElectricCapacitance zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ElectricCapacitanceInfo(string name, ElectricCapacitanceUnit baseUnit, IEnumerable> unitMappings, ElectricCapacitance zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ElectricCapacitance.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ElectricCapacitance", typeof(ElectricCapacitance).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricCapacitance quantity. + /// + /// A new instance of the class with the default settings. + public static ElectricCapacitanceInfo CreateDefault() + { + return new ElectricCapacitanceInfo(nameof(ElectricCapacitance), DefaultBaseUnit, GetDefaultMappings(), new ElectricCapacitance(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricCapacitance quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ElectricCapacitanceInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ElectricCapacitanceInfo(nameof(ElectricCapacitance), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ElectricCapacitance(0, DefaultBaseUnit), DefaultBaseDimensions); + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// The for is T^4L^-2M^-1I^2. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, -1, 4, 2, 0, 0, 0); + + /// + /// The default base unit of ElectricCapacitance is Farad. All conversions, as defined in the , go via this value. + /// + public static ElectricCapacitanceUnit DefaultBaseUnit { get; } = ElectricCapacitanceUnit.Farad; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for ElectricCapacitance. + public static IEnumerable> 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), + 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 = UnitsNetSetup.CreateQuantityInfo(ElectricCapacitanceInfo.CreateDefault); } /// @@ -95,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; @@ -109,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); @@ -120,131 +175,114 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ElectricCapacitance, which is Farad. All conversions go via this value. /// - public static ElectricCapacitanceUnit BaseUnit { get; } + public static ElectricCapacitanceUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ElectricCapacitance quantity. /// - public static ElectricCapacitanceUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Farad. /// - public static ElectricCapacitance Zero { get; } - - /// - public static ElectricCapacitance AdditiveIdentity => Zero; + public static ElectricCapacitance Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ElectricCapacitanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ElectricCapacitance.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -273,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); } @@ -281,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); } @@ -289,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); } @@ -297,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); } @@ -305,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); } @@ -313,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); } @@ -321,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); } @@ -332,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); } @@ -393,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); } /// @@ -424,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); } /// @@ -449,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")); /// @@ -457,10 +488,10 @@ public static ElectricCapacitanceUnit ParseUnit(string str) /// Error parsing string. public static ElectricCapacitanceUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -475,10 +506,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -494,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; } @@ -534,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ElectricCapacitance. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ElectricCapacitance), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -627,234 +652,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricCapacitance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ElectricCapacitance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ElectricCapacitance other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ElectricCapacitance otherTyped - && (tolerance is ElectricCapacitance toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ElectricCapacitance'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ElectricCapacitance other, ElectricCapacitance tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricCapacitance. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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)); + #region Conversion Methods (explicit implementations for netstandard2.0) - 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 ElectricCapacitanceUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCapacitanceUnit)} 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(ElectricCapacitanceUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(ElectricCapacitanceUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -869,137 +684,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricCapacitance)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricCapacitance)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricCapacitance)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ElectricCapacitance)) - return this; - else if (conversionType == typeof(ElectricCapacitanceUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ElectricCapacitance.Info; - else if (conversionType == typeof(BaseDimensions)) - return ElectricCapacitance.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ElectricCapacitance)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs index 13300c172c..9d3b3ffe2a 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -56,47 +51,115 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ElectricChargeInfo: QuantityInfo + { + /// + public ElectricChargeInfo(string name, ElectricChargeUnit baseUnit, IEnumerable> unitMappings, ElectricCharge zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ElectricChargeInfo(string name, ElectricChargeUnit baseUnit, IEnumerable> unitMappings, ElectricCharge zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ElectricCharge.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ElectricCharge", typeof(ElectricCharge).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricCharge quantity. + /// + /// A new instance of the class with the default settings. + public static ElectricChargeInfo CreateDefault() + { + return new ElectricChargeInfo(nameof(ElectricCharge), DefaultBaseUnit, GetDefaultMappings(), new ElectricCharge(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricCharge quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ElectricChargeInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ElectricChargeInfo(nameof(ElectricCharge), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ElectricCharge(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is TI. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, 1, 1, 0, 0, 0); + + /// + /// The default base unit of ElectricCharge is Coulomb. All conversions, as defined in the , go via this value. + /// + public static ElectricChargeUnit DefaultBaseUnit { get; } = ElectricChargeUnit.Coulomb; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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), + 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() { - BaseDimensions = new BaseDimensions(0, 0, 1, 1, 0, 0, 0); - BaseUnit = ElectricChargeUnit.Coulomb; - Units = Enum.GetValues(typeof(ElectricChargeUnit)).Cast().ToArray(); - Zero = new ElectricCharge(0, BaseUnit); - Info = new QuantityInfo("ElectricCharge", - new UnitInfo[] - { - new UnitInfo(ElectricChargeUnit.AmpereHour, "AmpereHours", new BaseUnits(time: DurationUnit.Hour, current: ElectricCurrentUnit.Ampere), "ElectricCharge"), - new UnitInfo(ElectricChargeUnit.Coulomb, "Coulombs", new BaseUnits(time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricCharge"), - new UnitInfo(ElectricChargeUnit.KiloampereHour, "KiloampereHours", new BaseUnits(time: DurationUnit.Hour, current: ElectricCurrentUnit.Kiloampere), "ElectricCharge"), - new UnitInfo(ElectricChargeUnit.Kilocoulomb, "Kilocoulombs", new BaseUnits(time: DurationUnit.Second, current: ElectricCurrentUnit.Kiloampere), "ElectricCharge"), - new UnitInfo(ElectricChargeUnit.MegaampereHour, "MegaampereHours", new BaseUnits(time: DurationUnit.Hour, current: ElectricCurrentUnit.Megaampere), "ElectricCharge"), - new UnitInfo(ElectricChargeUnit.Megacoulomb, "Megacoulombs", new BaseUnits(time: DurationUnit.Second, current: ElectricCurrentUnit.Megaampere), "ElectricCharge"), - new UnitInfo(ElectricChargeUnit.Microcoulomb, "Microcoulombs", new BaseUnits(time: DurationUnit.Second, current: ElectricCurrentUnit.Microampere), "ElectricCharge"), - new UnitInfo(ElectricChargeUnit.MilliampereHour, "MilliampereHours", new BaseUnits(time: DurationUnit.Hour, current: ElectricCurrentUnit.Milliampere), "ElectricCharge"), - new UnitInfo(ElectricChargeUnit.Millicoulomb, "Millicoulombs", new BaseUnits(time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere), "ElectricCharge"), - new UnitInfo(ElectricChargeUnit.Nanocoulomb, "Nanocoulombs", new BaseUnits(time: DurationUnit.Second, current: ElectricCurrentUnit.Nanoampere), "ElectricCharge"), - new UnitInfo(ElectricChargeUnit.Picocoulomb, "Picocoulombs", new BaseUnits(time: DurationUnit.Second, current: ElectricCurrentUnit.Picoampere), "ElectricCharge"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricChargeInfo.CreateDefault); } /// @@ -104,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; @@ -118,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); @@ -129,159 +192,134 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ElectricCharge, which is Coulomb. All conversions go via this value. /// - public static ElectricChargeUnit BaseUnit { get; } + public static ElectricChargeUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ElectricCharge quantity. /// - public static ElectricChargeUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Coulomb. /// - public static ElectricCharge Zero { get; } - - /// - public static ElectricCharge AdditiveIdentity => Zero; + public static ElectricCharge Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ElectricChargeUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ElectricCharge.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -310,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); } @@ -318,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); } @@ -326,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); } @@ -334,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); } @@ -342,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); } @@ -350,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); } @@ -358,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); } @@ -366,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); } @@ -374,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); } @@ -382,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); } @@ -390,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); } @@ -401,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); } @@ -462,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); } /// @@ -493,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); } /// @@ -518,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")); /// @@ -526,10 +557,10 @@ public static ElectricChargeUnit ParseUnit(string str) /// Error parsing string. public static ElectricChargeUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -544,10 +575,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -563,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; } @@ -625,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ElectricCharge. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ElectricCharge), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -718,242 +743,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricCharge other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ElectricCharge within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ElectricCharge other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ElectricCharge otherTyped - && (tolerance is ElectricCharge toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ElectricCharge'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ElectricCharge other, ElectricCharge tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricCharge. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(ElectricChargeUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(ElectricChargeUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -968,137 +775,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricCharge)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricCharge)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricCharge)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ElectricCharge)) - return this; - else if (conversionType == typeof(ElectricChargeUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ElectricCharge.Info; - else if (conversionType == typeof(BaseDimensions)) - return ElectricCharge.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ElectricCharge)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs index b80f4482d0..a8c8f46553 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,37 +46,85 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static ElectricChargeDensity() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ElectricChargeDensityInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(-3, 0, 1, 1, 0, 0, 0); - BaseUnit = ElectricChargeDensityUnit.CoulombPerCubicMeter; - Units = Enum.GetValues(typeof(ElectricChargeDensityUnit)).Cast().ToArray(); - Zero = new ElectricChargeDensity(0, BaseUnit); - Info = new QuantityInfo("ElectricChargeDensity", - new UnitInfo[] - { - new UnitInfo(ElectricChargeDensityUnit.CoulombPerCubicMeter, "CoulombsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricChargeDensity"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public ElectricChargeDensityInfo(string name, ElectricChargeDensityUnit baseUnit, IEnumerable> unitMappings, ElectricChargeDensity zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ElectricChargeDensityInfo(string name, ElectricChargeDensityUnit baseUnit, IEnumerable> unitMappings, ElectricChargeDensity zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ElectricChargeDensity.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ElectricChargeDensity", typeof(ElectricChargeDensity).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the ElectricChargeDensity quantity. + /// + /// A new instance of the class with the default settings. + public static ElectricChargeDensityInfo CreateDefault() + { + return new ElectricChargeDensityInfo(nameof(ElectricChargeDensity), DefaultBaseUnit, GetDefaultMappings(), new ElectricChargeDensity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricChargeDensity quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ElectricChargeDensityInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ElectricChargeDensityInfo(nameof(ElectricChargeDensity), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ElectricChargeDensity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is TL^-3I. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-3, 0, 1, 1, 0, 0, 0); + + /// + /// The default base unit of ElectricChargeDensity is CoulombPerCubicMeter. All conversions, as defined in the , go via this value. + /// + public static ElectricChargeDensityUnit DefaultBaseUnit { get; } = ElectricChargeDensityUnit.CoulombPerCubicMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for ElectricChargeDensity. + public static IEnumerable> GetDefaultMappings() + { + yield return new (ElectricChargeDensityUnit.CoulombPerCubicMeter, "CoulombPerCubicMeter", "CoulombsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); + } + } + + static ElectricChargeDensity() + { + Info = UnitsNetSetup.CreateQuantityInfo(ElectricChargeDensityInfo.CreateDefault); } /// @@ -89,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; @@ -103,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); @@ -114,88 +157,83 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ElectricChargeDensity, which is CoulombPerCubicMeter. All conversions go via this value. /// - public static ElectricChargeDensityUnit BaseUnit { get; } + public static ElectricChargeDensityUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ElectricChargeDensity quantity. /// - public static ElectricChargeDensityUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit CoulombPerCubicMeter. /// - public static ElectricChargeDensity Zero { get; } - - /// - public static ElectricChargeDensity AdditiveIdentity => Zero; + public static ElectricChargeDensity Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ElectricChargeDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ElectricChargeDensity.BaseDimensions; - #endregion + #region Explicit implementations - #region Conversion Properties + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); - /// - /// Gets a value of this quantity converted into - /// - public double CoulombsPerCubicMeter => As(ElectricChargeDensityUnit.CoulombPerCubicMeter); + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif #endregion - #region Static Methods + #endregion + + #region Conversion Properties /// - /// Registers the default conversion functions in the given instance. + /// Gets a value of this quantity converted into /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ElectricChargeDensityUnit -> BaseUnit + public QuantityValue CoulombsPerCubicMeter => this.As(ElectricChargeDensityUnit.CoulombPerCubicMeter); - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ElectricChargeDensityUnit.CoulombPerCubicMeter, ElectricChargeDensityUnit.CoulombPerCubicMeter, quantity => quantity); + #endregion - // Register in unit converter: BaseUnit -> ElectricChargeDensityUnit - } + #region Static Methods /// /// Get unit abbreviation string. @@ -225,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); } @@ -236,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); } @@ -297,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); } /// @@ -328,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); } /// @@ -353,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")); /// @@ -361,10 +392,10 @@ public static ElectricChargeDensityUnit ParseUnit(string str) /// Error parsing string. public static ElectricChargeDensityUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -379,10 +410,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -398,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; } @@ -438,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ElectricChargeDensity. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ElectricChargeDensity), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -531,222 +556,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricChargeDensity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ElectricChargeDensity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ElectricChargeDensity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ElectricChargeDensity otherTyped - && (tolerance is ElectricChargeDensity toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ElectricChargeDensity'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ElectricChargeDensity other, ElectricChargeDensity tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricChargeDensity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(ElectricChargeDensityUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(ElectricChargeDensityUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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 - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -761,137 +588,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricChargeDensity)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricChargeDensity)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricChargeDensity)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ElectricChargeDensity)) - return this; - else if (conversionType == typeof(ElectricChargeDensityUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ElectricChargeDensity.Info; - else if (conversionType == typeof(BaseDimensions)) - return ElectricChargeDensity.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ElectricChargeDensity)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs index 67ed857b98..5128e61977 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,52 +46,130 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ElectricConductanceInfo: QuantityInfo + { + /// + public ElectricConductanceInfo(string name, ElectricConductanceUnit baseUnit, IEnumerable> unitMappings, ElectricConductance zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ElectricConductanceInfo(string name, ElectricConductanceUnit baseUnit, IEnumerable> unitMappings, ElectricConductance zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ElectricConductance.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ElectricConductance", typeof(ElectricConductance).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricConductance quantity. + /// + /// A new instance of the class with the default settings. + public static ElectricConductanceInfo CreateDefault() + { + return new ElectricConductanceInfo(nameof(ElectricConductance), DefaultBaseUnit, GetDefaultMappings(), new ElectricConductance(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricConductance quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ElectricConductanceInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ElectricConductanceInfo(nameof(ElectricConductance), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ElectricConductance(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^3L^-2M^-1I^2. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, -1, 3, 2, 0, 0, 0); + + /// + /// The default base unit of ElectricConductance is Siemens. All conversions, as defined in the , go via this value. + /// + public static ElectricConductanceUnit DefaultBaseUnit { get; } = ElectricConductanceUnit.Siemens; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for ElectricConductance. + public static IEnumerable> GetDefaultMappings() + { + 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, + 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() { - BaseDimensions = new BaseDimensions(-2, -1, 3, 2, 0, 0, 0); - BaseUnit = ElectricConductanceUnit.Siemens; - Units = Enum.GetValues(typeof(ElectricConductanceUnit)).Cast().ToArray(); - Zero = new ElectricConductance(0, BaseUnit); - Info = new QuantityInfo("ElectricConductance", - new UnitInfo[] - { - new UnitInfo(ElectricConductanceUnit.Gigamho, "Gigamhos", BaseUnits.Undefined, "ElectricConductance"), - new UnitInfo(ElectricConductanceUnit.Gigasiemens, "Gigasiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricConductance"), - new UnitInfo(ElectricConductanceUnit.Kilomho, "Kilomhos", BaseUnits.Undefined, "ElectricConductance"), - new UnitInfo(ElectricConductanceUnit.Kilosiemens, "Kilosiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricConductance"), - new UnitInfo(ElectricConductanceUnit.Megamho, "Megamhos", BaseUnits.Undefined, "ElectricConductance"), - new UnitInfo(ElectricConductanceUnit.Megasiemens, "Megasiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricConductance"), - new UnitInfo(ElectricConductanceUnit.Mho, "Mhos", BaseUnits.Undefined, "ElectricConductance"), - new UnitInfo(ElectricConductanceUnit.Micromho, "Micromhos", BaseUnits.Undefined, "ElectricConductance"), - new UnitInfo(ElectricConductanceUnit.Microsiemens, "Microsiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere), "ElectricConductance"), - new UnitInfo(ElectricConductanceUnit.Millimho, "Millimhos", BaseUnits.Undefined, "ElectricConductance"), - new UnitInfo(ElectricConductanceUnit.Millisiemens, "Millisiemens", BaseUnits.Undefined, "ElectricConductance"), - new UnitInfo(ElectricConductanceUnit.Nanomho, "Nanomhos", BaseUnits.Undefined, "ElectricConductance"), - new UnitInfo(ElectricConductanceUnit.Nanosiemens, "Nanosiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond, current: ElectricCurrentUnit.Ampere), "ElectricConductance"), - new UnitInfo(ElectricConductanceUnit.Siemens, "Siemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricConductance"), - new UnitInfo(ElectricConductanceUnit.Teramho, "Teramhos", BaseUnits.Undefined, "ElectricConductance"), - new UnitInfo(ElectricConductanceUnit.Terasiemens, "Terasiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Nanogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricConductance"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricConductanceInfo.CreateDefault); } /// @@ -104,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; @@ -118,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); @@ -129,194 +202,159 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ElectricConductance, which is Siemens. All conversions go via this value. /// - public static ElectricConductanceUnit BaseUnit { get; } + public static ElectricConductanceUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ElectricConductance quantity. /// - public static ElectricConductanceUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Siemens. /// - public static ElectricConductance Zero { get; } - - /// - public static ElectricConductance AdditiveIdentity => Zero; + public static ElectricConductance Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ElectricConductanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ElectricConductance.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -345,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); } @@ -353,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); } @@ -361,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); } @@ -369,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); } @@ -377,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); } @@ -385,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); } @@ -393,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); } @@ -401,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); } @@ -409,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); } @@ -417,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); } @@ -425,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); } @@ -433,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); } @@ -441,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); } @@ -449,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); } @@ -457,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); } @@ -465,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); } @@ -476,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); } @@ -537,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); } /// @@ -568,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); } /// @@ -593,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")); /// @@ -601,10 +632,10 @@ public static ElectricConductanceUnit ParseUnit(string str) /// Error parsing string. public static ElectricConductanceUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -619,10 +650,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -638,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; } @@ -678,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ElectricConductance. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ElectricConductance), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -771,252 +796,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricConductance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ElectricConductance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ElectricConductance other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ElectricConductance otherTyped - && (tolerance is ElectricConductance toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ElectricConductance'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ElectricConductance other, ElectricConductance tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricConductance. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(ElectricConductanceUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(ElectricConductanceUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(ElectricConductanceUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1031,137 +828,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricConductance)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricConductance)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricConductance)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ElectricConductance)) - return this; - else if (conversionType == typeof(ElectricConductanceUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ElectricConductance.Info; - else if (conversionType == typeof(BaseDimensions)) - return ElectricConductance.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ElectricConductance)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs index 528070f486..b1aa171e27 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,42 +46,100 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static ElectricConductivity() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ElectricConductivityInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(-3, -1, 3, 2, 0, 0, 0); - BaseUnit = ElectricConductivityUnit.SiemensPerMeter; - Units = Enum.GetValues(typeof(ElectricConductivityUnit)).Cast().ToArray(); - Zero = new ElectricConductivity(0, BaseUnit); - Info = new QuantityInfo("ElectricConductivity", - new UnitInfo[] - { - new UnitInfo(ElectricConductivityUnit.MicrosiemensPerCentimeter, "MicrosiemensPerCentimeter", BaseUnits.Undefined, "ElectricConductivity"), - new UnitInfo(ElectricConductivityUnit.MillisiemensPerCentimeter, "MillisiemensPerCentimeter", BaseUnits.Undefined, "ElectricConductivity"), - new UnitInfo(ElectricConductivityUnit.SiemensPerCentimeter, "SiemensPerCentimeter", BaseUnits.Undefined, "ElectricConductivity"), - new UnitInfo(ElectricConductivityUnit.SiemensPerFoot, "SiemensPerFoot", BaseUnits.Undefined, "ElectricConductivity"), - new UnitInfo(ElectricConductivityUnit.SiemensPerInch, "SiemensPerInch", BaseUnits.Undefined, "ElectricConductivity"), - new UnitInfo(ElectricConductivityUnit.SiemensPerMeter, "SiemensPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricConductivity"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public ElectricConductivityInfo(string name, ElectricConductivityUnit baseUnit, IEnumerable> unitMappings, ElectricConductivity zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ElectricConductivityInfo(string name, ElectricConductivityUnit baseUnit, IEnumerable> unitMappings, ElectricConductivity zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ElectricConductivity.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ElectricConductivity", typeof(ElectricConductivity).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricConductivity quantity. + /// + /// A new instance of the class with the default settings. + public static ElectricConductivityInfo CreateDefault() + { + return new ElectricConductivityInfo(nameof(ElectricConductivity), DefaultBaseUnit, GetDefaultMappings(), new ElectricConductivity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricConductivity quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ElectricConductivityInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ElectricConductivityInfo(nameof(ElectricConductivity), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ElectricConductivity(0, DefaultBaseUnit), DefaultBaseDimensions); + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// The for is T^3L^-3M^-1I^2. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-3, -1, 3, 2, 0, 0, 0); + + /// + /// The default base unit of ElectricConductivity is SiemensPerMeter. All conversions, as defined in the , go via this value. + /// + public static ElectricConductivityUnit DefaultBaseUnit { get; } = ElectricConductivityUnit.SiemensPerMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for ElectricConductivity. + public static IEnumerable> GetDefaultMappings() + { + 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 = UnitsNetSetup.CreateQuantityInfo(ElectricConductivityInfo.CreateDefault); } /// @@ -94,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; @@ -108,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); @@ -119,124 +172,109 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ElectricConductivity, which is SiemensPerMeter. All conversions go via this value. /// - public static ElectricConductivityUnit BaseUnit { get; } + public static ElectricConductivityUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ElectricConductivity quantity. /// - public static ElectricConductivityUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit SiemensPerMeter. /// - public static ElectricConductivity Zero { get; } - - /// - public static ElectricConductivity AdditiveIdentity => Zero; + public static ElectricConductivity Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ElectricConductivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ElectricConductivity.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -265,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); } @@ -273,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); } @@ -281,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); } @@ -289,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); } @@ -297,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); } @@ -305,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); } @@ -316,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); } @@ -377,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); } /// @@ -408,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); } /// @@ -433,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")); /// @@ -441,10 +472,10 @@ public static ElectricConductivityUnit ParseUnit(string str) /// Error parsing string. public static ElectricConductivityUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -459,10 +490,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -478,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; } @@ -519,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 @@ -529,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ElectricConductivity. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ElectricConductivity), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -622,232 +647,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricConductivity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ElectricConductivity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ElectricConductivity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ElectricConductivity otherTyped - && (tolerance is ElectricConductivity toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ElectricConductivity'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ElectricConductivity other, ElectricConductivity tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricConductivity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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)); + #region Conversion Methods (explicit implementations for netstandard2.0) - 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 ElectricConductivityUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricConductivityUnit)} 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(ElectricConductivityUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(ElectricConductivityUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -862,137 +679,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricConductivity)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricConductivity)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricConductivity)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ElectricConductivity)) - return this; - else if (conversionType == typeof(ElectricConductivityUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ElectricConductivity.Info; - else if (conversionType == typeof(BaseDimensions)) - return ElectricConductivity.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ElectricConductivity)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs index 637605c6d2..3e7137a21a 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -58,45 +53,109 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ElectricCurrentInfo: QuantityInfo + { + /// + public ElectricCurrentInfo(string name, ElectricCurrentUnit baseUnit, IEnumerable> unitMappings, ElectricCurrent zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ElectricCurrentInfo(string name, ElectricCurrentUnit baseUnit, IEnumerable> unitMappings, ElectricCurrent zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ElectricCurrent.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ElectricCurrent", typeof(ElectricCurrent).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricCurrent quantity. + /// + /// A new instance of the class with the default settings. + public static ElectricCurrentInfo CreateDefault() + { + return new ElectricCurrentInfo(nameof(ElectricCurrent), DefaultBaseUnit, GetDefaultMappings(), new ElectricCurrent(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricCurrent quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ElectricCurrentInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ElectricCurrentInfo(nameof(ElectricCurrent), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ElectricCurrent(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is I. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, 0, 1, 0, 0, 0); + + /// + /// The default base unit of ElectricCurrent is Ampere. All conversions, as defined in the , go via this value. + /// + public static ElectricCurrentUnit DefaultBaseUnit { get; } = ElectricCurrentUnit.Ampere; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for ElectricCurrent. + public static IEnumerable> 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), + 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() { - BaseDimensions = new BaseDimensions(0, 0, 0, 1, 0, 0, 0); - BaseUnit = ElectricCurrentUnit.Ampere; - Units = Enum.GetValues(typeof(ElectricCurrentUnit)).Cast().ToArray(); - Zero = new ElectricCurrent(0, BaseUnit); - Info = new QuantityInfo("ElectricCurrent", - new UnitInfo[] - { - new UnitInfo(ElectricCurrentUnit.Ampere, "Amperes", new BaseUnits(current: ElectricCurrentUnit.Ampere), "ElectricCurrent"), - new UnitInfo(ElectricCurrentUnit.Centiampere, "Centiamperes", new BaseUnits(current: ElectricCurrentUnit.Centiampere), "ElectricCurrent"), - new UnitInfo(ElectricCurrentUnit.Femtoampere, "Femtoamperes", new BaseUnits(current: ElectricCurrentUnit.Femtoampere), "ElectricCurrent"), - new UnitInfo(ElectricCurrentUnit.Kiloampere, "Kiloamperes", new BaseUnits(current: ElectricCurrentUnit.Kiloampere), "ElectricCurrent"), - new UnitInfo(ElectricCurrentUnit.Megaampere, "Megaamperes", new BaseUnits(current: ElectricCurrentUnit.Megaampere), "ElectricCurrent"), - new UnitInfo(ElectricCurrentUnit.Microampere, "Microamperes", new BaseUnits(current: ElectricCurrentUnit.Microampere), "ElectricCurrent"), - new UnitInfo(ElectricCurrentUnit.Milliampere, "Milliamperes", new BaseUnits(current: ElectricCurrentUnit.Milliampere), "ElectricCurrent"), - new UnitInfo(ElectricCurrentUnit.Nanoampere, "Nanoamperes", new BaseUnits(current: ElectricCurrentUnit.Nanoampere), "ElectricCurrent"), - new UnitInfo(ElectricCurrentUnit.Picoampere, "Picoamperes", new BaseUnits(current: ElectricCurrentUnit.Picoampere), "ElectricCurrent"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricCurrentInfo.CreateDefault); } /// @@ -104,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; @@ -118,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); @@ -129,145 +188,124 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ElectricCurrent, which is Ampere. All conversions go via this value. /// - public static ElectricCurrentUnit BaseUnit { get; } + public static ElectricCurrentUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ElectricCurrent quantity. /// - public static ElectricCurrentUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Ampere. /// - public static ElectricCurrent Zero { get; } - - /// - public static ElectricCurrent AdditiveIdentity => Zero; + public static ElectricCurrent Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ElectricCurrentUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ElectricCurrent.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -296,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); } @@ -304,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); } @@ -312,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); } @@ -320,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); } @@ -328,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); } @@ -336,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); } @@ -344,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); } @@ -352,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); } @@ -360,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); } @@ -371,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); } @@ -432,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); } /// @@ -463,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); } /// @@ -488,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")); /// @@ -496,10 +527,10 @@ public static ElectricCurrentUnit ParseUnit(string str) /// Error parsing string. public static ElectricCurrentUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -514,10 +545,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -533,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; } @@ -607,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ElectricCurrent. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ElectricCurrent), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -700,238 +725,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricCurrent other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ElectricCurrent within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ElectricCurrent other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ElectricCurrent otherTyped - && (tolerance is ElectricCurrent toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ElectricCurrent'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ElectricCurrent other, ElectricCurrent tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricCurrent. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(ElectricCurrentUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(ElectricCurrentUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -946,137 +757,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricCurrent)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricCurrent)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricCurrent)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ElectricCurrent)) - return this; - else if (conversionType == typeof(ElectricCurrentUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ElectricCurrent.Info; - else if (conversionType == typeof(BaseDimensions)) - return ElectricCurrent.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ElectricCurrent)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs index 3515d52d93..b84646bcbb 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,39 +46,91 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static ElectricCurrentDensity() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ElectricCurrentDensityInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(-2, 0, 0, 1, 0, 0, 0); - BaseUnit = ElectricCurrentDensityUnit.AmperePerSquareMeter; - Units = Enum.GetValues(typeof(ElectricCurrentDensityUnit)).Cast().ToArray(); - Zero = new ElectricCurrentDensity(0, BaseUnit); - Info = new QuantityInfo("ElectricCurrentDensity", - new UnitInfo[] - { - new UnitInfo(ElectricCurrentDensityUnit.AmperePerSquareFoot, "AmperesPerSquareFoot", new BaseUnits(length: LengthUnit.Foot, current: ElectricCurrentUnit.Ampere), "ElectricCurrentDensity"), - new UnitInfo(ElectricCurrentDensityUnit.AmperePerSquareInch, "AmperesPerSquareInch", new BaseUnits(length: LengthUnit.Inch, current: ElectricCurrentUnit.Ampere), "ElectricCurrentDensity"), - new UnitInfo(ElectricCurrentDensityUnit.AmperePerSquareMeter, "AmperesPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, current: ElectricCurrentUnit.Ampere), "ElectricCurrentDensity"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public ElectricCurrentDensityInfo(string name, ElectricCurrentDensityUnit baseUnit, IEnumerable> unitMappings, ElectricCurrentDensity zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ElectricCurrentDensityInfo(string name, ElectricCurrentDensityUnit baseUnit, IEnumerable> unitMappings, ElectricCurrentDensity zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ElectricCurrentDensity.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ElectricCurrentDensity", typeof(ElectricCurrentDensity).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the ElectricCurrentDensity quantity. + /// + /// A new instance of the class with the default settings. + public static ElectricCurrentDensityInfo CreateDefault() + { + return new ElectricCurrentDensityInfo(nameof(ElectricCurrentDensity), DefaultBaseUnit, GetDefaultMappings(), new ElectricCurrentDensity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricCurrentDensity quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ElectricCurrentDensityInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ElectricCurrentDensityInfo(nameof(ElectricCurrentDensity), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ElectricCurrentDensity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is L^-2I. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, 0, 0, 1, 0, 0, 0); + + /// + /// The default base unit of ElectricCurrentDensity is AmperePerSquareMeter. All conversions, as defined in the , go via this value. + /// + public static ElectricCurrentDensityUnit DefaultBaseUnit { get; } = ElectricCurrentDensityUnit.AmperePerSquareMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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 = UnitsNetSetup.CreateQuantityInfo(ElectricCurrentDensityInfo.CreateDefault); } /// @@ -91,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; @@ -105,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); @@ -116,103 +163,94 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ElectricCurrentDensity, which is AmperePerSquareMeter. All conversions go via this value. /// - public static ElectricCurrentDensityUnit BaseUnit { get; } + public static ElectricCurrentDensityUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ElectricCurrentDensity quantity. /// - public static ElectricCurrentDensityUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit AmperePerSquareMeter. /// - public static ElectricCurrentDensity Zero { get; } - - /// - public static ElectricCurrentDensity AdditiveIdentity => Zero; + public static ElectricCurrentDensity Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ElectricCurrentDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ElectricCurrentDensity.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -241,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); } @@ -249,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); } @@ -257,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); } @@ -268,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); } @@ -329,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); } /// @@ -360,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); } /// @@ -385,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")); /// @@ -393,10 +424,10 @@ public static ElectricCurrentDensityUnit ParseUnit(string str) /// Error parsing string. public static ElectricCurrentDensityUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -411,10 +442,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -430,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; } @@ -470,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ElectricCurrentDensity. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ElectricCurrentDensity), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -563,226 +588,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricCurrentDensity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ElectricCurrentDensity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ElectricCurrentDensity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ElectricCurrentDensity otherTyped - && (tolerance is ElectricCurrentDensity toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ElectricCurrentDensity'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ElectricCurrentDensity other, ElectricCurrentDensity tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricCurrentDensity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(ElectricCurrentDensityUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(ElectricCurrentDensityUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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), - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -797,137 +620,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricCurrentDensity)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricCurrentDensity)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricCurrentDensity)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ElectricCurrentDensity)) - return this; - else if (conversionType == typeof(ElectricCurrentDensityUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ElectricCurrentDensity.Info; - else if (conversionType == typeof(BaseDimensions)) - return ElectricCurrentDensity.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ElectricCurrentDensity)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs index c2601bedbe..9e81150e9a 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -51,43 +46,103 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static ElectricCurrentGradient() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ElectricCurrentGradientInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(0, 0, -1, 1, 0, 0, 0); - BaseUnit = ElectricCurrentGradientUnit.AmperePerSecond; - Units = Enum.GetValues(typeof(ElectricCurrentGradientUnit)).Cast().ToArray(); - Zero = new ElectricCurrentGradient(0, BaseUnit); - Info = new QuantityInfo("ElectricCurrentGradient", - new UnitInfo[] - { - new UnitInfo(ElectricCurrentGradientUnit.AmperePerMicrosecond, "AmperesPerMicrosecond", new BaseUnits(time: DurationUnit.Microsecond, current: ElectricCurrentUnit.Ampere), "ElectricCurrentGradient"), - new UnitInfo(ElectricCurrentGradientUnit.AmperePerMillisecond, "AmperesPerMillisecond", new BaseUnits(time: DurationUnit.Millisecond, current: ElectricCurrentUnit.Ampere), "ElectricCurrentGradient"), - new UnitInfo(ElectricCurrentGradientUnit.AmperePerMinute, "AmperesPerMinute", new BaseUnits(time: DurationUnit.Minute, current: ElectricCurrentUnit.Ampere), "ElectricCurrentGradient"), - new UnitInfo(ElectricCurrentGradientUnit.AmperePerNanosecond, "AmperesPerNanosecond", new BaseUnits(time: DurationUnit.Nanosecond, current: ElectricCurrentUnit.Ampere), "ElectricCurrentGradient"), - new UnitInfo(ElectricCurrentGradientUnit.AmperePerSecond, "AmperesPerSecond", new BaseUnits(time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricCurrentGradient"), - new UnitInfo(ElectricCurrentGradientUnit.MilliamperePerMinute, "MilliamperesPerMinute", new BaseUnits(time: DurationUnit.Minute, current: ElectricCurrentUnit.Milliampere), "ElectricCurrentGradient"), - new UnitInfo(ElectricCurrentGradientUnit.MilliamperePerSecond, "MilliamperesPerSecond", new BaseUnits(time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere), "ElectricCurrentGradient"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public ElectricCurrentGradientInfo(string name, ElectricCurrentGradientUnit baseUnit, IEnumerable> unitMappings, ElectricCurrentGradient zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ElectricCurrentGradientInfo(string name, ElectricCurrentGradientUnit baseUnit, IEnumerable> unitMappings, ElectricCurrentGradient zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ElectricCurrentGradient.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ElectricCurrentGradient", typeof(ElectricCurrentGradient).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricCurrentGradient quantity. + /// + /// A new instance of the class with the default settings. + public static ElectricCurrentGradientInfo CreateDefault() + { + return new ElectricCurrentGradientInfo(nameof(ElectricCurrentGradient), DefaultBaseUnit, GetDefaultMappings(), new ElectricCurrentGradient(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricCurrentGradient quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ElectricCurrentGradientInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ElectricCurrentGradientInfo(nameof(ElectricCurrentGradient), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ElectricCurrentGradient(0, DefaultBaseUnit), DefaultBaseDimensions); + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// The for is T^-1I. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, -1, 1, 0, 0, 0); + + /// + /// The default base unit of ElectricCurrentGradient is AmperePerSecond. All conversions, as defined in the , go via this value. + /// + public static ElectricCurrentGradientUnit DefaultBaseUnit { get; } = ElectricCurrentGradientUnit.AmperePerSecond; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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), + 60000 + ); + yield return new (ElectricCurrentGradientUnit.MilliamperePerSecond, "MilliamperePerSecond", "MilliamperesPerSecond", new BaseUnits(time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere), + 1000 + ); + } + } + + static ElectricCurrentGradient() + { + Info = UnitsNetSetup.CreateQuantityInfo(ElectricCurrentGradientInfo.CreateDefault); } /// @@ -95,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; @@ -109,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); @@ -120,131 +175,114 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ElectricCurrentGradient, which is AmperePerSecond. All conversions go via this value. /// - public static ElectricCurrentGradientUnit BaseUnit { get; } + public static ElectricCurrentGradientUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ElectricCurrentGradient quantity. /// - public static ElectricCurrentGradientUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit AmperePerSecond. /// - public static ElectricCurrentGradient Zero { get; } - - /// - public static ElectricCurrentGradient AdditiveIdentity => Zero; + public static ElectricCurrentGradient Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ElectricCurrentGradientUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ElectricCurrentGradient.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -273,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); } @@ -281,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); } @@ -289,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); } @@ -297,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); } @@ -305,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); } @@ -313,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); } @@ -321,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); } @@ -332,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); } @@ -393,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); } /// @@ -424,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); } /// @@ -449,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")); /// @@ -457,10 +488,10 @@ public static ElectricCurrentGradientUnit ParseUnit(string str) /// Error parsing string. public static ElectricCurrentGradientUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -475,10 +506,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -494,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; } @@ -544,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ElectricCurrentGradient. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ElectricCurrentGradient), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -637,234 +662,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricCurrentGradient other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ElectricCurrentGradient within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ElectricCurrentGradient other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ElectricCurrentGradient otherTyped - && (tolerance is ElectricCurrentGradient toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ElectricCurrentGradient'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ElectricCurrentGradient other, ElectricCurrentGradient tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricCurrentGradient. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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)); + #region Conversion Methods (explicit implementations for netstandard2.0) - 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 ElectricCurrentGradientUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCurrentGradientUnit)} 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(ElectricCurrentGradientUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(ElectricCurrentGradientUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -879,137 +694,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricCurrentGradient)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricCurrentGradient)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricCurrentGradient)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ElectricCurrentGradient)) - return this; - else if (conversionType == typeof(ElectricCurrentGradientUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ElectricCurrentGradient.Info; - else if (conversionType == typeof(BaseDimensions)) - return ElectricCurrentGradient.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ElectricCurrentGradient)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs index 7a0282e459..82617fdc36 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,37 +46,85 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static ElectricField() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ElectricFieldInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(1, 1, -3, -1, 0, 0, 0); - BaseUnit = ElectricFieldUnit.VoltPerMeter; - Units = Enum.GetValues(typeof(ElectricFieldUnit)).Cast().ToArray(); - Zero = new ElectricField(0, BaseUnit); - Info = new QuantityInfo("ElectricField", - new UnitInfo[] - { - new UnitInfo(ElectricFieldUnit.VoltPerMeter, "VoltsPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricField"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public ElectricFieldInfo(string name, ElectricFieldUnit baseUnit, IEnumerable> unitMappings, ElectricField zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ElectricFieldInfo(string name, ElectricFieldUnit baseUnit, IEnumerable> unitMappings, ElectricField zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ElectricField.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ElectricField", typeof(ElectricField).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the ElectricField quantity. + /// + /// A new instance of the class with the default settings. + public static ElectricFieldInfo CreateDefault() + { + return new ElectricFieldInfo(nameof(ElectricField), DefaultBaseUnit, GetDefaultMappings(), new ElectricField(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricField quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ElectricFieldInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ElectricFieldInfo(nameof(ElectricField), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ElectricField(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-3LMI^-1. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, 1, -3, -1, 0, 0, 0); + + /// + /// The default base unit of ElectricField is VoltPerMeter. All conversions, as defined in the , go via this value. + /// + public static ElectricFieldUnit DefaultBaseUnit { get; } = ElectricFieldUnit.VoltPerMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for ElectricField. + public static IEnumerable> GetDefaultMappings() + { + yield return new (ElectricFieldUnit.VoltPerMeter, "VoltPerMeter", "VoltsPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); + } + } + + static ElectricField() + { + Info = UnitsNetSetup.CreateQuantityInfo(ElectricFieldInfo.CreateDefault); } /// @@ -89,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; @@ -103,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); @@ -114,88 +157,83 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ElectricField, which is VoltPerMeter. All conversions go via this value. /// - public static ElectricFieldUnit BaseUnit { get; } + public static ElectricFieldUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ElectricField quantity. /// - public static ElectricFieldUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit VoltPerMeter. /// - public static ElectricField Zero { get; } - - /// - public static ElectricField AdditiveIdentity => Zero; + public static ElectricField Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ElectricFieldUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ElectricField.BaseDimensions; - #endregion + #region Explicit implementations - #region Conversion Properties + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); - /// - /// Gets a value of this quantity converted into - /// - public double VoltsPerMeter => As(ElectricFieldUnit.VoltPerMeter); + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif #endregion - #region Static Methods + #endregion + + #region Conversion Properties /// - /// Registers the default conversion functions in the given instance. + /// Gets a value of this quantity converted into /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ElectricFieldUnit -> BaseUnit + public QuantityValue VoltsPerMeter => this.As(ElectricFieldUnit.VoltPerMeter); - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ElectricFieldUnit.VoltPerMeter, ElectricFieldUnit.VoltPerMeter, quantity => quantity); + #endregion - // Register in unit converter: BaseUnit -> ElectricFieldUnit - } + #region Static Methods /// /// Get unit abbreviation string. @@ -225,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); } @@ -236,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); } @@ -297,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); } /// @@ -328,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); } /// @@ -353,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")); /// @@ -361,10 +392,10 @@ public static ElectricFieldUnit ParseUnit(string str) /// Error parsing string. public static ElectricFieldUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -379,10 +410,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -398,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; } @@ -438,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ElectricField. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ElectricField), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -531,222 +556,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricField other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ElectricField within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ElectricField other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ElectricField otherTyped - && (tolerance is ElectricField toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ElectricField'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ElectricField other, ElectricField tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricField. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(ElectricFieldUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(ElectricFieldUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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 - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -761,137 +588,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricField)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricField)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricField)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ElectricField)) - return this; - else if (conversionType == typeof(ElectricFieldUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ElectricField.Info; - else if (conversionType == typeof(BaseDimensions)) - return ElectricField.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ElectricField)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricImpedance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricImpedance.g.cs index 49a4f5531b..1d98dc52d5 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricImpedance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricImpedance.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -43,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 @@ -52,44 +47,106 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ElectricImpedanceInfo: QuantityInfo + { + /// + public ElectricImpedanceInfo(string name, ElectricImpedanceUnit baseUnit, IEnumerable> unitMappings, ElectricImpedance zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ElectricImpedanceInfo(string name, ElectricImpedanceUnit baseUnit, IEnumerable> unitMappings, ElectricImpedance zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ElectricImpedance.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ElectricImpedance", typeof(ElectricImpedance).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricImpedance quantity. + /// + /// A new instance of the class with the default settings. + public static ElectricImpedanceInfo CreateDefault() + { + return new ElectricImpedanceInfo(nameof(ElectricImpedance), DefaultBaseUnit, GetDefaultMappings(), new ElectricImpedance(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricImpedance quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ElectricImpedanceInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ElectricImpedanceInfo(nameof(ElectricImpedance), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ElectricImpedance(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-3L^2MI^-2. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -3, -2, 0, 0, 0); + + /// + /// The default base unit of ElectricImpedance is Ohm. All conversions, as defined in the , go via this value. + /// + public static ElectricImpedanceUnit DefaultBaseUnit { get; } = ElectricImpedanceUnit.Ohm; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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), + new QuantityValue(1, 1000000000000) + ); + } + } + static ElectricImpedance() { - BaseDimensions = new BaseDimensions(2, 1, -3, -2, 0, 0, 0); - BaseUnit = ElectricImpedanceUnit.Ohm; - Units = Enum.GetValues(typeof(ElectricImpedanceUnit)).Cast().ToArray(); - Zero = new ElectricImpedance(0, BaseUnit); - Info = new QuantityInfo("ElectricImpedance", - new UnitInfo[] - { - new UnitInfo(ElectricImpedanceUnit.Gigaohm, "Gigaohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond, current: ElectricCurrentUnit.Ampere), "ElectricImpedance"), - new UnitInfo(ElectricImpedanceUnit.Kiloohm, "Kiloohms", BaseUnits.Undefined, "ElectricImpedance"), - new UnitInfo(ElectricImpedanceUnit.Megaohm, "Megaohms", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricImpedance"), - new UnitInfo(ElectricImpedanceUnit.Microohm, "Microohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricImpedance"), - new UnitInfo(ElectricImpedanceUnit.Milliohm, "Milliohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricImpedance"), - new UnitInfo(ElectricImpedanceUnit.Nanoohm, "Nanoohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricImpedance"), - new UnitInfo(ElectricImpedanceUnit.Ohm, "Ohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricImpedance"), - new UnitInfo(ElectricImpedanceUnit.Teraohm, "Teraohms", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricImpedance"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricImpedanceInfo.CreateDefault); } /// @@ -97,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; @@ -111,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); @@ -122,138 +179,119 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ElectricImpedance, which is Ohm. All conversions go via this value. /// - public static ElectricImpedanceUnit BaseUnit { get; } + public static ElectricImpedanceUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ElectricImpedance quantity. /// - public static ElectricImpedanceUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Ohm. /// - public static ElectricImpedance Zero { get; } - - /// - public static ElectricImpedance AdditiveIdentity => Zero; + public static ElectricImpedance Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ElectricImpedanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ElectricImpedance.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -282,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); } @@ -290,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); } @@ -298,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); } @@ -306,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); } @@ -314,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); } @@ -322,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); } @@ -330,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); } @@ -338,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); } @@ -349,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); } @@ -410,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); } /// @@ -441,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); } /// @@ -466,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")); /// @@ -474,10 +505,10 @@ public static ElectricImpedanceUnit ParseUnit(string str) /// Error parsing string. public static ElectricImpedanceUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -492,10 +523,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -511,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; } @@ -551,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ElectricImpedance. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ElectricImpedance), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -644,236 +669,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricImpedance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ElectricImpedance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ElectricImpedance other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ElectricImpedance otherTyped - && (tolerance is ElectricImpedance toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ElectricImpedance'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ElectricImpedance other, ElectricImpedance tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricImpedance. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(ElectricImpedanceUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(ElectricImpedanceUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -888,137 +701,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricImpedance)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricImpedance)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricImpedance)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ElectricImpedance)) - return this; - else if (conversionType == typeof(ElectricImpedanceUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ElectricImpedance.Info; - else if (conversionType == typeof(BaseDimensions)) - return ElectricImpedance.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ElectricImpedance)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs index 72b452c4ac..5f226531d5 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,41 +46,97 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static ElectricInductance() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ElectricInductanceInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(2, 1, -2, -2, 0, 0, 0); - BaseUnit = ElectricInductanceUnit.Henry; - Units = Enum.GetValues(typeof(ElectricInductanceUnit)).Cast().ToArray(); - Zero = new ElectricInductance(0, BaseUnit); - Info = new QuantityInfo("ElectricInductance", - new UnitInfo[] - { - new UnitInfo(ElectricInductanceUnit.Henry, "Henries", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricInductance"), - new UnitInfo(ElectricInductanceUnit.Microhenry, "Microhenries", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricInductance"), - new UnitInfo(ElectricInductanceUnit.Millihenry, "Millihenries", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricInductance"), - new UnitInfo(ElectricInductanceUnit.Nanohenry, "Nanohenries", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricInductance"), - new UnitInfo(ElectricInductanceUnit.Picohenry, "Picohenries", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Nanogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricInductance"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public ElectricInductanceInfo(string name, ElectricInductanceUnit baseUnit, IEnumerable> unitMappings, ElectricInductance zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ElectricInductanceInfo(string name, ElectricInductanceUnit baseUnit, IEnumerable> unitMappings, ElectricInductance zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ElectricInductance.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ElectricInductance", typeof(ElectricInductance).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricInductance quantity. + /// + /// A new instance of the class with the default settings. + public static ElectricInductanceInfo CreateDefault() + { + return new ElectricInductanceInfo(nameof(ElectricInductance), DefaultBaseUnit, GetDefaultMappings(), new ElectricInductance(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricInductance quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ElectricInductanceInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ElectricInductanceInfo(nameof(ElectricInductance), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ElectricInductance(0, DefaultBaseUnit), DefaultBaseDimensions); + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// The for is T^-2L^2MI^-2. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -2, -2, 0, 0, 0); + + /// + /// The default base unit of ElectricInductance is Henry. All conversions, as defined in the , go via this value. + /// + public static ElectricInductanceUnit DefaultBaseUnit { get; } = ElectricInductanceUnit.Henry; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for ElectricInductance. + public static IEnumerable> 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), + 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 = UnitsNetSetup.CreateQuantityInfo(ElectricInductanceInfo.CreateDefault); } /// @@ -93,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; @@ -107,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); @@ -118,117 +169,104 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ElectricInductance, which is Henry. All conversions go via this value. /// - public static ElectricInductanceUnit BaseUnit { get; } + public static ElectricInductanceUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ElectricInductance quantity. /// - public static ElectricInductanceUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Henry. /// - public static ElectricInductance Zero { get; } - - /// - public static ElectricInductance AdditiveIdentity => Zero; + public static ElectricInductance Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ElectricInductanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ElectricInductance.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -257,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); } @@ -265,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); } @@ -273,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); } @@ -281,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); } @@ -289,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); } @@ -300,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); } @@ -361,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); } /// @@ -392,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); } /// @@ -417,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")); /// @@ -425,10 +456,10 @@ public static ElectricInductanceUnit ParseUnit(string str) /// Error parsing string. public static ElectricInductanceUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -443,10 +474,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -462,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; } @@ -502,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ElectricInductance. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ElectricInductance), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -595,230 +620,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricInductance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ElectricInductance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ElectricInductance other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ElectricInductance otherTyped - && (tolerance is ElectricInductance toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ElectricInductance'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ElectricInductance other, ElectricInductance tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricInductance. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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)); + #region Conversion Methods (explicit implementations for netstandard2.0) - 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 ElectricInductanceUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricInductanceUnit)} 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(ElectricInductanceUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(ElectricInductanceUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -833,137 +652,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricInductance)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricInductance)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricInductance)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ElectricInductance)) - return this; - else if (conversionType == typeof(ElectricInductanceUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ElectricInductance.Info; - else if (conversionType == typeof(BaseDimensions)) - return ElectricInductance.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ElectricInductance)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs index 8e16e66487..da86bced03 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -57,42 +52,100 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static ElectricPotential() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ElectricPotentialInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(2, 1, -3, -1, 0, 0, 0); - BaseUnit = ElectricPotentialUnit.Volt; - Units = Enum.GetValues(typeof(ElectricPotentialUnit)).Cast().ToArray(); - Zero = new ElectricPotential(0, BaseUnit); - Info = new QuantityInfo("ElectricPotential", - new UnitInfo[] - { - new UnitInfo(ElectricPotentialUnit.Kilovolt, "Kilovolts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere), "ElectricPotential"), - new UnitInfo(ElectricPotentialUnit.Megavolt, "Megavolts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Microampere), "ElectricPotential"), - new UnitInfo(ElectricPotentialUnit.Microvolt, "Microvolts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricPotential"), - new UnitInfo(ElectricPotentialUnit.Millivolt, "Millivolts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricPotential"), - new UnitInfo(ElectricPotentialUnit.Nanovolt, "Nanovolts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricPotential"), - new UnitInfo(ElectricPotentialUnit.Volt, "Volts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricPotential"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public ElectricPotentialInfo(string name, ElectricPotentialUnit baseUnit, IEnumerable> unitMappings, ElectricPotential zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ElectricPotentialInfo(string name, ElectricPotentialUnit baseUnit, IEnumerable> unitMappings, ElectricPotential zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ElectricPotential.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ElectricPotential", typeof(ElectricPotential).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricPotential quantity. + /// + /// A new instance of the class with the default settings. + public static ElectricPotentialInfo CreateDefault() + { + return new ElectricPotentialInfo(nameof(ElectricPotential), DefaultBaseUnit, GetDefaultMappings(), new ElectricPotential(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricPotential quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ElectricPotentialInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ElectricPotentialInfo(nameof(ElectricPotential), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ElectricPotential(0, DefaultBaseUnit), DefaultBaseDimensions); + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// The for is T^-3L^2MI^-1. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -3, -1, 0, 0, 0); + + /// + /// The default base unit of ElectricPotential is Volt. All conversions, as defined in the , go via this value. + /// + public static ElectricPotentialUnit DefaultBaseUnit { get; } = ElectricPotentialUnit.Volt; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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 = UnitsNetSetup.CreateQuantityInfo(ElectricPotentialInfo.CreateDefault); } /// @@ -100,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; @@ -114,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); @@ -125,124 +178,109 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ElectricPotential, which is Volt. All conversions go via this value. /// - public static ElectricPotentialUnit BaseUnit { get; } + public static ElectricPotentialUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ElectricPotential quantity. /// - public static ElectricPotentialUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Volt. /// - public static ElectricPotential Zero { get; } - - /// - public static ElectricPotential AdditiveIdentity => Zero; + public static ElectricPotential Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ElectricPotentialUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ElectricPotential.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -271,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); } @@ -279,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); } @@ -287,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); } @@ -295,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); } @@ -303,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); } @@ -311,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); } @@ -322,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); } @@ -383,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); } /// @@ -414,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); } /// @@ -439,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")); /// @@ -447,10 +478,10 @@ public static ElectricPotentialUnit ParseUnit(string str) /// Error parsing string. public static ElectricPotentialUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -465,10 +496,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -484,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; } @@ -552,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ElectricPotential. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ElectricPotential), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -645,232 +670,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricPotential other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ElectricPotential within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ElectricPotential other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ElectricPotential otherTyped - && (tolerance is ElectricPotential toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ElectricPotential'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ElectricPotential other, ElectricPotential tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricPotential. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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)); + #region Conversion Methods (explicit implementations for netstandard2.0) - 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 ElectricPotentialUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialUnit)} 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(ElectricPotentialUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(ElectricPotentialUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -885,137 +702,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricPotential)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricPotential)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricPotential)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ElectricPotential)) - return this; - else if (conversionType == typeof(ElectricPotentialUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ElectricPotential.Info; - else if (conversionType == typeof(BaseDimensions)) - return ElectricPotential.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ElectricPotential)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs index 691a696708..b977e95bb4 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -48,56 +43,142 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ElectricPotentialChangeRateInfo: QuantityInfo + { + /// + public ElectricPotentialChangeRateInfo(string name, ElectricPotentialChangeRateUnit baseUnit, IEnumerable> unitMappings, ElectricPotentialChangeRate zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ElectricPotentialChangeRateInfo(string name, ElectricPotentialChangeRateUnit baseUnit, IEnumerable> unitMappings, ElectricPotentialChangeRate zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ElectricPotentialChangeRate.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ElectricPotentialChangeRate", typeof(ElectricPotentialChangeRate).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricPotentialChangeRate quantity. + /// + /// A new instance of the class with the default settings. + public static ElectricPotentialChangeRateInfo CreateDefault() + { + return new ElectricPotentialChangeRateInfo(nameof(ElectricPotentialChangeRate), DefaultBaseUnit, GetDefaultMappings(), new ElectricPotentialChangeRate(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricPotentialChangeRate quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ElectricPotentialChangeRateInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ElectricPotentialChangeRateInfo(nameof(ElectricPotentialChangeRate), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ElectricPotentialChangeRate(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-4L^2MI^-1. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -4, -1, 0, 0, 0); + + /// + /// The default base unit of ElectricPotentialChangeRate is VoltPerSecond. All conversions, as defined in the , go via this value. + /// + public static ElectricPotentialChangeRateUnit DefaultBaseUnit { get; } = ElectricPotentialChangeRateUnit.VoltPerSecond; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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() { - BaseDimensions = new BaseDimensions(2, 1, -4, -1, 0, 0, 0); - BaseUnit = ElectricPotentialChangeRateUnit.VoltPerSecond; - Units = Enum.GetValues(typeof(ElectricPotentialChangeRateUnit)).Cast().ToArray(); - Zero = new ElectricPotentialChangeRate(0, BaseUnit); - Info = new QuantityInfo("ElectricPotentialChangeRate", - new UnitInfo[] - { - new UnitInfo(ElectricPotentialChangeRateUnit.KilovoltPerHour, "KilovoltsPerHour", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Hour, current: ElectricCurrentUnit.Milliampere), "ElectricPotentialChangeRate"), - new UnitInfo(ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond, "KilovoltsPerMicrosecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Microsecond, current: ElectricCurrentUnit.Milliampere), "ElectricPotentialChangeRate"), - new UnitInfo(ElectricPotentialChangeRateUnit.KilovoltPerMinute, "KilovoltsPerMinute", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Minute, current: ElectricCurrentUnit.Milliampere), "ElectricPotentialChangeRate"), - new UnitInfo(ElectricPotentialChangeRateUnit.KilovoltPerSecond, "KilovoltsPerSecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere), "ElectricPotentialChangeRate"), - new UnitInfo(ElectricPotentialChangeRateUnit.MegavoltPerHour, "MegavoltsPerHour", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Hour, current: ElectricCurrentUnit.Microampere), "ElectricPotentialChangeRate"), - new UnitInfo(ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond, "MegavoltsPerMicrosecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Microsecond, current: ElectricCurrentUnit.Microampere), "ElectricPotentialChangeRate"), - new UnitInfo(ElectricPotentialChangeRateUnit.MegavoltPerMinute, "MegavoltsPerMinute", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Minute, current: ElectricCurrentUnit.Microampere), "ElectricPotentialChangeRate"), - new UnitInfo(ElectricPotentialChangeRateUnit.MegavoltPerSecond, "MegavoltsPerSecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Microampere), "ElectricPotentialChangeRate"), - new UnitInfo(ElectricPotentialChangeRateUnit.MicrovoltPerHour, "MicrovoltsPerHour", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Hour, current: ElectricCurrentUnit.Ampere), "ElectricPotentialChangeRate"), - new UnitInfo(ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond, "MicrovoltsPerMicrosecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Microsecond, current: ElectricCurrentUnit.Ampere), "ElectricPotentialChangeRate"), - new UnitInfo(ElectricPotentialChangeRateUnit.MicrovoltPerMinute, "MicrovoltsPerMinute", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Minute, current: ElectricCurrentUnit.Ampere), "ElectricPotentialChangeRate"), - new UnitInfo(ElectricPotentialChangeRateUnit.MicrovoltPerSecond, "MicrovoltsPerSecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricPotentialChangeRate"), - new UnitInfo(ElectricPotentialChangeRateUnit.MillivoltPerHour, "MillivoltsPerHour", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Hour, current: ElectricCurrentUnit.Ampere), "ElectricPotentialChangeRate"), - new UnitInfo(ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond, "MillivoltsPerMicrosecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Microsecond, current: ElectricCurrentUnit.Ampere), "ElectricPotentialChangeRate"), - new UnitInfo(ElectricPotentialChangeRateUnit.MillivoltPerMinute, "MillivoltsPerMinute", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Minute, current: ElectricCurrentUnit.Ampere), "ElectricPotentialChangeRate"), - new UnitInfo(ElectricPotentialChangeRateUnit.MillivoltPerSecond, "MillivoltsPerSecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricPotentialChangeRate"), - new UnitInfo(ElectricPotentialChangeRateUnit.VoltPerHour, "VoltsPerHour", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Hour, current: ElectricCurrentUnit.Ampere), "ElectricPotentialChangeRate"), - new UnitInfo(ElectricPotentialChangeRateUnit.VoltPerMicrosecond, "VoltsPerMicrosecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Microsecond, current: ElectricCurrentUnit.Ampere), "ElectricPotentialChangeRate"), - new UnitInfo(ElectricPotentialChangeRateUnit.VoltPerMinute, "VoltsPerMinute", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Minute, current: ElectricCurrentUnit.Ampere), "ElectricPotentialChangeRate"), - new UnitInfo(ElectricPotentialChangeRateUnit.VoltPerSecond, "VoltsPerSecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricPotentialChangeRate"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricPotentialChangeRateInfo.CreateDefault); } /// @@ -105,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; @@ -119,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); @@ -130,222 +211,179 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ElectricPotentialChangeRate, which is VoltPerSecond. All conversions go via this value. /// - public static ElectricPotentialChangeRateUnit BaseUnit { get; } + public static ElectricPotentialChangeRateUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ElectricPotentialChangeRate quantity. /// - public static ElectricPotentialChangeRateUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit VoltPerSecond. /// - public static ElectricPotentialChangeRate Zero { get; } - - /// - public static ElectricPotentialChangeRate AdditiveIdentity => Zero; + public static ElectricPotentialChangeRate Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ElectricPotentialChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ElectricPotentialChangeRate.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -374,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); } @@ -382,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); } @@ -390,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); } @@ -398,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); } @@ -406,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); } @@ -414,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); } @@ -422,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); } @@ -430,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); } @@ -438,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); } @@ -446,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); } @@ -454,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); } @@ -462,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); } @@ -470,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); } @@ -478,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); } @@ -486,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); } @@ -494,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); } @@ -502,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); } @@ -510,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); } @@ -518,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); } @@ -526,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); } @@ -537,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); } @@ -598,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); } /// @@ -629,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); } /// @@ -654,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")); /// @@ -662,10 +693,10 @@ public static ElectricPotentialChangeRateUnit ParseUnit(string str) /// Error parsing string. public static ElectricPotentialChangeRateUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -680,10 +711,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -699,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; } @@ -739,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ElectricPotentialChangeRate. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ElectricPotentialChangeRate), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -832,260 +857,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricPotentialChangeRate other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ElectricPotentialChangeRate within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ElectricPotentialChangeRate other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ElectricPotentialChangeRate otherTyped - && (tolerance is ElectricPotentialChangeRate toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ElectricPotentialChangeRate'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ElectricPotentialChangeRate other, ElectricPotentialChangeRate tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricPotentialChangeRate. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(ElectricPotentialChangeRateUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(ElectricPotentialChangeRateUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1100,137 +889,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricPotentialChangeRate)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricPotentialChangeRate)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricPotentialChangeRate)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ElectricPotentialChangeRate)) - return this; - else if (conversionType == typeof(ElectricPotentialChangeRateUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ElectricPotentialChangeRate.Info; - else if (conversionType == typeof(BaseDimensions)) - return ElectricPotentialChangeRate.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ElectricPotentialChangeRate)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricReactance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricReactance.g.cs index 246fa5283e..fae1b87660 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricReactance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricReactance.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,44 +46,106 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ElectricReactanceInfo: QuantityInfo + { + /// + public ElectricReactanceInfo(string name, ElectricReactanceUnit baseUnit, IEnumerable> unitMappings, ElectricReactance zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ElectricReactanceInfo(string name, ElectricReactanceUnit baseUnit, IEnumerable> unitMappings, ElectricReactance zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ElectricReactance.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ElectricReactance", typeof(ElectricReactance).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricReactance quantity. + /// + /// A new instance of the class with the default settings. + public static ElectricReactanceInfo CreateDefault() + { + return new ElectricReactanceInfo(nameof(ElectricReactance), DefaultBaseUnit, GetDefaultMappings(), new ElectricReactance(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricReactance quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ElectricReactanceInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ElectricReactanceInfo(nameof(ElectricReactance), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ElectricReactance(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-3L^2MI^-2. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -3, -2, 0, 0, 0); + + /// + /// The default base unit of ElectricReactance is Ohm. All conversions, as defined in the , go via this value. + /// + public static ElectricReactanceUnit DefaultBaseUnit { get; } = ElectricReactanceUnit.Ohm; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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), + new QuantityValue(1, 1000000000000) + ); + } + } + static ElectricReactance() { - BaseDimensions = new BaseDimensions(2, 1, -3, -2, 0, 0, 0); - BaseUnit = ElectricReactanceUnit.Ohm; - Units = Enum.GetValues(typeof(ElectricReactanceUnit)).Cast().ToArray(); - Zero = new ElectricReactance(0, BaseUnit); - Info = new QuantityInfo("ElectricReactance", - new UnitInfo[] - { - new UnitInfo(ElectricReactanceUnit.Gigaohm, "Gigaohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond, current: ElectricCurrentUnit.Ampere), "ElectricReactance"), - new UnitInfo(ElectricReactanceUnit.Kiloohm, "Kiloohms", BaseUnits.Undefined, "ElectricReactance"), - new UnitInfo(ElectricReactanceUnit.Megaohm, "Megaohms", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricReactance"), - new UnitInfo(ElectricReactanceUnit.Microohm, "Microohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricReactance"), - new UnitInfo(ElectricReactanceUnit.Milliohm, "Milliohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricReactance"), - new UnitInfo(ElectricReactanceUnit.Nanoohm, "Nanoohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricReactance"), - new UnitInfo(ElectricReactanceUnit.Ohm, "Ohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricReactance"), - new UnitInfo(ElectricReactanceUnit.Teraohm, "Teraohms", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricReactance"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricReactanceInfo.CreateDefault); } /// @@ -96,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; @@ -110,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); @@ -121,138 +178,119 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ElectricReactance, which is Ohm. All conversions go via this value. /// - public static ElectricReactanceUnit BaseUnit { get; } + public static ElectricReactanceUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ElectricReactance quantity. /// - public static ElectricReactanceUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Ohm. /// - public static ElectricReactance Zero { get; } - - /// - public static ElectricReactance AdditiveIdentity => Zero; + public static ElectricReactance Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ElectricReactanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ElectricReactance.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -281,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); } @@ -289,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); } @@ -297,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); } @@ -305,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); } @@ -313,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); } @@ -321,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); } @@ -329,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); } @@ -337,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); } @@ -348,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); } @@ -409,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); } /// @@ -440,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); } /// @@ -465,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")); /// @@ -473,10 +504,10 @@ public static ElectricReactanceUnit ParseUnit(string str) /// Error parsing string. public static ElectricReactanceUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -491,10 +522,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -510,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; } @@ -550,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ElectricReactance. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ElectricReactance), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -643,236 +668,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricReactance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ElectricReactance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ElectricReactance other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ElectricReactance otherTyped - && (tolerance is ElectricReactance toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ElectricReactance'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ElectricReactance other, ElectricReactance tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricReactance. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(ElectricReactanceUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - /// 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); - } + IQuantity IQuantity.ToUnit(ElectricReactanceUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(ElectricReactanceUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -887,137 +700,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricReactance)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricReactance)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricReactance)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ElectricReactance)) - return this; - else if (conversionType == typeof(ElectricReactanceUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ElectricReactance.Info; - else if (conversionType == typeof(BaseDimensions)) - return ElectricReactance.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ElectricReactance)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricReactiveEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricReactiveEnergy.g.cs index 1e6ce1b120..358d66d8c0 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricReactiveEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricReactiveEnergy.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -48,39 +43,91 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static ElectricReactiveEnergy() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ElectricReactiveEnergyInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); - BaseUnit = ElectricReactiveEnergyUnit.VoltampereReactiveHour; - Units = Enum.GetValues(typeof(ElectricReactiveEnergyUnit)).Cast().ToArray(); - Zero = new ElectricReactiveEnergy(0, BaseUnit); - Info = new QuantityInfo("ElectricReactiveEnergy", - new UnitInfo[] - { - new UnitInfo(ElectricReactiveEnergyUnit.KilovoltampereReactiveHour, "KilovoltampereReactiveHours", BaseUnits.Undefined, "ElectricReactiveEnergy"), - new UnitInfo(ElectricReactiveEnergyUnit.MegavoltampereReactiveHour, "MegavoltampereReactiveHours", BaseUnits.Undefined, "ElectricReactiveEnergy"), - new UnitInfo(ElectricReactiveEnergyUnit.VoltampereReactiveHour, "VoltampereReactiveHours", BaseUnits.Undefined, "ElectricReactiveEnergy"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public ElectricReactiveEnergyInfo(string name, ElectricReactiveEnergyUnit baseUnit, IEnumerable> unitMappings, ElectricReactiveEnergy zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ElectricReactiveEnergyInfo(string name, ElectricReactiveEnergyUnit baseUnit, IEnumerable> unitMappings, ElectricReactiveEnergy zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ElectricReactiveEnergy.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ElectricReactiveEnergy", typeof(ElectricReactiveEnergy).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the ElectricReactiveEnergy quantity. + /// + /// A new instance of the class with the default settings. + public static ElectricReactiveEnergyInfo CreateDefault() + { + return new ElectricReactiveEnergyInfo(nameof(ElectricReactiveEnergy), DefaultBaseUnit, GetDefaultMappings(), new ElectricReactiveEnergy(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricReactiveEnergy quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ElectricReactiveEnergyInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ElectricReactiveEnergyInfo(nameof(ElectricReactiveEnergy), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ElectricReactiveEnergy(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-2L^2M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); + + /// + /// The default base unit of ElectricReactiveEnergy is VoltampereReactiveHour. All conversions, as defined in the , go via this value. + /// + public static ElectricReactiveEnergyUnit DefaultBaseUnit { get; } = ElectricReactiveEnergyUnit.VoltampereReactiveHour; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for ElectricReactiveEnergy. + public static IEnumerable> GetDefaultMappings() + { + 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 = UnitsNetSetup.CreateQuantityInfo(ElectricReactiveEnergyInfo.CreateDefault); } /// @@ -88,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; @@ -102,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); @@ -113,103 +160,94 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ElectricReactiveEnergy, which is VoltampereReactiveHour. All conversions go via this value. /// - public static ElectricReactiveEnergyUnit BaseUnit { get; } + public static ElectricReactiveEnergyUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ElectricReactiveEnergy quantity. /// - public static ElectricReactiveEnergyUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereReactiveHour. /// - public static ElectricReactiveEnergy Zero { get; } - - /// - public static ElectricReactiveEnergy AdditiveIdentity => Zero; + public static ElectricReactiveEnergy Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ElectricReactiveEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ElectricReactiveEnergy.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -238,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); } @@ -246,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); } @@ -254,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); } @@ -265,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); } @@ -326,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); } /// @@ -357,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); } /// @@ -382,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")); /// @@ -390,10 +421,10 @@ public static ElectricReactiveEnergyUnit ParseUnit(string str) /// Error parsing string. public static ElectricReactiveEnergyUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -408,10 +439,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -427,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; } @@ -467,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ElectricReactiveEnergy. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ElectricReactiveEnergy), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -560,226 +585,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricReactiveEnergy other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ElectricReactiveEnergy within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ElectricReactiveEnergy other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ElectricReactiveEnergy otherTyped - && (tolerance is ElectricReactiveEnergy toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ElectricReactiveEnergy'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ElectricReactiveEnergy other, ElectricReactiveEnergy tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricReactiveEnergy. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(ElectricReactiveEnergyUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(ElectricReactiveEnergyUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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), - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -794,137 +617,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricReactiveEnergy)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricReactiveEnergy)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricReactiveEnergy)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ElectricReactiveEnergy)) - return this; - else if (conversionType == typeof(ElectricReactiveEnergyUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ElectricReactiveEnergy.Info; - else if (conversionType == typeof(BaseDimensions)) - return ElectricReactiveEnergy.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ElectricReactiveEnergy)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricReactivePower.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricReactivePower.g.cs index d16c1b0288..d46f6a9a74 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricReactivePower.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricReactivePower.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,40 +46,94 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static ElectricReactivePower() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ElectricReactivePowerInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); - BaseUnit = ElectricReactivePowerUnit.VoltampereReactive; - Units = Enum.GetValues(typeof(ElectricReactivePowerUnit)).Cast().ToArray(); - Zero = new ElectricReactivePower(0, BaseUnit); - Info = new QuantityInfo("ElectricReactivePower", - new UnitInfo[] - { - new UnitInfo(ElectricReactivePowerUnit.GigavoltampereReactive, "GigavoltamperesReactive", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond), "ElectricReactivePower"), - new UnitInfo(ElectricReactivePowerUnit.KilovoltampereReactive, "KilovoltamperesReactive", BaseUnits.Undefined, "ElectricReactivePower"), - new UnitInfo(ElectricReactivePowerUnit.MegavoltampereReactive, "MegavoltamperesReactive", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "ElectricReactivePower"), - new UnitInfo(ElectricReactivePowerUnit.VoltampereReactive, "VoltamperesReactive", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "ElectricReactivePower"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public ElectricReactivePowerInfo(string name, ElectricReactivePowerUnit baseUnit, IEnumerable> unitMappings, ElectricReactivePower zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ElectricReactivePowerInfo(string name, ElectricReactivePowerUnit baseUnit, IEnumerable> unitMappings, ElectricReactivePower zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ElectricReactivePower.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ElectricReactivePower", typeof(ElectricReactivePower).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the ElectricReactivePower quantity. + /// + /// A new instance of the class with the default settings. + public static ElectricReactivePowerInfo CreateDefault() + { + return new ElectricReactivePowerInfo(nameof(ElectricReactivePower), DefaultBaseUnit, GetDefaultMappings(), new ElectricReactivePower(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricReactivePower quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ElectricReactivePowerInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ElectricReactivePowerInfo(nameof(ElectricReactivePower), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ElectricReactivePower(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-3L^2M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); + + /// + /// The default base unit of ElectricReactivePower is VoltampereReactive. All conversions, as defined in the , go via this value. + /// + public static ElectricReactivePowerUnit DefaultBaseUnit { get; } = ElectricReactivePowerUnit.VoltampereReactive; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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 = UnitsNetSetup.CreateQuantityInfo(ElectricReactivePowerInfo.CreateDefault); } /// @@ -92,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; @@ -106,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); @@ -117,110 +166,99 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ElectricReactivePower, which is VoltampereReactive. All conversions go via this value. /// - public static ElectricReactivePowerUnit BaseUnit { get; } + public static ElectricReactivePowerUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ElectricReactivePower quantity. /// - public static ElectricReactivePowerUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereReactive. /// - public static ElectricReactivePower Zero { get; } - - /// - public static ElectricReactivePower AdditiveIdentity => Zero; + public static ElectricReactivePower Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ElectricReactivePowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ElectricReactivePower.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -249,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); } @@ -257,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); } @@ -265,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); } @@ -273,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); } @@ -284,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); } @@ -345,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); } /// @@ -376,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); } /// @@ -401,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")); /// @@ -409,10 +440,10 @@ public static ElectricReactivePowerUnit ParseUnit(string str) /// Error parsing string. public static ElectricReactivePowerUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -427,10 +458,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -446,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; } @@ -486,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ElectricReactivePower. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ElectricReactivePower), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -579,228 +604,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricReactivePower other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ElectricReactivePower within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ElectricReactivePower other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ElectricReactivePower otherTyped - && (tolerance is ElectricReactivePower toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ElectricReactivePower'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ElectricReactivePower other, ElectricReactivePower tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricReactivePower. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(ElectricReactivePowerUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(ElectricReactivePowerUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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), - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -815,137 +636,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricReactivePower)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricReactivePower)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricReactivePower)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ElectricReactivePower)) - return this; - else if (conversionType == typeof(ElectricReactivePowerUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ElectricReactivePower.Info; - else if (conversionType == typeof(BaseDimensions)) - return ElectricReactivePower.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ElectricReactivePower)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs index 3b475ee618..ac49ccdcfb 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -54,44 +49,106 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ElectricResistanceInfo: QuantityInfo + { + /// + public ElectricResistanceInfo(string name, ElectricResistanceUnit baseUnit, IEnumerable> unitMappings, ElectricResistance zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ElectricResistanceInfo(string name, ElectricResistanceUnit baseUnit, IEnumerable> unitMappings, ElectricResistance zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ElectricResistance.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ElectricResistance", typeof(ElectricResistance).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricResistance quantity. + /// + /// A new instance of the class with the default settings. + public static ElectricResistanceInfo CreateDefault() + { + return new ElectricResistanceInfo(nameof(ElectricResistance), DefaultBaseUnit, GetDefaultMappings(), new ElectricResistance(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricResistance quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ElectricResistanceInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ElectricResistanceInfo(nameof(ElectricResistance), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ElectricResistance(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-3L^2MI^-2. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -3, -2, 0, 0, 0); + + /// + /// The default base unit of ElectricResistance is Ohm. All conversions, as defined in the , go via this value. + /// + public static ElectricResistanceUnit DefaultBaseUnit { get; } = ElectricResistanceUnit.Ohm; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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), + new QuantityValue(1, 1000000000000) + ); + } + } + static ElectricResistance() { - BaseDimensions = new BaseDimensions(2, 1, -3, -2, 0, 0, 0); - BaseUnit = ElectricResistanceUnit.Ohm; - Units = Enum.GetValues(typeof(ElectricResistanceUnit)).Cast().ToArray(); - Zero = new ElectricResistance(0, BaseUnit); - Info = new QuantityInfo("ElectricResistance", - new UnitInfo[] - { - new UnitInfo(ElectricResistanceUnit.Gigaohm, "Gigaohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond, current: ElectricCurrentUnit.Ampere), "ElectricResistance"), - new UnitInfo(ElectricResistanceUnit.Kiloohm, "Kiloohms", BaseUnits.Undefined, "ElectricResistance"), - new UnitInfo(ElectricResistanceUnit.Megaohm, "Megaohms", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricResistance"), - new UnitInfo(ElectricResistanceUnit.Microohm, "Microohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricResistance"), - new UnitInfo(ElectricResistanceUnit.Milliohm, "Milliohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricResistance"), - new UnitInfo(ElectricResistanceUnit.Nanoohm, "Nanoohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricResistance"), - new UnitInfo(ElectricResistanceUnit.Ohm, "Ohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricResistance"), - new UnitInfo(ElectricResistanceUnit.Teraohm, "Teraohms", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricResistance"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricResistanceInfo.CreateDefault); } /// @@ -99,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; @@ -113,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); @@ -124,138 +181,119 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ElectricResistance, which is Ohm. All conversions go via this value. /// - public static ElectricResistanceUnit BaseUnit { get; } + public static ElectricResistanceUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ElectricResistance quantity. /// - public static ElectricResistanceUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Ohm. /// - public static ElectricResistance Zero { get; } - - /// - public static ElectricResistance AdditiveIdentity => Zero; + public static ElectricResistance Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ElectricResistanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ElectricResistance.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -284,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); } @@ -292,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); } @@ -300,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); } @@ -308,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); } @@ -316,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); } @@ -324,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); } @@ -332,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); } @@ -340,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); } @@ -351,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); } @@ -412,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); } /// @@ -443,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); } /// @@ -468,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")); /// @@ -476,10 +507,10 @@ public static ElectricResistanceUnit ParseUnit(string str) /// Error parsing string. public static ElectricResistanceUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -494,10 +525,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -513,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; } @@ -563,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ElectricResistance. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ElectricResistance), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -656,236 +681,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricResistance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ElectricResistance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ElectricResistance other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ElectricResistance otherTyped - && (tolerance is ElectricResistance toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ElectricResistance'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ElectricResistance other, ElectricResistance tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricResistance. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(ElectricResistanceUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(ElectricResistanceUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -900,137 +713,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricResistance)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricResistance)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricResistance)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ElectricResistance)) - return this; - else if (conversionType == typeof(ElectricResistanceUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ElectricResistance.Info; - else if (conversionType == typeof(BaseDimensions)) - return ElectricResistance.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ElectricResistance)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs index 4591efd124..2caa99abf4 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,50 +46,124 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ElectricResistivityInfo: QuantityInfo + { + /// + public ElectricResistivityInfo(string name, ElectricResistivityUnit baseUnit, IEnumerable> unitMappings, ElectricResistivity zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ElectricResistivityInfo(string name, ElectricResistivityUnit baseUnit, IEnumerable> unitMappings, ElectricResistivity zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ElectricResistivity.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ElectricResistivity", typeof(ElectricResistivity).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricResistivity quantity. + /// + /// A new instance of the class with the default settings. + public static ElectricResistivityInfo CreateDefault() + { + return new ElectricResistivityInfo(nameof(ElectricResistivity), DefaultBaseUnit, GetDefaultMappings(), new ElectricResistivity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricResistivity quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ElectricResistivityInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ElectricResistivityInfo(nameof(ElectricResistivity), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ElectricResistivity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-3L^3MI^-2. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(3, 1, -3, -2, 0, 0, 0); + + /// + /// The default base unit of ElectricResistivity is OhmMeter. All conversions, as defined in the , go via this value. + /// + public static ElectricResistivityUnit DefaultBaseUnit { get; } = ElectricResistivityUnit.OhmMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for ElectricResistivity. + public static IEnumerable> GetDefaultMappings() + { + 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, + 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() { - BaseDimensions = new BaseDimensions(3, 1, -3, -2, 0, 0, 0); - BaseUnit = ElectricResistivityUnit.OhmMeter; - Units = Enum.GetValues(typeof(ElectricResistivityUnit)).Cast().ToArray(); - Zero = new ElectricResistivity(0, BaseUnit); - Info = new QuantityInfo("ElectricResistivity", - new UnitInfo[] - { - new UnitInfo(ElectricResistivityUnit.KiloohmCentimeter, "KiloohmsCentimeter", BaseUnits.Undefined, "ElectricResistivity"), - new UnitInfo(ElectricResistivityUnit.KiloohmMeter, "KiloohmMeters", new BaseUnits(length: LengthUnit.Decameter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricResistivity"), - new UnitInfo(ElectricResistivityUnit.MegaohmCentimeter, "MegaohmsCentimeter", BaseUnits.Undefined, "ElectricResistivity"), - new UnitInfo(ElectricResistivityUnit.MegaohmMeter, "MegaohmMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere), "ElectricResistivity"), - new UnitInfo(ElectricResistivityUnit.MicroohmCentimeter, "MicroohmsCentimeter", BaseUnits.Undefined, "ElectricResistivity"), - new UnitInfo(ElectricResistivityUnit.MicroohmMeter, "MicroohmMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricResistivity"), - new UnitInfo(ElectricResistivityUnit.MilliohmCentimeter, "MilliohmsCentimeter", BaseUnits.Undefined, "ElectricResistivity"), - new UnitInfo(ElectricResistivityUnit.MilliohmMeter, "MilliohmMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricResistivity"), - new UnitInfo(ElectricResistivityUnit.NanoohmCentimeter, "NanoohmsCentimeter", BaseUnits.Undefined, "ElectricResistivity"), - new UnitInfo(ElectricResistivityUnit.NanoohmMeter, "NanoohmMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricResistivity"), - new UnitInfo(ElectricResistivityUnit.OhmCentimeter, "OhmsCentimeter", BaseUnits.Undefined, "ElectricResistivity"), - new UnitInfo(ElectricResistivityUnit.OhmMeter, "OhmMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricResistivity"), - new UnitInfo(ElectricResistivityUnit.PicoohmCentimeter, "PicoohmsCentimeter", BaseUnits.Undefined, "ElectricResistivity"), - new UnitInfo(ElectricResistivityUnit.PicoohmMeter, "PicoohmMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Nanogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricResistivity"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricResistivityInfo.CreateDefault); } /// @@ -102,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; @@ -116,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); @@ -127,180 +196,149 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ElectricResistivity, which is OhmMeter. All conversions go via this value. /// - public static ElectricResistivityUnit BaseUnit { get; } + public static ElectricResistivityUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ElectricResistivity quantity. /// - public static ElectricResistivityUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit OhmMeter. /// - public static ElectricResistivity Zero { get; } - - /// - public static ElectricResistivity AdditiveIdentity => Zero; + public static ElectricResistivity Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ElectricResistivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ElectricResistivity.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -329,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); } @@ -337,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); } @@ -345,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); } @@ -353,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); } @@ -361,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); } @@ -369,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); } @@ -377,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); } @@ -385,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); } @@ -393,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); } @@ -401,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); } @@ -409,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); } @@ -417,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); } @@ -425,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); } @@ -433,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); } @@ -444,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); } @@ -505,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); } /// @@ -536,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); } /// @@ -561,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")); /// @@ -569,10 +600,10 @@ public static ElectricResistivityUnit ParseUnit(string str) /// Error parsing string. public static ElectricResistivityUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -587,10 +618,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -606,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; } @@ -647,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 @@ -657,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ElectricResistivity. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ElectricResistivity), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -750,248 +775,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricResistivity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ElectricResistivity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ElectricResistivity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ElectricResistivity otherTyped - && (tolerance is ElectricResistivity toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ElectricResistivity'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ElectricResistivity other, ElectricResistivity tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricResistivity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(ElectricResistivityUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(ElectricResistivityUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1006,137 +807,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricResistivity)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricResistivity)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricResistivity)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ElectricResistivity)) - return this; - else if (conversionType == typeof(ElectricResistivityUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ElectricResistivity.Info; - else if (conversionType == typeof(BaseDimensions)) - return ElectricResistivity.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ElectricResistivity)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs index cf35e233e7..9cb65ecba4 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,39 +46,91 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static ElectricSurfaceChargeDensity() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ElectricSurfaceChargeDensityInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(-2, 0, 1, 1, 0, 0, 0); - BaseUnit = ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter; - Units = Enum.GetValues(typeof(ElectricSurfaceChargeDensityUnit)).Cast().ToArray(); - Zero = new ElectricSurfaceChargeDensity(0, BaseUnit); - Info = new QuantityInfo("ElectricSurfaceChargeDensity", - new UnitInfo[] - { - new UnitInfo(ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter, "CoulombsPerSquareCentimeter", new BaseUnits(length: LengthUnit.Centimeter, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricSurfaceChargeDensity"), - new UnitInfo(ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch, "CoulombsPerSquareInch", new BaseUnits(length: LengthUnit.Inch, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricSurfaceChargeDensity"), - new UnitInfo(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, "CoulombsPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricSurfaceChargeDensity"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public ElectricSurfaceChargeDensityInfo(string name, ElectricSurfaceChargeDensityUnit baseUnit, IEnumerable> unitMappings, ElectricSurfaceChargeDensity zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ElectricSurfaceChargeDensityInfo(string name, ElectricSurfaceChargeDensityUnit baseUnit, IEnumerable> unitMappings, ElectricSurfaceChargeDensity zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ElectricSurfaceChargeDensity.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ElectricSurfaceChargeDensity", typeof(ElectricSurfaceChargeDensity).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the ElectricSurfaceChargeDensity quantity. + /// + /// A new instance of the class with the default settings. + public static ElectricSurfaceChargeDensityInfo CreateDefault() + { + return new ElectricSurfaceChargeDensityInfo(nameof(ElectricSurfaceChargeDensity), DefaultBaseUnit, GetDefaultMappings(), new ElectricSurfaceChargeDensity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricSurfaceChargeDensity quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ElectricSurfaceChargeDensityInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ElectricSurfaceChargeDensityInfo(nameof(ElectricSurfaceChargeDensity), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ElectricSurfaceChargeDensity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is TL^-2I. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, 0, 1, 1, 0, 0, 0); + + /// + /// The default base unit of ElectricSurfaceChargeDensity is CoulombPerSquareMeter. All conversions, as defined in the , go via this value. + /// + public static ElectricSurfaceChargeDensityUnit DefaultBaseUnit { get; } = ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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 = UnitsNetSetup.CreateQuantityInfo(ElectricSurfaceChargeDensityInfo.CreateDefault); } /// @@ -91,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; @@ -105,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); @@ -116,103 +163,94 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ElectricSurfaceChargeDensity, which is CoulombPerSquareMeter. All conversions go via this value. /// - public static ElectricSurfaceChargeDensityUnit BaseUnit { get; } + public static ElectricSurfaceChargeDensityUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ElectricSurfaceChargeDensity quantity. /// - public static ElectricSurfaceChargeDensityUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit CoulombPerSquareMeter. /// - public static ElectricSurfaceChargeDensity Zero { get; } - - /// - public static ElectricSurfaceChargeDensity AdditiveIdentity => Zero; + public static ElectricSurfaceChargeDensity Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ElectricSurfaceChargeDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ElectricSurfaceChargeDensity.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -241,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); } @@ -249,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); } @@ -257,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); } @@ -268,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); } @@ -329,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); } /// @@ -360,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); } /// @@ -385,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")); /// @@ -393,10 +424,10 @@ public static ElectricSurfaceChargeDensityUnit ParseUnit(string str) /// Error parsing string. public static ElectricSurfaceChargeDensityUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -411,10 +442,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -430,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; } @@ -470,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ElectricSurfaceChargeDensity. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ElectricSurfaceChargeDensity), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -563,226 +588,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricSurfaceChargeDensity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ElectricSurfaceChargeDensity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ElectricSurfaceChargeDensity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ElectricSurfaceChargeDensity otherTyped - && (tolerance is ElectricSurfaceChargeDensity toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ElectricSurfaceChargeDensity'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ElectricSurfaceChargeDensity other, ElectricSurfaceChargeDensity tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricSurfaceChargeDensity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(ElectricSurfaceChargeDensityUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(ElectricSurfaceChargeDensityUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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), - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -797,137 +620,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricSurfaceChargeDensity)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricSurfaceChargeDensity)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricSurfaceChargeDensity)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ElectricSurfaceChargeDensity)) - return this; - else if (conversionType == typeof(ElectricSurfaceChargeDensityUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ElectricSurfaceChargeDensity.Info; - else if (conversionType == typeof(BaseDimensions)) - return ElectricSurfaceChargeDensity.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ElectricSurfaceChargeDensity)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricSusceptance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricSusceptance.g.cs index b7962e73d2..4a2cf9074f 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricSusceptance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricSusceptance.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,52 +46,130 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ElectricSusceptanceInfo: QuantityInfo + { + /// + public ElectricSusceptanceInfo(string name, ElectricSusceptanceUnit baseUnit, IEnumerable> unitMappings, ElectricSusceptance zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ElectricSusceptanceInfo(string name, ElectricSusceptanceUnit baseUnit, IEnumerable> unitMappings, ElectricSusceptance zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ElectricSusceptance.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ElectricSusceptance", typeof(ElectricSusceptance).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricSusceptance quantity. + /// + /// A new instance of the class with the default settings. + public static ElectricSusceptanceInfo CreateDefault() + { + return new ElectricSusceptanceInfo(nameof(ElectricSusceptance), DefaultBaseUnit, GetDefaultMappings(), new ElectricSusceptance(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ElectricSusceptance quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ElectricSusceptanceInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ElectricSusceptanceInfo(nameof(ElectricSusceptance), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ElectricSusceptance(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^3L^-2M^-1I^2. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, -1, 3, 2, 0, 0, 0); + + /// + /// The default base unit of ElectricSusceptance is Siemens. All conversions, as defined in the , go via this value. + /// + public static ElectricSusceptanceUnit DefaultBaseUnit { get; } = ElectricSusceptanceUnit.Siemens; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for ElectricSusceptance. + public static IEnumerable> GetDefaultMappings() + { + 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, + 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() { - BaseDimensions = new BaseDimensions(-2, -1, 3, 2, 0, 0, 0); - BaseUnit = ElectricSusceptanceUnit.Siemens; - Units = Enum.GetValues(typeof(ElectricSusceptanceUnit)).Cast().ToArray(); - Zero = new ElectricSusceptance(0, BaseUnit); - Info = new QuantityInfo("ElectricSusceptance", - new UnitInfo[] - { - new UnitInfo(ElectricSusceptanceUnit.Gigamho, "Gigamhos", BaseUnits.Undefined, "ElectricSusceptance"), - new UnitInfo(ElectricSusceptanceUnit.Gigasiemens, "Gigasiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricSusceptance"), - new UnitInfo(ElectricSusceptanceUnit.Kilomho, "Kilomhos", BaseUnits.Undefined, "ElectricSusceptance"), - new UnitInfo(ElectricSusceptanceUnit.Kilosiemens, "Kilosiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricSusceptance"), - new UnitInfo(ElectricSusceptanceUnit.Megamho, "Megamhos", BaseUnits.Undefined, "ElectricSusceptance"), - new UnitInfo(ElectricSusceptanceUnit.Megasiemens, "Megasiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricSusceptance"), - new UnitInfo(ElectricSusceptanceUnit.Mho, "Mhos", BaseUnits.Undefined, "ElectricSusceptance"), - new UnitInfo(ElectricSusceptanceUnit.Micromho, "Micromhos", BaseUnits.Undefined, "ElectricSusceptance"), - new UnitInfo(ElectricSusceptanceUnit.Microsiemens, "Microsiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere), "ElectricSusceptance"), - new UnitInfo(ElectricSusceptanceUnit.Millimho, "Millimhos", BaseUnits.Undefined, "ElectricSusceptance"), - new UnitInfo(ElectricSusceptanceUnit.Millisiemens, "Millisiemens", BaseUnits.Undefined, "ElectricSusceptance"), - new UnitInfo(ElectricSusceptanceUnit.Nanomho, "Nanomhos", BaseUnits.Undefined, "ElectricSusceptance"), - new UnitInfo(ElectricSusceptanceUnit.Nanosiemens, "Nanosiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond, current: ElectricCurrentUnit.Ampere), "ElectricSusceptance"), - new UnitInfo(ElectricSusceptanceUnit.Siemens, "Siemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricSusceptance"), - new UnitInfo(ElectricSusceptanceUnit.Teramho, "Teramhos", BaseUnits.Undefined, "ElectricSusceptance"), - new UnitInfo(ElectricSusceptanceUnit.Terasiemens, "Terasiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Nanogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "ElectricSusceptance"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricSusceptanceInfo.CreateDefault); } /// @@ -104,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; @@ -118,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); @@ -129,194 +202,159 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ElectricSusceptance, which is Siemens. All conversions go via this value. /// - public static ElectricSusceptanceUnit BaseUnit { get; } + public static ElectricSusceptanceUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ElectricSusceptance quantity. /// - public static ElectricSusceptanceUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Siemens. /// - public static ElectricSusceptance Zero { get; } - - /// - public static ElectricSusceptance AdditiveIdentity => Zero; + public static ElectricSusceptance Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ElectricSusceptanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ElectricSusceptance.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -345,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); } @@ -353,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); } @@ -361,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); } @@ -369,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); } @@ -377,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); } @@ -385,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); } @@ -393,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); } @@ -401,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); } @@ -409,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); } @@ -417,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); } @@ -425,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); } @@ -433,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); } @@ -441,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); } @@ -449,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); } @@ -457,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); } @@ -465,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); } @@ -476,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); } @@ -537,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); } /// @@ -568,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); } /// @@ -593,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")); /// @@ -601,10 +632,10 @@ public static ElectricSusceptanceUnit ParseUnit(string str) /// Error parsing string. public static ElectricSusceptanceUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -619,10 +650,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -638,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; } @@ -678,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ElectricSusceptance. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ElectricSusceptance), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -771,252 +796,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricSusceptance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ElectricSusceptance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ElectricSusceptance other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ElectricSusceptance otherTyped - && (tolerance is ElectricSusceptance toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ElectricSusceptance'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ElectricSusceptance other, ElectricSusceptance tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ElectricSusceptance. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(ElectricSusceptanceUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(ElectricSusceptanceUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(ElectricSusceptanceUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1031,137 +828,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricSusceptance)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricSusceptance)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ElectricSusceptance)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ElectricSusceptance)) - return this; - else if (conversionType == typeof(ElectricSusceptanceUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ElectricSusceptance.Info; - else if (conversionType == typeof(BaseDimensions)) - return ElectricSusceptance.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ElectricSusceptance)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Energy.g.cs b/UnitsNet/GeneratedCode/Quantities/Energy.g.cs index ee650dd3b1..5d790d7dc1 100644 --- a/UnitsNet/GeneratedCode/Quantities/Energy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Energy.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -63,76 +58,202 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class EnergyInfo: QuantityInfo + { + /// + public EnergyInfo(string name, EnergyUnit baseUnit, IEnumerable> unitMappings, Energy zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public EnergyInfo(string name, EnergyUnit baseUnit, IEnumerable> unitMappings, Energy zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Energy.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Energy", typeof(Energy).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Energy quantity. + /// + /// A new instance of the class with the default settings. + public static EnergyInfo CreateDefault() + { + return new EnergyInfo(nameof(Energy), DefaultBaseUnit, GetDefaultMappings(), new Energy(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Energy quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static EnergyInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new EnergyInfo(nameof(Energy), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Energy(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-2L^2M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); + + /// + /// The default base unit of Energy is Joule. All conversions, as defined in the , go via this value. + /// + public static EnergyUnit DefaultBaseUnit { get; } = EnergyUnit.Joule; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Energy. + public static IEnumerable> GetDefaultMappings() + { + 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, + 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() { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); - BaseUnit = EnergyUnit.Joule; - Units = Enum.GetValues(typeof(EnergyUnit)).Cast().ToArray(); - Zero = new Energy(0, BaseUnit); - Info = new QuantityInfo("Energy", - new UnitInfo[] - { - new UnitInfo(EnergyUnit.BritishThermalUnit, "BritishThermalUnits", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.Calorie, "Calories", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.DecathermEc, "DecathermsEc", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.DecathermImperial, "DecathermsImperial", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.DecathermUs, "DecathermsUs", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.ElectronVolt, "ElectronVolts", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.Erg, "Ergs", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.FootPound, "FootPounds", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.GigabritishThermalUnit, "GigabritishThermalUnits", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.GigaelectronVolt, "GigaelectronVolts", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.Gigajoule, "Gigajoules", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.GigawattDay, "GigawattDays", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.GigawattHour, "GigawattHours", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.HorsepowerHour, "HorsepowerHours", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.Joule, "Joules", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Energy"), - new UnitInfo(EnergyUnit.KilobritishThermalUnit, "KilobritishThermalUnits", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.Kilocalorie, "Kilocalories", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.KiloelectronVolt, "KiloelectronVolts", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.Kilojoule, "Kilojoules", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.KilowattDay, "KilowattDays", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.KilowattHour, "KilowattHours", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.MegabritishThermalUnit, "MegabritishThermalUnits", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.Megacalorie, "Megacalories", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.MegaelectronVolt, "MegaelectronVolts", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.Megajoule, "Megajoules", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Energy"), - new UnitInfo(EnergyUnit.MegawattDay, "MegawattDays", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.MegawattHour, "MegawattHours", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.Microjoule, "Microjoules", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second), "Energy"), - new UnitInfo(EnergyUnit.Millijoule, "Millijoules", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second), "Energy"), - new UnitInfo(EnergyUnit.Nanojoule, "Nanojoules", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second), "Energy"), - new UnitInfo(EnergyUnit.Petajoule, "Petajoules", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.TeraelectronVolt, "TeraelectronVolts", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.Terajoule, "Terajoules", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Energy"), - new UnitInfo(EnergyUnit.TerawattDay, "TerawattDays", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.TerawattHour, "TerawattHours", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.ThermEc, "ThermsEc", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.ThermImperial, "ThermsImperial", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.ThermUs, "ThermsUs", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.WattDay, "WattDays", BaseUnits.Undefined, "Energy"), - new UnitInfo(EnergyUnit.WattHour, "WattHours", BaseUnits.Undefined, "Energy"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(EnergyInfo.CreateDefault); } /// @@ -140,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; @@ -154,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); @@ -165,362 +286,279 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Energy, which is Joule. All conversions go via this value. /// - public static EnergyUnit BaseUnit { get; } + public static EnergyUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Energy quantity. /// - public static EnergyUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Joule. /// - public static Energy Zero { get; } - - /// - public static Energy AdditiveIdentity => Zero; + public static Energy Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public EnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Energy.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -549,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); } @@ -557,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); } @@ -565,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); } @@ -573,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); } @@ -581,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); } @@ -589,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); } @@ -597,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); } @@ -605,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); } @@ -613,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); } @@ -621,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); } @@ -629,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); } @@ -637,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); } @@ -645,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); } @@ -653,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); } @@ -661,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); } @@ -669,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); } @@ -677,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); } @@ -685,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); } @@ -693,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); } @@ -701,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); } @@ -709,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); } @@ -717,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); } @@ -725,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); } @@ -733,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); } @@ -741,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); } @@ -749,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); } @@ -757,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); } @@ -765,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); } @@ -773,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); } @@ -781,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); } @@ -789,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); } @@ -797,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); } @@ -805,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); } @@ -813,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); } @@ -821,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); } @@ -829,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); } @@ -837,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); } @@ -845,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); } @@ -853,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); } @@ -861,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); } @@ -872,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); } @@ -933,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); } /// @@ -964,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); } /// @@ -989,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")); /// @@ -997,10 +1028,10 @@ public static EnergyUnit ParseUnit(string str) /// Error parsing string. public static EnergyUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -1015,10 +1046,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -1034,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; } @@ -1156,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Energy. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Energy), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -1249,300 +1274,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Energy other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Energy within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Energy other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Energy otherTyped - && (tolerance is Energy toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Energy'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Energy other, Energy tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Energy. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(EnergyUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - /// 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 NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } + IQuantity IQuantity.ToUnit(EnergyUnit unit) => this.ToUnit(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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(EnergyUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1557,137 +1306,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Energy)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Energy)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Energy)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Energy)) - return this; - else if (conversionType == typeof(EnergyUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Energy.Info; - else if (conversionType == typeof(BaseDimensions)) - return Energy.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Energy)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/EnergyDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/EnergyDensity.g.cs index c1b7ba7714..da3ae40a10 100644 --- a/UnitsNet/GeneratedCode/Quantities/EnergyDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/EnergyDensity.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -51,48 +46,118 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class EnergyDensityInfo: QuantityInfo + { + /// + public EnergyDensityInfo(string name, EnergyDensityUnit baseUnit, IEnumerable> unitMappings, EnergyDensity zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public EnergyDensityInfo(string name, EnergyDensityUnit baseUnit, IEnumerable> unitMappings, EnergyDensity zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, EnergyDensity.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.EnergyDensity", typeof(EnergyDensity).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the EnergyDensity quantity. + /// + /// A new instance of the class with the default settings. + public static EnergyDensityInfo CreateDefault() + { + return new EnergyDensityInfo(nameof(EnergyDensity), DefaultBaseUnit, GetDefaultMappings(), new EnergyDensity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the EnergyDensity quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static EnergyDensityInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new EnergyDensityInfo(nameof(EnergyDensity), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new EnergyDensity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-2L^-1M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-1, 1, -2, 0, 0, 0, 0); + + /// + /// The default base unit of EnergyDensity is JoulePerCubicMeter. All conversions, as defined in the , go via this value. + /// + public static EnergyDensityUnit DefaultBaseUnit { get; } = EnergyDensityUnit.JoulePerCubicMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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), + 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() { - BaseDimensions = new BaseDimensions(-1, 1, -2, 0, 0, 0, 0); - BaseUnit = EnergyDensityUnit.JoulePerCubicMeter; - Units = Enum.GetValues(typeof(EnergyDensityUnit)).Cast().ToArray(); - Zero = new EnergyDensity(0, BaseUnit); - Info = new QuantityInfo("EnergyDensity", - new UnitInfo[] - { - new UnitInfo(EnergyDensityUnit.GigajoulePerCubicMeter, "GigajoulesPerCubicMeter", new BaseUnits(length: LengthUnit.Nanometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "EnergyDensity"), - new UnitInfo(EnergyDensityUnit.GigawattHourPerCubicMeter, "GigawattHoursPerCubicMeter", BaseUnits.Undefined, "EnergyDensity"), - new UnitInfo(EnergyDensityUnit.JoulePerCubicMeter, "JoulesPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "EnergyDensity"), - new UnitInfo(EnergyDensityUnit.KilojoulePerCubicMeter, "KilojoulesPerCubicMeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "EnergyDensity"), - new UnitInfo(EnergyDensityUnit.KilowattHourPerCubicMeter, "KilowattHoursPerCubicMeter", BaseUnits.Undefined, "EnergyDensity"), - new UnitInfo(EnergyDensityUnit.MegajoulePerCubicMeter, "MegajoulesPerCubicMeter", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "EnergyDensity"), - new UnitInfo(EnergyDensityUnit.MegawattHourPerCubicMeter, "MegawattHoursPerCubicMeter", BaseUnits.Undefined, "EnergyDensity"), - new UnitInfo(EnergyDensityUnit.PetajoulePerCubicMeter, "PetajoulesPerCubicMeter", new BaseUnits(length: LengthUnit.Femtometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "EnergyDensity"), - new UnitInfo(EnergyDensityUnit.PetawattHourPerCubicMeter, "PetawattHoursPerCubicMeter", BaseUnits.Undefined, "EnergyDensity"), - new UnitInfo(EnergyDensityUnit.TerajoulePerCubicMeter, "TerajoulesPerCubicMeter", new BaseUnits(length: LengthUnit.Picometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "EnergyDensity"), - new UnitInfo(EnergyDensityUnit.TerawattHourPerCubicMeter, "TerawattHoursPerCubicMeter", BaseUnits.Undefined, "EnergyDensity"), - new UnitInfo(EnergyDensityUnit.WattHourPerCubicMeter, "WattHoursPerCubicMeter", BaseUnits.Undefined, "EnergyDensity"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(EnergyDensityInfo.CreateDefault); } /// @@ -100,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; @@ -114,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); @@ -125,166 +190,139 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of EnergyDensity, which is JoulePerCubicMeter. All conversions go via this value. /// - public static EnergyDensityUnit BaseUnit { get; } + public static EnergyDensityUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the EnergyDensity quantity. /// - public static EnergyDensityUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerCubicMeter. /// - public static EnergyDensity Zero { get; } - - /// - public static EnergyDensity AdditiveIdentity => Zero; + public static EnergyDensity Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public EnergyDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => EnergyDensity.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -313,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); } @@ -321,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); } @@ -329,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); } @@ -337,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); } @@ -345,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); } @@ -353,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); } @@ -361,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); } @@ -369,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); } @@ -377,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); } @@ -385,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); } @@ -393,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); } @@ -401,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); } @@ -412,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); } @@ -473,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); } /// @@ -504,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); } /// @@ -529,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")); /// @@ -537,10 +568,10 @@ public static EnergyDensityUnit ParseUnit(string str) /// Error parsing string. public static EnergyDensityUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -555,10 +586,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -574,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; } @@ -624,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current EnergyDensity. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(EnergyDensity), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -717,244 +742,24 @@ public int CompareTo(object? obj) /// public int CompareTo(EnergyDensity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another EnergyDensity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(EnergyDensity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is EnergyDensity otherTyped - && (tolerance is EnergyDensity toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'EnergyDensity'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(EnergyDensity other, EnergyDensity tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current EnergyDensity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(EnergyDensityUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(EnergyDensityUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -969,137 +774,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(EnergyDensity)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(EnergyDensity)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(EnergyDensity)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(EnergyDensity)) - return this; - else if (conversionType == typeof(EnergyDensityUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return EnergyDensity.Info; - else if (conversionType == typeof(BaseDimensions)) - return EnergyDensity.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(EnergyDensity)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs b/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs index 2fb78647f0..c8f6678ca9 100644 --- a/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -53,43 +48,103 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class EntropyInfo: QuantityInfo + { + /// + public EntropyInfo(string name, EntropyUnit baseUnit, IEnumerable> unitMappings, Entropy zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public EntropyInfo(string name, EntropyUnit baseUnit, IEnumerable> unitMappings, Entropy zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Entropy.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Entropy", typeof(Entropy).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Entropy quantity. + /// + /// A new instance of the class with the default settings. + public static EntropyInfo CreateDefault() + { + return new EntropyInfo(nameof(Entropy), DefaultBaseUnit, GetDefaultMappings(), new Entropy(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Entropy quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static EntropyInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new EntropyInfo(nameof(Entropy), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Entropy(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-2L^2MΘ^-1. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -2, 0, -1, 0, 0); + + /// + /// The default base unit of Entropy is JoulePerKelvin. All conversions, as defined in the , go via this value. + /// + public static EntropyUnit DefaultBaseUnit { get; } = EntropyUnit.JoulePerKelvin; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Entropy. + public static IEnumerable> GetDefaultMappings() + { + 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, + 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() { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, -1, 0, 0); - BaseUnit = EntropyUnit.JoulePerKelvin; - Units = Enum.GetValues(typeof(EntropyUnit)).Cast().ToArray(); - Zero = new Entropy(0, BaseUnit); - Info = new QuantityInfo("Entropy", - new UnitInfo[] - { - new UnitInfo(EntropyUnit.CaloriePerKelvin, "CaloriesPerKelvin", BaseUnits.Undefined, "Entropy"), - new UnitInfo(EntropyUnit.JoulePerDegreeCelsius, "JoulesPerDegreeCelsius", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius), "Entropy"), - new UnitInfo(EntropyUnit.JoulePerKelvin, "JoulesPerKelvin", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin), "Entropy"), - new UnitInfo(EntropyUnit.KilocaloriePerKelvin, "KilocaloriesPerKelvin", BaseUnits.Undefined, "Entropy"), - new UnitInfo(EntropyUnit.KilojoulePerDegreeCelsius, "KilojoulesPerDegreeCelsius", BaseUnits.Undefined, "Entropy"), - new UnitInfo(EntropyUnit.KilojoulePerKelvin, "KilojoulesPerKelvin", BaseUnits.Undefined, "Entropy"), - new UnitInfo(EntropyUnit.MegajoulePerKelvin, "MegajoulesPerKelvin", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin), "Entropy"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(EntropyInfo.CreateDefault); } /// @@ -97,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; @@ -111,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); @@ -122,131 +177,114 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Entropy, which is JoulePerKelvin. All conversions go via this value. /// - public static EntropyUnit BaseUnit { get; } + public static EntropyUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Entropy quantity. /// - public static EntropyUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerKelvin. /// - public static Entropy Zero { get; } - - /// - public static Entropy AdditiveIdentity => Zero; + public static Entropy Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public EntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Entropy.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -275,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); } @@ -283,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); } @@ -291,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); } @@ -299,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); } @@ -307,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); } @@ -315,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); } @@ -323,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); } @@ -334,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); } @@ -395,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); } /// @@ -426,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); } /// @@ -451,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")); /// @@ -459,10 +490,10 @@ public static EntropyUnit ParseUnit(string str) /// Error parsing string. public static EntropyUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -477,10 +508,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -496,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; } @@ -558,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Entropy. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Entropy), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -651,234 +676,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Entropy other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Entropy within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Entropy other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Entropy otherTyped - && (tolerance is Entropy toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Entropy'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Entropy other, Entropy tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Entropy. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(EntropyUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(EntropyUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -893,137 +708,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Entropy)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Entropy)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Entropy)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Entropy)) - return this; - else if (conversionType == typeof(EntropyUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Entropy.Info; - else if (conversionType == typeof(BaseDimensions)) - return Entropy.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Entropy)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/FluidResistance.g.cs b/UnitsNet/GeneratedCode/Quantities/FluidResistance.g.cs index c5b1913563..a4220dcb29 100644 --- a/UnitsNet/GeneratedCode/Quantities/FluidResistance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/FluidResistance.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,55 +46,139 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class FluidResistanceInfo: QuantityInfo + { + /// + public FluidResistanceInfo(string name, FluidResistanceUnit baseUnit, IEnumerable> unitMappings, FluidResistance zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public FluidResistanceInfo(string name, FluidResistanceUnit baseUnit, IEnumerable> unitMappings, FluidResistance zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, FluidResistance.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.FluidResistance", typeof(FluidResistance).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the FluidResistance quantity. + /// + /// A new instance of the class with the default settings. + public static FluidResistanceInfo CreateDefault() + { + return new FluidResistanceInfo(nameof(FluidResistance), DefaultBaseUnit, GetDefaultMappings(), new FluidResistance(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the FluidResistance quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static FluidResistanceInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new FluidResistanceInfo(nameof(FluidResistance), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new FluidResistance(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-1L^-4M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-4, 1, -1, 0, 0, 0, 0); + + /// + /// The default base unit of FluidResistance is PascalSecondPerCubicMeter. All conversions, as defined in the , go via this value. + /// + public static FluidResistanceUnit DefaultBaseUnit { get; } = FluidResistanceUnit.PascalSecondPerCubicMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for FluidResistance. + public static IEnumerable> GetDefaultMappings() + { + 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, + 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() { - BaseDimensions = new BaseDimensions(-4, 1, -1, 0, 0, 0, 0); - BaseUnit = FluidResistanceUnit.PascalSecondPerCubicMeter; - Units = Enum.GetValues(typeof(FluidResistanceUnit)).Cast().ToArray(); - Zero = new FluidResistance(0, BaseUnit); - Info = new QuantityInfo("FluidResistance", - new UnitInfo[] - { - new UnitInfo(FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth, "DyneSecondsPerCentimeterToTheFifth", BaseUnits.Undefined, "FluidResistance"), - new UnitInfo(FluidResistanceUnit.MegapascalSecondPerCubicMeter, "MegapascalSecondsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Microsecond), "FluidResistance"), - new UnitInfo(FluidResistanceUnit.MillimeterMercuryMinutePerCubicCentimeter, "MillimeterMercuryMinutesPerCubicCentimeter", BaseUnits.Undefined, "FluidResistance"), - new UnitInfo(FluidResistanceUnit.MillimeterMercuryMinutePerCubicMeter, "MillimeterMercuryMinutesPerCubicMeter", BaseUnits.Undefined, "FluidResistance"), - new UnitInfo(FluidResistanceUnit.MillimeterMercuryMinutePerLiter, "MillimeterMercuryMinutesPerLiter", BaseUnits.Undefined, "FluidResistance"), - new UnitInfo(FluidResistanceUnit.MillimeterMercuryMinutePerMilliliter, "MillimeterMercuryMinutesPerMilliliter", BaseUnits.Undefined, "FluidResistance"), - new UnitInfo(FluidResistanceUnit.MillimeterMercurySecondPerCubicCentimeter, "MillimeterMercurySecondsPerCubicCentimeter", BaseUnits.Undefined, "FluidResistance"), - new UnitInfo(FluidResistanceUnit.MillimeterMercurySecondPerCubicMeter, "MillimeterMercurySecondsPerCubicMeter", BaseUnits.Undefined, "FluidResistance"), - new UnitInfo(FluidResistanceUnit.MillimeterMercurySecondPerLiter, "MillimeterMercurySecondsPerLiter", BaseUnits.Undefined, "FluidResistance"), - new UnitInfo(FluidResistanceUnit.MillimeterMercurySecondPerMilliliter, "MillimeterMercurySecondsPerMilliliter", BaseUnits.Undefined, "FluidResistance"), - new UnitInfo(FluidResistanceUnit.PascalMinutePerCubicCentimeter, "PascalMinutesPerCubicCentimeter", BaseUnits.Undefined, "FluidResistance"), - new UnitInfo(FluidResistanceUnit.PascalMinutePerCubicMeter, "PascalMinutesPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Minute), "FluidResistance"), - new UnitInfo(FluidResistanceUnit.PascalMinutePerLiter, "PascalMinutesPerLiter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Minute), "FluidResistance"), - new UnitInfo(FluidResistanceUnit.PascalMinutePerMilliliter, "PascalMinutesPerMilliliter", BaseUnits.Undefined, "FluidResistance"), - new UnitInfo(FluidResistanceUnit.PascalSecondPerCubicCentimeter, "PascalSecondsPerCubicCentimeter", BaseUnits.Undefined, "FluidResistance"), - new UnitInfo(FluidResistanceUnit.PascalSecondPerCubicMeter, "PascalSecondsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "FluidResistance"), - new UnitInfo(FluidResistanceUnit.PascalSecondPerLiter, "PascalSecondsPerLiter", BaseUnits.Undefined, "FluidResistance"), - new UnitInfo(FluidResistanceUnit.PascalSecondPerMilliliter, "PascalSecondsPerMilliliter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second), "FluidResistance"), - new UnitInfo(FluidResistanceUnit.WoodUnit, "WoodUnits", BaseUnits.Undefined, "FluidResistance"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(FluidResistanceInfo.CreateDefault); } /// @@ -107,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; @@ -121,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); @@ -132,215 +211,174 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of FluidResistance, which is PascalSecondPerCubicMeter. All conversions go via this value. /// - public static FluidResistanceUnit BaseUnit { get; } + public static FluidResistanceUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the FluidResistance quantity. /// - public static FluidResistanceUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit PascalSecondPerCubicMeter. /// - public static FluidResistance Zero { get; } - - /// - public static FluidResistance AdditiveIdentity => Zero; + public static FluidResistance Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public FluidResistanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => FluidResistance.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -369,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); } @@ -377,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); } @@ -385,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); } @@ -393,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); } @@ -401,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); } @@ -409,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); } @@ -417,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); } @@ -425,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); } @@ -433,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); } @@ -441,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); } @@ -449,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); } @@ -457,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); } @@ -465,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); } @@ -473,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); } @@ -481,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); } @@ -489,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); } @@ -497,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); } @@ -505,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); } @@ -513,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); } @@ -524,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); } @@ -585,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); } /// @@ -616,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); } /// @@ -641,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")); /// @@ -649,10 +680,10 @@ public static FluidResistanceUnit ParseUnit(string str) /// Error parsing string. public static FluidResistanceUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -667,10 +698,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -686,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; } @@ -726,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current FluidResistance. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(FluidResistance), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -819,258 +844,24 @@ public int CompareTo(object? obj) /// public int CompareTo(FluidResistance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another FluidResistance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(FluidResistance other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is FluidResistance otherTyped - && (tolerance is FluidResistance toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'FluidResistance'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(FluidResistance other, FluidResistance tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current FluidResistance. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(FluidResistanceUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(FluidResistanceUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(FluidResistanceUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1085,137 +876,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(FluidResistance)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(FluidResistance)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(FluidResistance)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(FluidResistance)) - return this; - else if (conversionType == typeof(FluidResistanceUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return FluidResistance.Info; - else if (conversionType == typeof(BaseDimensions)) - return FluidResistance.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(FluidResistance)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Force.g.cs b/UnitsNet/GeneratedCode/Quantities/Force.g.cs index 19e96dc347..90a6d0da0e 100644 --- a/UnitsNet/GeneratedCode/Quantities/Force.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Force.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -62,51 +57,127 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ForceInfo: QuantityInfo + { + /// + public ForceInfo(string name, ForceUnit baseUnit, IEnumerable> unitMappings, Force zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ForceInfo(string name, ForceUnit baseUnit, IEnumerable> unitMappings, Force zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Force.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Force", typeof(Force).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Force quantity. + /// + /// A new instance of the class with the default settings. + public static ForceInfo CreateDefault() + { + return new ForceInfo(nameof(Force), DefaultBaseUnit, GetDefaultMappings(), new Force(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Force quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ForceInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ForceInfo(nameof(Force), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Force(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-2LM. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, 1, -2, 0, 0, 0, 0); + + /// + /// The default base unit of Force is Newton. All conversions, as defined in the , go via this value. + /// + public static ForceUnit DefaultBaseUnit { get; } = ForceUnit.Newton; + + /// + /// Retrieves the default mappings for . + /// + /// 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), + 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, + 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() { - BaseDimensions = new BaseDimensions(1, 1, -2, 0, 0, 0, 0); - BaseUnit = ForceUnit.Newton; - Units = Enum.GetValues(typeof(ForceUnit)).Cast().ToArray(); - Zero = new Force(0, BaseUnit); - Info = new QuantityInfo("Force", - new UnitInfo[] - { - new UnitInfo(ForceUnit.Decanewton, "Decanewtons", new BaseUnits(length: LengthUnit.Decameter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Force"), - new UnitInfo(ForceUnit.Dyn, "Dyne", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram, time: DurationUnit.Second), "Force"), - new UnitInfo(ForceUnit.KilogramForce, "KilogramsForce", BaseUnits.Undefined, "Force"), - new UnitInfo(ForceUnit.Kilonewton, "Kilonewtons", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Force"), - new UnitInfo(ForceUnit.KiloPond, "KiloPonds", BaseUnits.Undefined, "Force"), - new UnitInfo(ForceUnit.KilopoundForce, "KilopoundsForce", BaseUnits.Undefined, "Force"), - new UnitInfo(ForceUnit.Meganewton, "Meganewtons", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Force"), - new UnitInfo(ForceUnit.Micronewton, "Micronewtons", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Force"), - new UnitInfo(ForceUnit.Millinewton, "Millinewtons", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Force"), - new UnitInfo(ForceUnit.Newton, "Newtons", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Force"), - new UnitInfo(ForceUnit.OunceForce, "OunceForce", BaseUnits.Undefined, "Force"), - new UnitInfo(ForceUnit.Poundal, "Poundals", BaseUnits.Undefined, "Force"), - new UnitInfo(ForceUnit.PoundForce, "PoundsForce", BaseUnits.Undefined, "Force"), - new UnitInfo(ForceUnit.ShortTonForce, "ShortTonsForce", BaseUnits.Undefined, "Force"), - new UnitInfo(ForceUnit.TonneForce, "TonnesForce", BaseUnits.Undefined, "Force"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ForceInfo.CreateDefault); } /// @@ -114,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; @@ -128,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); @@ -139,187 +210,154 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Force, which is Newton. All conversions go via this value. /// - public static ForceUnit BaseUnit { get; } + public static ForceUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Force quantity. /// - public static ForceUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Newton. /// - public static Force Zero { get; } - - /// - public static Force AdditiveIdentity => Zero; + public static Force Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ForceUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Force.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -348,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); } @@ -356,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); } @@ -364,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); } @@ -372,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); } @@ -380,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); } @@ -388,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); } @@ -396,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); } @@ -404,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); } @@ -412,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); } @@ -420,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); } @@ -428,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); } @@ -436,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); } @@ -444,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); } @@ -452,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); } @@ -460,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); } @@ -471,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); } @@ -532,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); } /// @@ -563,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); } /// @@ -588,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")); /// @@ -596,10 +627,10 @@ public static ForceUnit ParseUnit(string str) /// Error parsing string. public static ForceUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -614,10 +645,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -633,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; } @@ -749,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Force. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Force), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -842,250 +867,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Force other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Force within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Force other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Force otherTyped - && (tolerance is Force toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Force'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Force other, Force tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Force. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(ForceUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(ForceUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(ForceUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1100,137 +899,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Force)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Force)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Force)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Force)) - return this; - else if (conversionType == typeof(ForceUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Force.Info; - else if (conversionType == typeof(BaseDimensions)) - return Force.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Force)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs index 3d2948e876..08105dafc0 100644 --- a/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -51,51 +46,127 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ForceChangeRateInfo: QuantityInfo + { + /// + public ForceChangeRateInfo(string name, ForceChangeRateUnit baseUnit, IEnumerable> unitMappings, ForceChangeRate zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ForceChangeRateInfo(string name, ForceChangeRateUnit baseUnit, IEnumerable> unitMappings, ForceChangeRate zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ForceChangeRate.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ForceChangeRate", typeof(ForceChangeRate).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the ForceChangeRate quantity. + /// + /// A new instance of the class with the default settings. + public static ForceChangeRateInfo CreateDefault() + { + return new ForceChangeRateInfo(nameof(ForceChangeRate), DefaultBaseUnit, GetDefaultMappings(), new ForceChangeRate(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ForceChangeRate quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ForceChangeRateInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ForceChangeRateInfo(nameof(ForceChangeRate), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ForceChangeRate(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-3LM. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, 1, -3, 0, 0, 0, 0); + + /// + /// The default base unit of ForceChangeRate is NewtonPerSecond. All conversions, as defined in the , go via this value. + /// + public static ForceChangeRateUnit DefaultBaseUnit { get; } = ForceChangeRateUnit.NewtonPerSecond; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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, + new QuantityValue(120000000000000, 8896443230521) + ); + yield return new (ForceChangeRateUnit.PoundForcePerSecond, "PoundForcePerSecond", "PoundsForcePerSecond", BaseUnits.Undefined, + new QuantityValue(2000000000000, 8896443230521) + ); + } + } + static ForceChangeRate() { - BaseDimensions = new BaseDimensions(1, 1, -3, 0, 0, 0, 0); - BaseUnit = ForceChangeRateUnit.NewtonPerSecond; - Units = Enum.GetValues(typeof(ForceChangeRateUnit)).Cast().ToArray(); - Zero = new ForceChangeRate(0, BaseUnit); - Info = new QuantityInfo("ForceChangeRate", - new UnitInfo[] - { - new UnitInfo(ForceChangeRateUnit.CentinewtonPerSecond, "CentinewtonsPerSecond", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "ForceChangeRate"), - new UnitInfo(ForceChangeRateUnit.DecanewtonPerMinute, "DecanewtonsPerMinute", BaseUnits.Undefined, "ForceChangeRate"), - new UnitInfo(ForceChangeRateUnit.DecanewtonPerSecond, "DecanewtonsPerSecond", new BaseUnits(length: LengthUnit.Decameter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "ForceChangeRate"), - new UnitInfo(ForceChangeRateUnit.DecinewtonPerSecond, "DecinewtonsPerSecond", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "ForceChangeRate"), - new UnitInfo(ForceChangeRateUnit.KilonewtonPerMinute, "KilonewtonsPerMinute", BaseUnits.Undefined, "ForceChangeRate"), - new UnitInfo(ForceChangeRateUnit.KilonewtonPerSecond, "KilonewtonsPerSecond", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "ForceChangeRate"), - new UnitInfo(ForceChangeRateUnit.KilopoundForcePerMinute, "KilopoundsForcePerMinute", BaseUnits.Undefined, "ForceChangeRate"), - new UnitInfo(ForceChangeRateUnit.KilopoundForcePerSecond, "KilopoundsForcePerSecond", BaseUnits.Undefined, "ForceChangeRate"), - new UnitInfo(ForceChangeRateUnit.MicronewtonPerSecond, "MicronewtonsPerSecond", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "ForceChangeRate"), - new UnitInfo(ForceChangeRateUnit.MillinewtonPerSecond, "MillinewtonsPerSecond", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "ForceChangeRate"), - new UnitInfo(ForceChangeRateUnit.NanonewtonPerSecond, "NanonewtonsPerSecond", new BaseUnits(length: LengthUnit.Nanometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "ForceChangeRate"), - new UnitInfo(ForceChangeRateUnit.NewtonPerMinute, "NewtonsPerMinute", BaseUnits.Undefined, "ForceChangeRate"), - new UnitInfo(ForceChangeRateUnit.NewtonPerSecond, "NewtonsPerSecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "ForceChangeRate"), - new UnitInfo(ForceChangeRateUnit.PoundForcePerMinute, "PoundsForcePerMinute", BaseUnits.Undefined, "ForceChangeRate"), - new UnitInfo(ForceChangeRateUnit.PoundForcePerSecond, "PoundsForcePerSecond", BaseUnits.Undefined, "ForceChangeRate"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ForceChangeRateInfo.CreateDefault); } /// @@ -103,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; @@ -117,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); @@ -128,187 +199,154 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ForceChangeRate, which is NewtonPerSecond. All conversions go via this value. /// - public static ForceChangeRateUnit BaseUnit { get; } + public static ForceChangeRateUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ForceChangeRate quantity. /// - public static ForceChangeRateUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit NewtonPerSecond. /// - public static ForceChangeRate Zero { get; } - - /// - public static ForceChangeRate AdditiveIdentity => Zero; + public static ForceChangeRate Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ForceChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ForceChangeRate.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -337,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); } @@ -345,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); } @@ -353,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); } @@ -361,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); } @@ -369,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); } @@ -377,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); } @@ -385,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); } @@ -393,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); } @@ -401,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); } @@ -409,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); } @@ -417,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); } @@ -425,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); } @@ -433,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); } @@ -441,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); } @@ -449,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); } @@ -460,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); } @@ -521,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); } /// @@ -552,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); } /// @@ -577,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")); /// @@ -585,10 +616,10 @@ public static ForceChangeRateUnit ParseUnit(string str) /// Error parsing string. public static ForceChangeRateUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -603,10 +634,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -622,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; } @@ -672,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ForceChangeRate. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ForceChangeRate), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -765,250 +790,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ForceChangeRate other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ForceChangeRate within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ForceChangeRate other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ForceChangeRate otherTyped - && (tolerance is ForceChangeRate toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ForceChangeRate'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ForceChangeRate other, ForceChangeRate tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ForceChangeRate. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(ForceChangeRateUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(ForceChangeRateUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(ForceChangeRateUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1023,137 +822,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ForceChangeRate)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ForceChangeRate)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ForceChangeRate)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ForceChangeRate)) - return this; - else if (conversionType == typeof(ForceChangeRateUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ForceChangeRate.Info; - else if (conversionType == typeof(BaseDimensions)) - return ForceChangeRate.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ForceChangeRate)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs b/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs index 5c4934c44c..f64caca119 100644 --- a/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -59,74 +54,196 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ForcePerLengthInfo: QuantityInfo + { + /// + public ForcePerLengthInfo(string name, ForcePerLengthUnit baseUnit, IEnumerable> unitMappings, ForcePerLength zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ForcePerLengthInfo(string name, ForcePerLengthUnit baseUnit, IEnumerable> unitMappings, ForcePerLength zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ForcePerLength.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ForcePerLength", typeof(ForcePerLength).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the ForcePerLength quantity. + /// + /// A new instance of the class with the default settings. + public static ForcePerLengthInfo CreateDefault() + { + return new ForcePerLengthInfo(nameof(ForcePerLength), DefaultBaseUnit, GetDefaultMappings(), new ForcePerLength(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ForcePerLength quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ForcePerLengthInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ForcePerLengthInfo(nameof(ForcePerLength), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ForcePerLength(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-2M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 1, -2, 0, 0, 0, 0); + + /// + /// The default base unit of ForcePerLength is NewtonPerMeter. All conversions, as defined in the , go via this value. + /// + public static ForcePerLengthUnit DefaultBaseUnit { get; } = ForcePerLengthUnit.NewtonPerMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for ForcePerLength. + public static IEnumerable> GetDefaultMappings() + { + 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, + 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() { - BaseDimensions = new BaseDimensions(0, 1, -2, 0, 0, 0, 0); - BaseUnit = ForcePerLengthUnit.NewtonPerMeter; - Units = Enum.GetValues(typeof(ForcePerLengthUnit)).Cast().ToArray(); - Zero = new ForcePerLength(0, BaseUnit); - Info = new QuantityInfo("ForcePerLength", - new UnitInfo[] - { - new UnitInfo(ForcePerLengthUnit.CentinewtonPerCentimeter, "CentinewtonsPerCentimeter", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.CentinewtonPerMeter, "CentinewtonsPerMeter", new BaseUnits(mass: MassUnit.Decagram, time: DurationUnit.Second), "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.CentinewtonPerMillimeter, "CentinewtonsPerMillimeter", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.DecanewtonPerCentimeter, "DecanewtonsPerCentimeter", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.DecanewtonPerMeter, "DecanewtonsPerMeter", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.DecanewtonPerMillimeter, "DecanewtonsPerMillimeter", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.DecinewtonPerCentimeter, "DecinewtonsPerCentimeter", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.DecinewtonPerMeter, "DecinewtonsPerMeter", new BaseUnits(mass: MassUnit.Hectogram, time: DurationUnit.Second), "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.DecinewtonPerMillimeter, "DecinewtonsPerMillimeter", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.KilogramForcePerCentimeter, "KilogramsForcePerCentimeter", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.KilogramForcePerMeter, "KilogramsForcePerMeter", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.KilogramForcePerMillimeter, "KilogramsForcePerMillimeter", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.KilonewtonPerCentimeter, "KilonewtonsPerCentimeter", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.KilonewtonPerMeter, "KilonewtonsPerMeter", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.KilonewtonPerMillimeter, "KilonewtonsPerMillimeter", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.KilopoundForcePerFoot, "KilopoundsForcePerFoot", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.KilopoundForcePerInch, "KilopoundsForcePerInch", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.MeganewtonPerCentimeter, "MeganewtonsPerCentimeter", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.MeganewtonPerMeter, "MeganewtonsPerMeter", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Millisecond), "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.MeganewtonPerMillimeter, "MeganewtonsPerMillimeter", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.MicronewtonPerCentimeter, "MicronewtonsPerCentimeter", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.MicronewtonPerMeter, "MicronewtonsPerMeter", new BaseUnits(mass: MassUnit.Milligram, time: DurationUnit.Second), "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.MicronewtonPerMillimeter, "MicronewtonsPerMillimeter", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.MillinewtonPerCentimeter, "MillinewtonsPerCentimeter", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.MillinewtonPerMeter, "MillinewtonsPerMeter", new BaseUnits(mass: MassUnit.Gram, time: DurationUnit.Second), "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.MillinewtonPerMillimeter, "MillinewtonsPerMillimeter", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.NanonewtonPerCentimeter, "NanonewtonsPerCentimeter", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.NanonewtonPerMeter, "NanonewtonsPerMeter", new BaseUnits(mass: MassUnit.Microgram, time: DurationUnit.Second), "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.NanonewtonPerMillimeter, "NanonewtonsPerMillimeter", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.NewtonPerCentimeter, "NewtonsPerCentimeter", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.NewtonPerMeter, "NewtonsPerMeter", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second), "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.NewtonPerMillimeter, "NewtonsPerMillimeter", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.PoundForcePerFoot, "PoundsForcePerFoot", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.PoundForcePerInch, "PoundsForcePerInch", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.PoundForcePerYard, "PoundsForcePerYard", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.TonneForcePerCentimeter, "TonnesForcePerCentimeter", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.TonneForcePerMeter, "TonnesForcePerMeter", BaseUnits.Undefined, "ForcePerLength"), - new UnitInfo(ForcePerLengthUnit.TonneForcePerMillimeter, "TonnesForcePerMillimeter", BaseUnits.Undefined, "ForcePerLength"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ForcePerLengthInfo.CreateDefault); } /// @@ -134,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; @@ -148,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); @@ -159,348 +276,269 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ForcePerLength, which is NewtonPerMeter. All conversions go via this value. /// - public static ForcePerLengthUnit BaseUnit { get; } + public static ForcePerLengthUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ForcePerLength quantity. /// - public static ForcePerLengthUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit NewtonPerMeter. /// - public static ForcePerLength Zero { get; } - - /// - public static ForcePerLength AdditiveIdentity => Zero; + public static ForcePerLength Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ForcePerLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ForcePerLength.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -529,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); } @@ -537,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); } @@ -545,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); } @@ -553,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); } @@ -561,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); } @@ -569,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); } @@ -577,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); } @@ -585,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); } @@ -593,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); } @@ -601,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); } @@ -609,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); } @@ -617,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); } @@ -625,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); } @@ -633,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); } @@ -641,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); } @@ -649,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); } @@ -657,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); } @@ -665,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); } @@ -673,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); } @@ -681,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); } @@ -689,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); } @@ -697,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); } @@ -705,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); } @@ -713,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); } @@ -721,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); } @@ -729,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); } @@ -737,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); } @@ -745,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); } @@ -753,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); } @@ -761,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); } @@ -769,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); } @@ -777,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); } @@ -785,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); } @@ -793,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); } @@ -801,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); } @@ -809,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); } @@ -817,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); } @@ -825,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); } @@ -836,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); } @@ -897,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); } /// @@ -928,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); } /// @@ -953,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")); /// @@ -961,10 +992,10 @@ public static ForcePerLengthUnit ParseUnit(string str) /// Error parsing string. public static ForcePerLengthUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -979,10 +1010,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -998,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; } @@ -1096,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ForcePerLength. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ForcePerLength), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -1189,296 +1214,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ForcePerLength other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ForcePerLength within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ForcePerLength other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ForcePerLength otherTyped - && (tolerance is ForcePerLength toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ForcePerLength'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ForcePerLength other, ForcePerLength tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ForcePerLength. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(ForcePerLengthUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - /// 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 NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } + IQuantity IQuantity.ToUnit(ForcePerLengthUnit unit) => this.ToUnit(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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(ForcePerLengthUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1493,137 +1246,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ForcePerLength)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ForcePerLength)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ForcePerLength)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ForcePerLength)) - return this; - else if (conversionType == typeof(ForcePerLengthUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ForcePerLength.Info; - else if (conversionType == typeof(BaseDimensions)) - return ForcePerLength.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ForcePerLength)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs b/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs index 1e426e232b..ccd72e1770 100644 --- a/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -51,48 +46,118 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class FrequencyInfo: QuantityInfo + { + /// + public FrequencyInfo(string name, FrequencyUnit baseUnit, IEnumerable> unitMappings, Frequency zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public FrequencyInfo(string name, FrequencyUnit baseUnit, IEnumerable> unitMappings, Frequency zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Frequency.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Frequency", typeof(Frequency).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Frequency quantity. + /// + /// A new instance of the class with the default settings. + public static FrequencyInfo CreateDefault() + { + return new FrequencyInfo(nameof(Frequency), DefaultBaseUnit, GetDefaultMappings(), new Frequency(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Frequency quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static FrequencyInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new FrequencyInfo(nameof(Frequency), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Frequency(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-1. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); + + /// + /// The default base unit of Frequency is Hertz. All conversions, as defined in the , go via this value. + /// + public static FrequencyUnit DefaultBaseUnit { get; } = FrequencyUnit.Hertz; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Frequency. + public static IEnumerable> GetDefaultMappings() + { + 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), + 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", BaseUnits.Undefined, + new QuantityValue(1, 1000000000000) + ); + } + } + static Frequency() { - BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); - BaseUnit = FrequencyUnit.Hertz; - Units = Enum.GetValues(typeof(FrequencyUnit)).Cast().ToArray(); - Zero = new Frequency(0, BaseUnit); - Info = new QuantityInfo("Frequency", - new UnitInfo[] - { - new UnitInfo(FrequencyUnit.BeatPerMinute, "BeatsPerMinute", new BaseUnits(time: DurationUnit.Minute), "Frequency"), - new UnitInfo(FrequencyUnit.CyclePerHour, "CyclesPerHour", new BaseUnits(time: DurationUnit.Hour), "Frequency"), - new UnitInfo(FrequencyUnit.CyclePerMinute, "CyclesPerMinute", new BaseUnits(time: DurationUnit.Minute), "Frequency"), - new UnitInfo(FrequencyUnit.Gigahertz, "Gigahertz", new BaseUnits(time: DurationUnit.Nanosecond), "Frequency"), - new UnitInfo(FrequencyUnit.Hertz, "Hertz", new BaseUnits(time: DurationUnit.Second), "Frequency"), - new UnitInfo(FrequencyUnit.Kilohertz, "Kilohertz", new BaseUnits(time: DurationUnit.Millisecond), "Frequency"), - new UnitInfo(FrequencyUnit.Megahertz, "Megahertz", new BaseUnits(time: DurationUnit.Microsecond), "Frequency"), - new UnitInfo(FrequencyUnit.Microhertz, "Microhertz", BaseUnits.Undefined, "Frequency"), - new UnitInfo(FrequencyUnit.Millihertz, "Millihertz", BaseUnits.Undefined, "Frequency"), - new UnitInfo(FrequencyUnit.PerSecond, "PerSecond", new BaseUnits(time: DurationUnit.Second), "Frequency"), - new UnitInfo(FrequencyUnit.RadianPerSecond, "RadiansPerSecond", BaseUnits.Undefined, "Frequency"), - new UnitInfo(FrequencyUnit.Terahertz, "Terahertz", BaseUnits.Undefined, "Frequency"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(FrequencyInfo.CreateDefault); } /// @@ -100,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; @@ -114,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); @@ -125,166 +190,139 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Frequency, which is Hertz. All conversions go via this value. /// - public static FrequencyUnit BaseUnit { get; } + public static FrequencyUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Frequency quantity. /// - public static FrequencyUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Hertz. /// - public static Frequency Zero { get; } - - /// - public static Frequency AdditiveIdentity => Zero; + public static Frequency Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public FrequencyUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Frequency.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -313,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); } @@ -321,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); } @@ -329,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); } @@ -337,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); } @@ -345,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); } @@ -353,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); } @@ -361,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); } @@ -369,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); } @@ -377,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); } @@ -385,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); } @@ -393,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); } @@ -401,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); } @@ -412,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); } @@ -473,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); } /// @@ -504,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); } /// @@ -529,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")); /// @@ -537,10 +568,10 @@ public static FrequencyUnit ParseUnit(string str) /// Error parsing string. public static FrequencyUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -555,10 +586,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -574,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; } @@ -624,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Frequency. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Frequency), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -717,244 +742,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Frequency other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Frequency within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Frequency other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Frequency otherTyped - && (tolerance is Frequency toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Frequency'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Frequency other, Frequency tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Frequency. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(FrequencyUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(FrequencyUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -969,137 +774,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Frequency)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Frequency)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Frequency)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Frequency)) - return this; - else if (conversionType == typeof(FrequencyUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Frequency.Info; - else if (conversionType == typeof(BaseDimensions)) - return Frequency.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Frequency)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/FuelEfficiency.g.cs b/UnitsNet/GeneratedCode/Quantities/FuelEfficiency.g.cs index 0532819357..654abfc194 100644 --- a/UnitsNet/GeneratedCode/Quantities/FuelEfficiency.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/FuelEfficiency.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,40 +46,95 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static FuelEfficiency() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class FuelEfficiencyInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(-2, 0, 0, 0, 0, 0, 0); - BaseUnit = FuelEfficiencyUnit.KilometerPerLiter; - Units = Enum.GetValues(typeof(FuelEfficiencyUnit)).Cast().ToArray(); - Zero = new FuelEfficiency(0, BaseUnit); - Info = new QuantityInfo("FuelEfficiency", - new UnitInfo[] - { - new UnitInfo(FuelEfficiencyUnit.KilometerPerLiter, "KilometersPerLiter", BaseUnits.Undefined, "FuelEfficiency"), - new UnitInfo(FuelEfficiencyUnit.LiterPer100Kilometers, "LitersPer100Kilometers", BaseUnits.Undefined, "FuelEfficiency"), - new UnitInfo(FuelEfficiencyUnit.MilePerUkGallon, "MilesPerUkGallon", BaseUnits.Undefined, "FuelEfficiency"), - new UnitInfo(FuelEfficiencyUnit.MilePerUsGallon, "MilesPerUsGallon", BaseUnits.Undefined, "FuelEfficiency"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public FuelEfficiencyInfo(string name, FuelEfficiencyUnit baseUnit, IEnumerable> unitMappings, FuelEfficiency zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public FuelEfficiencyInfo(string name, FuelEfficiencyUnit baseUnit, IEnumerable> unitMappings, FuelEfficiency zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, FuelEfficiency.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.FuelEfficiency", typeof(FuelEfficiency).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the FuelEfficiency quantity. + /// + /// A new instance of the class with the default settings. + public static FuelEfficiencyInfo CreateDefault() + { + return new FuelEfficiencyInfo(nameof(FuelEfficiency), DefaultBaseUnit, GetDefaultMappings(), new FuelEfficiency(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the FuelEfficiency quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static FuelEfficiencyInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new FuelEfficiencyInfo(nameof(FuelEfficiency), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new FuelEfficiency(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is L^-2. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, 0, 0, 0, 0, 0, 0); + + /// + /// The default base unit of FuelEfficiency is KilometerPerLiter. All conversions, as defined in the , go via this value. + /// + public static FuelEfficiencyUnit DefaultBaseUnit { get; } = FuelEfficiencyUnit.KilometerPerLiter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for FuelEfficiency. + public static IEnumerable> GetDefaultMappings() + { + yield return new (FuelEfficiencyUnit.KilometerPerLiter, "KilometerPerLiter", "KilometersPerLiter", 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 = UnitsNetSetup.CreateQuantityInfo(FuelEfficiencyInfo.CreateDefault); } /// @@ -92,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; @@ -106,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); @@ -117,110 +167,99 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of FuelEfficiency, which is KilometerPerLiter. All conversions go via this value. /// - public static FuelEfficiencyUnit BaseUnit { get; } + public static FuelEfficiencyUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the FuelEfficiency quantity. /// - public static FuelEfficiencyUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit KilometerPerLiter. /// - public static FuelEfficiency Zero { get; } - - /// - public static FuelEfficiency AdditiveIdentity => Zero; + public static FuelEfficiency Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public FuelEfficiencyUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => FuelEfficiency.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -249,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); } @@ -257,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); } @@ -265,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); } @@ -273,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); } @@ -284,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); } @@ -345,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); } /// @@ -376,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); } /// @@ -401,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")); /// @@ -409,10 +441,10 @@ public static FuelEfficiencyUnit ParseUnit(string str) /// Error parsing string. public static FuelEfficiencyUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -427,10 +459,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -446,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; } @@ -486,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current FuelEfficiency. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(FuelEfficiency), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -579,228 +605,24 @@ public int CompareTo(object? obj) /// public int CompareTo(FuelEfficiency other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another FuelEfficiency within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(FuelEfficiency other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is FuelEfficiency otherTyped - && (tolerance is FuelEfficiency toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'FuelEfficiency'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(FuelEfficiency other, FuelEfficiency tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current FuelEfficiency. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(FuelEfficiencyUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(FuelEfficiencyUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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), - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -815,137 +637,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(FuelEfficiency)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(FuelEfficiency)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(FuelEfficiency)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(FuelEfficiency)) - return this; - else if (conversionType == typeof(FuelEfficiencyUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return FuelEfficiency.Info; - else if (conversionType == typeof(BaseDimensions)) - return FuelEfficiency.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(FuelEfficiency)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/HeatFlux.g.cs b/UnitsNet/GeneratedCode/Quantities/HeatFlux.g.cs index 9865e36c85..45c5e0fa82 100644 --- a/UnitsNet/GeneratedCode/Quantities/HeatFlux.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/HeatFlux.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -51,54 +46,136 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class HeatFluxInfo: QuantityInfo + { + /// + public HeatFluxInfo(string name, HeatFluxUnit baseUnit, IEnumerable> unitMappings, HeatFlux zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public HeatFluxInfo(string name, HeatFluxUnit baseUnit, IEnumerable> unitMappings, HeatFlux zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, HeatFlux.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.HeatFlux", typeof(HeatFlux).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the HeatFlux quantity. + /// + /// A new instance of the class with the default settings. + public static HeatFluxInfo CreateDefault() + { + return new HeatFluxInfo(nameof(HeatFlux), DefaultBaseUnit, GetDefaultMappings(), new HeatFlux(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the HeatFlux quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static HeatFluxInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new HeatFluxInfo(nameof(HeatFlux), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new HeatFlux(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-3M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 1, -3, 0, 0, 0, 0); + + /// + /// The default base unit of HeatFlux is WattPerSquareMeter. All conversions, as defined in the , go via this value. + /// + public static HeatFluxUnit DefaultBaseUnit { get; } = HeatFluxUnit.WattPerSquareMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for HeatFlux. + public static IEnumerable> GetDefaultMappings() + { + 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() { - BaseDimensions = new BaseDimensions(0, 1, -3, 0, 0, 0, 0); - BaseUnit = HeatFluxUnit.WattPerSquareMeter; - Units = Enum.GetValues(typeof(HeatFluxUnit)).Cast().ToArray(); - Zero = new HeatFlux(0, BaseUnit); - Info = new QuantityInfo("HeatFlux", - new UnitInfo[] - { - new UnitInfo(HeatFluxUnit.BtuPerHourSquareFoot, "BtusPerHourSquareFoot", BaseUnits.Undefined, "HeatFlux"), - new UnitInfo(HeatFluxUnit.BtuPerMinuteSquareFoot, "BtusPerMinuteSquareFoot", BaseUnits.Undefined, "HeatFlux"), - new UnitInfo(HeatFluxUnit.BtuPerSecondSquareFoot, "BtusPerSecondSquareFoot", BaseUnits.Undefined, "HeatFlux"), - new UnitInfo(HeatFluxUnit.BtuPerSecondSquareInch, "BtusPerSecondSquareInch", BaseUnits.Undefined, "HeatFlux"), - new UnitInfo(HeatFluxUnit.CaloriePerSecondSquareCentimeter, "CaloriesPerSecondSquareCentimeter", BaseUnits.Undefined, "HeatFlux"), - new UnitInfo(HeatFluxUnit.CentiwattPerSquareMeter, "CentiwattsPerSquareMeter", new BaseUnits(mass: MassUnit.Decagram, time: DurationUnit.Second), "HeatFlux"), - new UnitInfo(HeatFluxUnit.DeciwattPerSquareMeter, "DeciwattsPerSquareMeter", new BaseUnits(mass: MassUnit.Hectogram, time: DurationUnit.Second), "HeatFlux"), - new UnitInfo(HeatFluxUnit.KilocaloriePerHourSquareMeter, "KilocaloriesPerHourSquareMeter", BaseUnits.Undefined, "HeatFlux"), - new UnitInfo(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter, "KilocaloriesPerSecondSquareCentimeter", BaseUnits.Undefined, "HeatFlux"), - new UnitInfo(HeatFluxUnit.KilowattPerSquareMeter, "KilowattsPerSquareMeter", BaseUnits.Undefined, "HeatFlux"), - new UnitInfo(HeatFluxUnit.MicrowattPerSquareMeter, "MicrowattsPerSquareMeter", new BaseUnits(mass: MassUnit.Milligram, time: DurationUnit.Second), "HeatFlux"), - new UnitInfo(HeatFluxUnit.MilliwattPerSquareMeter, "MilliwattsPerSquareMeter", new BaseUnits(mass: MassUnit.Gram, time: DurationUnit.Second), "HeatFlux"), - new UnitInfo(HeatFluxUnit.NanowattPerSquareMeter, "NanowattsPerSquareMeter", new BaseUnits(mass: MassUnit.Microgram, time: DurationUnit.Second), "HeatFlux"), - new UnitInfo(HeatFluxUnit.PoundForcePerFootSecond, "PoundsForcePerFootSecond", BaseUnits.Undefined, "HeatFlux"), - new UnitInfo(HeatFluxUnit.PoundPerSecondCubed, "PoundsPerSecondCubed", BaseUnits.Undefined, "HeatFlux"), - new UnitInfo(HeatFluxUnit.WattPerSquareFoot, "WattsPerSquareFoot", BaseUnits.Undefined, "HeatFlux"), - new UnitInfo(HeatFluxUnit.WattPerSquareInch, "WattsPerSquareInch", BaseUnits.Undefined, "HeatFlux"), - new UnitInfo(HeatFluxUnit.WattPerSquareMeter, "WattsPerSquareMeter", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second), "HeatFlux"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(HeatFluxInfo.CreateDefault); } /// @@ -106,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; @@ -120,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); @@ -131,208 +208,169 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of HeatFlux, which is WattPerSquareMeter. All conversions go via this value. /// - public static HeatFluxUnit BaseUnit { get; } + public static HeatFluxUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the HeatFlux quantity. /// - public static HeatFluxUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit WattPerSquareMeter. /// - public static HeatFlux Zero { get; } - - /// - public static HeatFlux AdditiveIdentity => Zero; + public static HeatFlux Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public HeatFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => HeatFlux.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -361,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); } @@ -369,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); } @@ -377,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); } @@ -385,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); } @@ -393,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); } @@ -401,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); } @@ -409,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); } @@ -417,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); } @@ -425,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); } @@ -433,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); } @@ -441,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); } @@ -449,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); } @@ -457,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); } @@ -465,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); } @@ -473,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); } @@ -481,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); } @@ -489,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); } @@ -497,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); } @@ -508,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); } @@ -569,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); } /// @@ -600,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); } /// @@ -625,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")); /// @@ -633,10 +664,10 @@ public static HeatFluxUnit ParseUnit(string str) /// Error parsing string. public static HeatFluxUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -651,10 +682,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -670,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; } @@ -720,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current HeatFlux. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(HeatFlux), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -813,256 +838,24 @@ public int CompareTo(object? obj) /// public int CompareTo(HeatFlux other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another HeatFlux within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(HeatFlux other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is HeatFlux otherTyped - && (tolerance is HeatFlux toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'HeatFlux'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(HeatFlux other, HeatFlux tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current HeatFlux. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(HeatFluxUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(HeatFluxUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(HeatFluxUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1077,137 +870,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(HeatFlux)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(HeatFlux)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(HeatFlux)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(HeatFlux)) - return this; - else if (conversionType == typeof(HeatFluxUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return HeatFlux.Info; - else if (conversionType == typeof(BaseDimensions)) - return HeatFlux.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(HeatFlux)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs b/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs index fb4ebf6926..93acc61172 100644 --- a/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -48,41 +43,97 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static HeatTransferCoefficient() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class HeatTransferCoefficientInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(0, 1, -3, 0, -1, 0, 0); - BaseUnit = HeatTransferCoefficientUnit.WattPerSquareMeterKelvin; - Units = Enum.GetValues(typeof(HeatTransferCoefficientUnit)).Cast().ToArray(); - Zero = new HeatTransferCoefficient(0, BaseUnit); - Info = new QuantityInfo("HeatTransferCoefficient", - new UnitInfo[] - { - new UnitInfo(HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit, "BtusPerHourSquareFootDegreeFahrenheit", BaseUnits.Undefined, "HeatTransferCoefficient"), - new UnitInfo(HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius, "CaloriesPerHourSquareMeterDegreeCelsius", BaseUnits.Undefined, "HeatTransferCoefficient"), - new UnitInfo(HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius, "KilocaloriesPerHourSquareMeterDegreeCelsius", BaseUnits.Undefined, "HeatTransferCoefficient"), - new UnitInfo(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, "WattsPerSquareMeterCelsius", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius), "HeatTransferCoefficient"), - new UnitInfo(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, "WattsPerSquareMeterKelvin", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin), "HeatTransferCoefficient"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public HeatTransferCoefficientInfo(string name, HeatTransferCoefficientUnit baseUnit, IEnumerable> unitMappings, HeatTransferCoefficient zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public HeatTransferCoefficientInfo(string name, HeatTransferCoefficientUnit baseUnit, IEnumerable> unitMappings, HeatTransferCoefficient zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, HeatTransferCoefficient.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.HeatTransferCoefficient", typeof(HeatTransferCoefficient).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the HeatTransferCoefficient quantity. + /// + /// A new instance of the class with the default settings. + public static HeatTransferCoefficientInfo CreateDefault() + { + return new HeatTransferCoefficientInfo(nameof(HeatTransferCoefficient), DefaultBaseUnit, GetDefaultMappings(), new HeatTransferCoefficient(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the HeatTransferCoefficient quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static HeatTransferCoefficientInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new HeatTransferCoefficientInfo(nameof(HeatTransferCoefficient), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new HeatTransferCoefficient(0, DefaultBaseUnit), DefaultBaseDimensions); + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// The for is T^-3MΘ^-1. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 1, -3, 0, -1, 0, 0); + + /// + /// The default base unit of HeatTransferCoefficient is WattPerSquareMeterKelvin. All conversions, as defined in the , go via this value. + /// + public static HeatTransferCoefficientUnit DefaultBaseUnit { get; } = HeatTransferCoefficientUnit.WattPerSquareMeterKelvin; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for HeatTransferCoefficient. + public static IEnumerable> GetDefaultMappings() + { + 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 = UnitsNetSetup.CreateQuantityInfo(HeatTransferCoefficientInfo.CreateDefault); } /// @@ -90,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; @@ -104,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); @@ -115,117 +166,104 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of HeatTransferCoefficient, which is WattPerSquareMeterKelvin. All conversions go via this value. /// - public static HeatTransferCoefficientUnit BaseUnit { get; } + public static HeatTransferCoefficientUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the HeatTransferCoefficient quantity. /// - public static HeatTransferCoefficientUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit WattPerSquareMeterKelvin. /// - public static HeatTransferCoefficient Zero { get; } - - /// - public static HeatTransferCoefficient AdditiveIdentity => Zero; + public static HeatTransferCoefficient Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public HeatTransferCoefficientUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => HeatTransferCoefficient.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -254,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); } @@ -262,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); } @@ -270,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); } @@ -278,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); } @@ -286,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); } @@ -297,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); } @@ -358,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); } /// @@ -389,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); } /// @@ -414,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")); /// @@ -422,10 +453,10 @@ public static HeatTransferCoefficientUnit ParseUnit(string str) /// Error parsing string. public static HeatTransferCoefficientUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -440,10 +471,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -459,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; } @@ -499,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current HeatTransferCoefficient. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(HeatTransferCoefficient), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -592,230 +617,24 @@ public int CompareTo(object? obj) /// public int CompareTo(HeatTransferCoefficient other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another HeatTransferCoefficient within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(HeatTransferCoefficient other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is HeatTransferCoefficient otherTyped - && (tolerance is HeatTransferCoefficient toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'HeatTransferCoefficient'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(HeatTransferCoefficient other, HeatTransferCoefficient tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current HeatTransferCoefficient. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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)); + #region Conversion Methods (explicit implementations for netstandard2.0) - 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 HeatTransferCoefficientUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(HeatTransferCoefficientUnit)} 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(HeatTransferCoefficientUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(HeatTransferCoefficientUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -830,137 +649,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(HeatTransferCoefficient)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(HeatTransferCoefficient)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(HeatTransferCoefficient)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(HeatTransferCoefficient)) - return this; - else if (conversionType == typeof(HeatTransferCoefficientUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return HeatTransferCoefficient.Info; - else if (conversionType == typeof(BaseDimensions)) - return HeatTransferCoefficient.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(HeatTransferCoefficient)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs b/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs index 1a04548857..5d1e625945 100644 --- a/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -54,40 +49,94 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static Illuminance() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class IlluminanceInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(-2, 0, 0, 0, 0, 0, 1); - BaseUnit = IlluminanceUnit.Lux; - Units = Enum.GetValues(typeof(IlluminanceUnit)).Cast().ToArray(); - Zero = new Illuminance(0, BaseUnit); - Info = new QuantityInfo("Illuminance", - new UnitInfo[] - { - new UnitInfo(IlluminanceUnit.Kilolux, "Kilolux", BaseUnits.Undefined, "Illuminance"), - new UnitInfo(IlluminanceUnit.Lux, "Lux", new BaseUnits(length: LengthUnit.Meter, luminousIntensity: LuminousIntensityUnit.Candela), "Illuminance"), - new UnitInfo(IlluminanceUnit.Megalux, "Megalux", new BaseUnits(length: LengthUnit.Millimeter, luminousIntensity: LuminousIntensityUnit.Candela), "Illuminance"), - new UnitInfo(IlluminanceUnit.Millilux, "Millilux", BaseUnits.Undefined, "Illuminance"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public IlluminanceInfo(string name, IlluminanceUnit baseUnit, IEnumerable> unitMappings, Illuminance zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public IlluminanceInfo(string name, IlluminanceUnit baseUnit, IEnumerable> unitMappings, Illuminance zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Illuminance.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Illuminance", typeof(Illuminance).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the Illuminance quantity. + /// + /// A new instance of the class with the default settings. + public static IlluminanceInfo CreateDefault() + { + return new IlluminanceInfo(nameof(Illuminance), DefaultBaseUnit, GetDefaultMappings(), new Illuminance(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Illuminance quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static IlluminanceInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new IlluminanceInfo(nameof(Illuminance), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Illuminance(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is L^-2J. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, 0, 0, 0, 0, 0, 1); + + /// + /// The default base unit of Illuminance is Lux. All conversions, as defined in the , go via this value. + /// + public static IlluminanceUnit DefaultBaseUnit { get; } = IlluminanceUnit.Lux; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Illuminance. + public static IEnumerable> GetDefaultMappings() + { + 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), + new QuantityValue(1, 1000000) + ); + yield return new (IlluminanceUnit.Millilux, "Millilux", "Millilux", BaseUnits.Undefined, + 1000 + ); + } + } + + static Illuminance() + { + Info = UnitsNetSetup.CreateQuantityInfo(IlluminanceInfo.CreateDefault); } /// @@ -95,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; @@ -109,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); @@ -120,110 +169,99 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Illuminance, which is Lux. All conversions go via this value. /// - public static IlluminanceUnit BaseUnit { get; } + public static IlluminanceUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Illuminance quantity. /// - public static IlluminanceUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Lux. /// - public static Illuminance Zero { get; } - - /// - public static Illuminance AdditiveIdentity => Zero; + public static Illuminance Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public IlluminanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Illuminance.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -252,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); } @@ -260,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); } @@ -268,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); } @@ -276,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); } @@ -287,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); } @@ -348,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); } /// @@ -379,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); } /// @@ -404,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")); /// @@ -412,10 +443,10 @@ public static IlluminanceUnit ParseUnit(string str) /// Error parsing string. public static IlluminanceUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -430,10 +461,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -449,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; } @@ -499,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Illuminance. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Illuminance), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -592,228 +617,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Illuminance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Illuminance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Illuminance other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Illuminance otherTyped - && (tolerance is Illuminance toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Illuminance'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Illuminance other, Illuminance tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Illuminance. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(IlluminanceUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(IlluminanceUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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), - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -828,137 +649,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Illuminance)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Illuminance)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Illuminance)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Illuminance)) - return this; - else if (conversionType == typeof(IlluminanceUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Illuminance.Info; - else if (conversionType == typeof(BaseDimensions)) - return Illuminance.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Illuminance)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Impulse.g.cs b/UnitsNet/GeneratedCode/Quantities/Impulse.g.cs index a56c939e48..f63630eb1f 100644 --- a/UnitsNet/GeneratedCode/Quantities/Impulse.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Impulse.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -48,49 +43,121 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ImpulseInfo: QuantityInfo + { + /// + public ImpulseInfo(string name, ImpulseUnit baseUnit, IEnumerable> unitMappings, Impulse zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ImpulseInfo(string name, ImpulseUnit baseUnit, IEnumerable> unitMappings, Impulse zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Impulse.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Impulse", typeof(Impulse).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Impulse quantity. + /// + /// A new instance of the class with the default settings. + public static ImpulseInfo CreateDefault() + { + return new ImpulseInfo(nameof(Impulse), DefaultBaseUnit, GetDefaultMappings(), new Impulse(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Impulse quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ImpulseInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ImpulseInfo(nameof(Impulse), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Impulse(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-1LM. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, 1, -1, 0, 0, 0, 0); + + /// + /// The default base unit of Impulse is NewtonSecond. All conversions, as defined in the , go via this value. + /// + public static ImpulseUnit DefaultBaseUnit { get; } = ImpulseUnit.NewtonSecond; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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), + 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() { - BaseDimensions = new BaseDimensions(1, 1, -1, 0, 0, 0, 0); - BaseUnit = ImpulseUnit.NewtonSecond; - Units = Enum.GetValues(typeof(ImpulseUnit)).Cast().ToArray(); - Zero = new Impulse(0, BaseUnit); - Info = new QuantityInfo("Impulse", - new UnitInfo[] - { - new UnitInfo(ImpulseUnit.CentinewtonSecond, "CentinewtonSeconds", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Impulse"), - new UnitInfo(ImpulseUnit.DecanewtonSecond, "DecanewtonSeconds", new BaseUnits(length: LengthUnit.Decameter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Impulse"), - new UnitInfo(ImpulseUnit.DecinewtonSecond, "DecinewtonSeconds", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Impulse"), - new UnitInfo(ImpulseUnit.KilogramMeterPerSecond, "KilogramMetersPerSecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Impulse"), - new UnitInfo(ImpulseUnit.KilonewtonSecond, "KilonewtonSeconds", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Impulse"), - new UnitInfo(ImpulseUnit.MeganewtonSecond, "MeganewtonSeconds", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Impulse"), - new UnitInfo(ImpulseUnit.MicronewtonSecond, "MicronewtonSeconds", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Impulse"), - new UnitInfo(ImpulseUnit.MillinewtonSecond, "MillinewtonSeconds", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Impulse"), - new UnitInfo(ImpulseUnit.NanonewtonSecond, "NanonewtonSeconds", new BaseUnits(length: LengthUnit.Nanometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Impulse"), - new UnitInfo(ImpulseUnit.NewtonSecond, "NewtonSeconds", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Impulse"), - new UnitInfo(ImpulseUnit.PoundFootPerSecond, "PoundFeetPerSecond", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Pound, time: DurationUnit.Second), "Impulse"), - new UnitInfo(ImpulseUnit.PoundForceSecond, "PoundForceSeconds", BaseUnits.Undefined, "Impulse"), - new UnitInfo(ImpulseUnit.SlugFootPerSecond, "SlugFeetPerSecond", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Slug, time: DurationUnit.Second), "Impulse"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ImpulseInfo.CreateDefault); } /// @@ -98,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; @@ -112,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); @@ -123,173 +190,144 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Impulse, which is NewtonSecond. All conversions go via this value. /// - public static ImpulseUnit BaseUnit { get; } + public static ImpulseUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Impulse quantity. /// - public static ImpulseUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit NewtonSecond. /// - public static Impulse Zero { get; } - - /// - public static Impulse AdditiveIdentity => Zero; + public static Impulse Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ImpulseUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Impulse.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -318,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); } @@ -326,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); } @@ -334,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); } @@ -342,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); } @@ -350,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); } @@ -358,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); } @@ -366,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); } @@ -374,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); } @@ -382,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); } @@ -390,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); } @@ -398,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); } @@ -406,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); } @@ -414,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); } @@ -425,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); } @@ -486,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); } /// @@ -517,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); } /// @@ -542,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")); /// @@ -550,10 +581,10 @@ public static ImpulseUnit ParseUnit(string str) /// Error parsing string. public static ImpulseUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -568,10 +599,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -587,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; } @@ -627,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Impulse. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Impulse), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -720,246 +745,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Impulse other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Impulse within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Impulse other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Impulse otherTyped - && (tolerance is Impulse toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Impulse'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Impulse other, Impulse tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Impulse. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(ImpulseUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(ImpulseUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -974,137 +777,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Impulse)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Impulse)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Impulse)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Impulse)) - return this; - else if (conversionType == typeof(ImpulseUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Impulse.Info; - else if (conversionType == typeof(BaseDimensions)) - return Impulse.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Impulse)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Information.g.cs b/UnitsNet/GeneratedCode/Quantities/Information.g.cs index bca77601ae..7b7126366c 100644 --- a/UnitsNet/GeneratedCode/Quantities/Information.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Information.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -48,62 +43,160 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class InformationInfo: QuantityInfo + { + /// + public InformationInfo(string name, InformationUnit baseUnit, IEnumerable> unitMappings, Information zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public InformationInfo(string name, InformationUnit baseUnit, IEnumerable> unitMappings, Information zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Information.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Information", typeof(Information).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Information quantity. + /// + /// A new instance of the class with the default settings. + public static InformationInfo CreateDefault() + { + return new InformationInfo(nameof(Information), DefaultBaseUnit, GetDefaultMappings(), new Information(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Information quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static InformationInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new InformationInfo(nameof(Information), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Information(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is . + /// + public static BaseDimensions DefaultBaseDimensions { get; } = BaseDimensions.Dimensionless; + + /// + /// The default base unit of Information is Bit. All conversions, as defined in the , go via this value. + /// + public static InformationUnit DefaultBaseUnit { get; } = InformationUnit.Bit; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Information. + public static IEnumerable> GetDefaultMappings() + { + yield return new (InformationUnit.Bit, "Bit", "Bits", 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.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.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.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.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.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.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.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.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.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.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.Terabit, "Terabit", "Terabits", BaseUnits.Undefined, + new QuantityValue(1, 1000000000000) + ); + yield return new (InformationUnit.Terabyte, "Terabyte", "Terabytes", BaseUnits.Undefined, + new QuantityValue(1, 8000000000000) + ); + } + } + static Information() { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = InformationUnit.Bit; - Units = Enum.GetValues(typeof(InformationUnit)).Cast().ToArray(); - Zero = new Information(0, BaseUnit); - Info = new QuantityInfo("Information", - new UnitInfo[] - { - new UnitInfo(InformationUnit.Bit, "Bits", BaseUnits.Undefined, "Information"), - new UnitInfo(InformationUnit.Byte, "Bytes", BaseUnits.Undefined, "Information"), - new UnitInfo(InformationUnit.Exabit, "Exabits", BaseUnits.Undefined, "Information"), - new UnitInfo(InformationUnit.Exabyte, "Exabytes", BaseUnits.Undefined, "Information"), - new UnitInfo(InformationUnit.Exbibit, "Exbibits", BaseUnits.Undefined, "Information"), - new UnitInfo(InformationUnit.Exbibyte, "Exbibytes", BaseUnits.Undefined, "Information"), - new UnitInfo(InformationUnit.Gibibit, "Gibibits", BaseUnits.Undefined, "Information"), - new UnitInfo(InformationUnit.Gibibyte, "Gibibytes", BaseUnits.Undefined, "Information"), - new UnitInfo(InformationUnit.Gigabit, "Gigabits", BaseUnits.Undefined, "Information"), - new UnitInfo(InformationUnit.Gigabyte, "Gigabytes", BaseUnits.Undefined, "Information"), - new UnitInfo(InformationUnit.Kibibit, "Kibibits", BaseUnits.Undefined, "Information"), - new UnitInfo(InformationUnit.Kibibyte, "Kibibytes", BaseUnits.Undefined, "Information"), - new UnitInfo(InformationUnit.Kilobit, "Kilobits", BaseUnits.Undefined, "Information"), - new UnitInfo(InformationUnit.Kilobyte, "Kilobytes", BaseUnits.Undefined, "Information"), - new UnitInfo(InformationUnit.Mebibit, "Mebibits", BaseUnits.Undefined, "Information"), - new UnitInfo(InformationUnit.Mebibyte, "Mebibytes", BaseUnits.Undefined, "Information"), - new UnitInfo(InformationUnit.Megabit, "Megabits", BaseUnits.Undefined, "Information"), - new UnitInfo(InformationUnit.Megabyte, "Megabytes", BaseUnits.Undefined, "Information"), - new UnitInfo(InformationUnit.Pebibit, "Pebibits", BaseUnits.Undefined, "Information"), - new UnitInfo(InformationUnit.Pebibyte, "Pebibytes", BaseUnits.Undefined, "Information"), - new UnitInfo(InformationUnit.Petabit, "Petabits", BaseUnits.Undefined, "Information"), - new UnitInfo(InformationUnit.Petabyte, "Petabytes", BaseUnits.Undefined, "Information"), - new UnitInfo(InformationUnit.Tebibit, "Tebibits", BaseUnits.Undefined, "Information"), - new UnitInfo(InformationUnit.Tebibyte, "Tebibytes", BaseUnits.Undefined, "Information"), - new UnitInfo(InformationUnit.Terabit, "Terabits", BaseUnits.Undefined, "Information"), - new UnitInfo(InformationUnit.Terabyte, "Terabytes", BaseUnits.Undefined, "Information"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(InformationInfo.CreateDefault); } /// @@ -111,7 +204,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; @@ -122,264 +215,209 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Information, which is Bit. All conversions go via this value. /// - public static InformationUnit BaseUnit { get; } + public static InformationUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Information quantity. /// - public static InformationUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Bit. /// - public static Information Zero { get; } - - /// - public static Information AdditiveIdentity => Zero; + public static Information Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public InformationUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Information.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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 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 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 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 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 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 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 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 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 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 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 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); #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.Exbibit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Exbibyte, 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.Gigabit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Gigabyte, 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.Kilobit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Kilobyte, 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.Megabit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Megabyte, 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.Petabit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Petabyte, 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.Terabit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Terabyte, 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.Exbibit, quantity => quantity.ToUnit(InformationUnit.Exbibit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Exbibyte, quantity => quantity.ToUnit(InformationUnit.Exbibyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Gibibit, quantity => quantity.ToUnit(InformationUnit.Gibibit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Gibibyte, quantity => quantity.ToUnit(InformationUnit.Gibibyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Gigabit, quantity => quantity.ToUnit(InformationUnit.Gigabit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Gigabyte, quantity => quantity.ToUnit(InformationUnit.Gigabyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Kibibit, quantity => quantity.ToUnit(InformationUnit.Kibibit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Kibibyte, quantity => quantity.ToUnit(InformationUnit.Kibibyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Kilobit, quantity => quantity.ToUnit(InformationUnit.Kilobit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Kilobyte, quantity => quantity.ToUnit(InformationUnit.Kilobyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Mebibit, quantity => quantity.ToUnit(InformationUnit.Mebibit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Mebibyte, quantity => quantity.ToUnit(InformationUnit.Mebibyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Megabit, quantity => quantity.ToUnit(InformationUnit.Megabit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Megabyte, quantity => quantity.ToUnit(InformationUnit.Megabyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Pebibit, quantity => quantity.ToUnit(InformationUnit.Pebibit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Pebibyte, quantity => quantity.ToUnit(InformationUnit.Pebibyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Petabit, quantity => quantity.ToUnit(InformationUnit.Petabit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Petabyte, quantity => quantity.ToUnit(InformationUnit.Petabyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Tebibit, quantity => quantity.ToUnit(InformationUnit.Tebibit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Tebibyte, quantity => quantity.ToUnit(InformationUnit.Tebibyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Terabit, quantity => quantity.ToUnit(InformationUnit.Terabit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Terabyte, quantity => quantity.ToUnit(InformationUnit.Terabyte)); - } - /// /// Get unit abbreviation string. /// @@ -408,7 +446,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); } @@ -416,7 +454,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); } @@ -424,7 +462,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); } @@ -432,7 +470,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); } @@ -440,7 +478,7 @@ public static Information FromExabytes(double value) /// /// Creates a from . /// - public static Information FromExbibits(double value) + public static Information FromExbibits(QuantityValue value) { return new Information(value, InformationUnit.Exbibit); } @@ -448,7 +486,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); } @@ -456,7 +494,7 @@ public static Information FromExbibytes(double value) /// /// Creates a from . /// - public static Information FromGibibits(double value) + public static Information FromGibibits(QuantityValue value) { return new Information(value, InformationUnit.Gibibit); } @@ -464,7 +502,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); } @@ -472,7 +510,7 @@ public static Information FromGibibytes(double value) /// /// Creates a from . /// - public static Information FromGigabits(double value) + public static Information FromGigabits(QuantityValue value) { return new Information(value, InformationUnit.Gigabit); } @@ -480,7 +518,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); } @@ -488,7 +526,7 @@ public static Information FromGigabytes(double value) /// /// Creates a from . /// - public static Information FromKibibits(double value) + public static Information FromKibibits(QuantityValue value) { return new Information(value, InformationUnit.Kibibit); } @@ -496,7 +534,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); } @@ -504,7 +542,7 @@ public static Information FromKibibytes(double value) /// /// Creates a from . /// - public static Information FromKilobits(double value) + public static Information FromKilobits(QuantityValue value) { return new Information(value, InformationUnit.Kilobit); } @@ -512,7 +550,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); } @@ -520,7 +558,7 @@ public static Information FromKilobytes(double value) /// /// Creates a from . /// - public static Information FromMebibits(double value) + public static Information FromMebibits(QuantityValue value) { return new Information(value, InformationUnit.Mebibit); } @@ -528,7 +566,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); } @@ -536,7 +574,7 @@ public static Information FromMebibytes(double value) /// /// Creates a from . /// - public static Information FromMegabits(double value) + public static Information FromMegabits(QuantityValue value) { return new Information(value, InformationUnit.Megabit); } @@ -544,7 +582,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); } @@ -552,7 +590,7 @@ public static Information FromMegabytes(double value) /// /// Creates a from . /// - public static Information FromPebibits(double value) + public static Information FromPebibits(QuantityValue value) { return new Information(value, InformationUnit.Pebibit); } @@ -560,7 +598,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); } @@ -568,7 +606,7 @@ public static Information FromPebibytes(double value) /// /// Creates a from . /// - public static Information FromPetabits(double value) + public static Information FromPetabits(QuantityValue value) { return new Information(value, InformationUnit.Petabit); } @@ -576,7 +614,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); } @@ -584,7 +622,7 @@ public static Information FromPetabytes(double value) /// /// Creates a from . /// - public static Information FromTebibits(double value) + public static Information FromTebibits(QuantityValue value) { return new Information(value, InformationUnit.Tebibit); } @@ -592,7 +630,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); } @@ -600,7 +638,7 @@ public static Information FromTebibytes(double value) /// /// Creates a from . /// - public static Information FromTerabits(double value) + public static Information FromTerabits(QuantityValue value) { return new Information(value, InformationUnit.Terabit); } @@ -608,7 +646,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); } @@ -619,7 +657,7 @@ public static Information FromTerabytes(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); } @@ -680,10 +718,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); } /// @@ -711,11 +746,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); } /// @@ -736,7 +767,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")); /// @@ -744,10 +775,10 @@ public static InformationUnit ParseUnit(string str) /// Error parsing string. public static InformationUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -762,10 +793,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -781,35 +812,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; } @@ -821,88 +852,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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Information. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Information), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -914,272 +939,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Information other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Information within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Information other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Information otherTyped - && (tolerance is Information toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Information'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Information other, Information tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Information. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(InformationUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - /// 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); - } + IQuantity IQuantity.ToUnit(InformationUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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.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.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.Gigabit, InformationUnit.Bit) => new Information((_value) * 1e9d, InformationUnit.Bit), - (InformationUnit.Gigabyte, 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.Kilobit, InformationUnit.Bit) => new Information((_value) * 1e3d, InformationUnit.Bit), - (InformationUnit.Kilobyte, 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.Megabit, InformationUnit.Bit) => new Information((_value) * 1e6d, InformationUnit.Bit), - (InformationUnit.Megabyte, InformationUnit.Bit) => new Information((_value * 8) * 1e6d, 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.Petabit, InformationUnit.Bit) => new Information((_value) * 1e15d, InformationUnit.Bit), - (InformationUnit.Petabyte, 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.Terabit, InformationUnit.Bit) => new Information((_value) * 1e12d, InformationUnit.Bit), - (InformationUnit.Terabyte, 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.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.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.Gigabit) => new Information((_value) / 1e9d, InformationUnit.Gigabit), - (InformationUnit.Bit, InformationUnit.Gigabyte) => new Information((_value / 8) / 1e9d, InformationUnit.Gigabyte), - (InformationUnit.Bit, InformationUnit.Kibibit) => new Information((_value) / 1024d, InformationUnit.Kibibit), - (InformationUnit.Bit, InformationUnit.Kibibyte) => new Information((_value / 8) / 1024d, InformationUnit.Kibibyte), - (InformationUnit.Bit, InformationUnit.Kilobit) => new Information((_value) / 1e3d, InformationUnit.Kilobit), - (InformationUnit.Bit, InformationUnit.Kilobyte) => new Information((_value / 8) / 1e3d, InformationUnit.Kilobyte), - (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.Megabit) => new Information((_value) / 1e6d, InformationUnit.Megabit), - (InformationUnit.Bit, InformationUnit.Megabyte) => new Information((_value / 8) / 1e6d, InformationUnit.Megabyte), - (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.Petabit) => new Information((_value) / 1e15d, InformationUnit.Petabit), - (InformationUnit.Bit, InformationUnit.Petabyte) => new Information((_value / 8) / 1e15d, InformationUnit.Petabyte), - (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.Terabit) => new Information((_value) / 1e12d, InformationUnit.Terabit), - (InformationUnit.Bit, InformationUnit.Terabyte) => new Information((_value / 8) / 1e12d, InformationUnit.Terabyte), - - _ => 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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(InformationUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1194,137 +971,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Information)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Information)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Information)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Information)) - return this; - else if (conversionType == typeof(InformationUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Information.Info; - else if (conversionType == typeof(BaseDimensions)) - return Information.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Information)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs b/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs index 99279811f4..43280d1a55 100644 --- a/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -48,50 +43,124 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class IrradianceInfo: QuantityInfo + { + /// + public IrradianceInfo(string name, IrradianceUnit baseUnit, IEnumerable> unitMappings, Irradiance zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public IrradianceInfo(string name, IrradianceUnit baseUnit, IEnumerable> unitMappings, Irradiance zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Irradiance.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Irradiance", typeof(Irradiance).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Irradiance quantity. + /// + /// A new instance of the class with the default settings. + public static IrradianceInfo CreateDefault() + { + return new IrradianceInfo(nameof(Irradiance), DefaultBaseUnit, GetDefaultMappings(), new Irradiance(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Irradiance quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static IrradianceInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new IrradianceInfo(nameof(Irradiance), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Irradiance(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-3M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 1, -3, 0, 0, 0, 0); + + /// + /// The default base unit of Irradiance is WattPerSquareMeter. All conversions, as defined in the , go via this value. + /// + public static IrradianceUnit DefaultBaseUnit { get; } = IrradianceUnit.WattPerSquareMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Irradiance. + public static IEnumerable> GetDefaultMappings() + { + 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() { - BaseDimensions = new BaseDimensions(0, 1, -3, 0, 0, 0, 0); - BaseUnit = IrradianceUnit.WattPerSquareMeter; - Units = Enum.GetValues(typeof(IrradianceUnit)).Cast().ToArray(); - Zero = new Irradiance(0, BaseUnit); - Info = new QuantityInfo("Irradiance", - new UnitInfo[] - { - new UnitInfo(IrradianceUnit.KilowattPerSquareCentimeter, "KilowattsPerSquareCentimeter", BaseUnits.Undefined, "Irradiance"), - new UnitInfo(IrradianceUnit.KilowattPerSquareMeter, "KilowattsPerSquareMeter", BaseUnits.Undefined, "Irradiance"), - new UnitInfo(IrradianceUnit.MegawattPerSquareCentimeter, "MegawattsPerSquareCentimeter", BaseUnits.Undefined, "Irradiance"), - new UnitInfo(IrradianceUnit.MegawattPerSquareMeter, "MegawattsPerSquareMeter", BaseUnits.Undefined, "Irradiance"), - new UnitInfo(IrradianceUnit.MicrowattPerSquareCentimeter, "MicrowattsPerSquareCentimeter", BaseUnits.Undefined, "Irradiance"), - new UnitInfo(IrradianceUnit.MicrowattPerSquareMeter, "MicrowattsPerSquareMeter", new BaseUnits(mass: MassUnit.Milligram, time: DurationUnit.Second), "Irradiance"), - new UnitInfo(IrradianceUnit.MilliwattPerSquareCentimeter, "MilliwattsPerSquareCentimeter", BaseUnits.Undefined, "Irradiance"), - new UnitInfo(IrradianceUnit.MilliwattPerSquareMeter, "MilliwattsPerSquareMeter", new BaseUnits(mass: MassUnit.Gram, time: DurationUnit.Second), "Irradiance"), - new UnitInfo(IrradianceUnit.NanowattPerSquareCentimeter, "NanowattsPerSquareCentimeter", BaseUnits.Undefined, "Irradiance"), - new UnitInfo(IrradianceUnit.NanowattPerSquareMeter, "NanowattsPerSquareMeter", new BaseUnits(mass: MassUnit.Microgram, time: DurationUnit.Second), "Irradiance"), - new UnitInfo(IrradianceUnit.PicowattPerSquareCentimeter, "PicowattsPerSquareCentimeter", BaseUnits.Undefined, "Irradiance"), - new UnitInfo(IrradianceUnit.PicowattPerSquareMeter, "PicowattsPerSquareMeter", new BaseUnits(mass: MassUnit.Nanogram, time: DurationUnit.Second), "Irradiance"), - new UnitInfo(IrradianceUnit.WattPerSquareCentimeter, "WattsPerSquareCentimeter", BaseUnits.Undefined, "Irradiance"), - new UnitInfo(IrradianceUnit.WattPerSquareMeter, "WattsPerSquareMeter", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second), "Irradiance"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(IrradianceInfo.CreateDefault); } /// @@ -99,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; @@ -113,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); @@ -124,180 +193,149 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Irradiance, which is WattPerSquareMeter. All conversions go via this value. /// - public static IrradianceUnit BaseUnit { get; } + public static IrradianceUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Irradiance quantity. /// - public static IrradianceUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit WattPerSquareMeter. /// - public static Irradiance Zero { get; } - - /// - public static Irradiance AdditiveIdentity => Zero; + public static Irradiance Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public IrradianceUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Irradiance.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -326,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); } @@ -334,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); } @@ -342,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); } @@ -350,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); } @@ -358,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); } @@ -366,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); } @@ -374,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); } @@ -382,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); } @@ -390,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); } @@ -398,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); } @@ -406,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); } @@ -414,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); } @@ -422,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); } @@ -430,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); } @@ -441,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); } @@ -502,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); } /// @@ -533,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); } /// @@ -558,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")); /// @@ -566,10 +597,10 @@ public static IrradianceUnit ParseUnit(string str) /// Error parsing string. public static IrradianceUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -584,10 +615,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -603,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; } @@ -643,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Irradiance. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Irradiance), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -736,248 +761,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Irradiance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Irradiance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Irradiance other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Irradiance otherTyped - && (tolerance is Irradiance toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Irradiance'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Irradiance other, Irradiance tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Irradiance. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(IrradianceUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(IrradianceUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -992,137 +793,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Irradiance)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Irradiance)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Irradiance)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Irradiance)) - return this; - else if (conversionType == typeof(IrradianceUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Irradiance.Info; - else if (conversionType == typeof(BaseDimensions)) - return Irradiance.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Irradiance)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs b/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs index 09e764f34d..b43434ab72 100644 --- a/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,45 +46,109 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class IrradiationInfo: QuantityInfo + { + /// + public IrradiationInfo(string name, IrradiationUnit baseUnit, IEnumerable> unitMappings, Irradiation zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public IrradiationInfo(string name, IrradiationUnit baseUnit, IEnumerable> unitMappings, Irradiation zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Irradiation.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Irradiation", typeof(Irradiation).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Irradiation quantity. + /// + /// A new instance of the class with the default settings. + public static IrradiationInfo CreateDefault() + { + return new IrradiationInfo(nameof(Irradiation), DefaultBaseUnit, GetDefaultMappings(), new Irradiation(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Irradiation quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static IrradiationInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new IrradiationInfo(nameof(Irradiation), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Irradiation(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-2M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 1, -2, 0, 0, 0, 0); + + /// + /// The default base unit of Irradiation is JoulePerSquareMeter. All conversions, as defined in the , go via this value. + /// + public static IrradiationUnit DefaultBaseUnit { get; } = IrradiationUnit.JoulePerSquareMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Irradiation. + public static IEnumerable> GetDefaultMappings() + { + 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, + 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() { - BaseDimensions = new BaseDimensions(0, 1, -2, 0, 0, 0, 0); - BaseUnit = IrradiationUnit.JoulePerSquareMeter; - Units = Enum.GetValues(typeof(IrradiationUnit)).Cast().ToArray(); - Zero = new Irradiation(0, BaseUnit); - Info = new QuantityInfo("Irradiation", - new UnitInfo[] - { - new UnitInfo(IrradiationUnit.BtuPerSquareFoot, "BtusPerSquareFoot", BaseUnits.Undefined, "Irradiation"), - new UnitInfo(IrradiationUnit.JoulePerSquareCentimeter, "JoulesPerSquareCentimeter", BaseUnits.Undefined, "Irradiation"), - new UnitInfo(IrradiationUnit.JoulePerSquareMeter, "JoulesPerSquareMeter", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second), "Irradiation"), - new UnitInfo(IrradiationUnit.JoulePerSquareMillimeter, "JoulesPerSquareMillimeter", BaseUnits.Undefined, "Irradiation"), - new UnitInfo(IrradiationUnit.KilobtuPerSquareFoot, "KilobtusPerSquareFoot", BaseUnits.Undefined, "Irradiation"), - new UnitInfo(IrradiationUnit.KilojoulePerSquareMeter, "KilojoulesPerSquareMeter", BaseUnits.Undefined, "Irradiation"), - new UnitInfo(IrradiationUnit.KilowattHourPerSquareMeter, "KilowattHoursPerSquareMeter", BaseUnits.Undefined, "Irradiation"), - new UnitInfo(IrradiationUnit.MillijoulePerSquareCentimeter, "MillijoulesPerSquareCentimeter", BaseUnits.Undefined, "Irradiation"), - new UnitInfo(IrradiationUnit.WattHourPerSquareMeter, "WattHoursPerSquareMeter", BaseUnits.Undefined, "Irradiation"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(IrradiationInfo.CreateDefault); } /// @@ -97,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; @@ -111,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); @@ -122,145 +181,124 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Irradiation, which is JoulePerSquareMeter. All conversions go via this value. /// - public static IrradiationUnit BaseUnit { get; } + public static IrradiationUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Irradiation quantity. /// - public static IrradiationUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerSquareMeter. /// - public static Irradiation Zero { get; } - - /// - public static Irradiation AdditiveIdentity => Zero; + public static Irradiation Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public IrradiationUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Irradiation.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -289,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); } @@ -297,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); } @@ -305,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); } @@ -313,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); } @@ -321,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); } @@ -329,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); } @@ -337,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); } @@ -345,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); } @@ -353,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); } @@ -364,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); } @@ -425,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); } /// @@ -456,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); } /// @@ -481,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")); /// @@ -489,10 +520,10 @@ public static IrradiationUnit ParseUnit(string str) /// Error parsing string. public static IrradiationUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -507,10 +538,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -526,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; } @@ -566,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Irradiation. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Irradiation), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -659,238 +684,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Irradiation other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Irradiation within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Irradiation other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Irradiation otherTyped - && (tolerance is Irradiation toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Irradiation'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Irradiation other, Irradiation tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Irradiation. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(IrradiationUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(IrradiationUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -905,137 +716,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Irradiation)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Irradiation)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Irradiation)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Irradiation)) - return this; - else if (conversionType == typeof(IrradiationUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Irradiation.Info; - else if (conversionType == typeof(BaseDimensions)) - return Irradiation.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Irradiation)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Jerk.g.cs b/UnitsNet/GeneratedCode/Quantities/Jerk.g.cs index 24b2653260..bf8e1d52cf 100644 --- a/UnitsNet/GeneratedCode/Quantities/Jerk.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Jerk.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -51,47 +46,115 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class JerkInfo: QuantityInfo + { + /// + public JerkInfo(string name, JerkUnit baseUnit, IEnumerable> unitMappings, Jerk zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public JerkInfo(string name, JerkUnit baseUnit, IEnumerable> unitMappings, Jerk zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Jerk.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Jerk", typeof(Jerk).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Jerk quantity. + /// + /// A new instance of the class with the default settings. + public static JerkInfo CreateDefault() + { + return new JerkInfo(nameof(Jerk), DefaultBaseUnit, GetDefaultMappings(), new Jerk(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Jerk quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static JerkInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new JerkInfo(nameof(Jerk), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Jerk(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-3L. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, 0, -3, 0, 0, 0, 0); + + /// + /// The default base unit of Jerk is MeterPerSecondCubed. All conversions, as defined in the , go via this value. + /// + public static JerkUnit DefaultBaseUnit { get; } = JerkUnit.MeterPerSecondCubed; + + /// + /// Retrieves the default mappings for . + /// + /// 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), + 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), + 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() { - BaseDimensions = new BaseDimensions(1, 0, -3, 0, 0, 0, 0); - BaseUnit = JerkUnit.MeterPerSecondCubed; - Units = Enum.GetValues(typeof(JerkUnit)).Cast().ToArray(); - Zero = new Jerk(0, BaseUnit); - Info = new QuantityInfo("Jerk", - new UnitInfo[] - { - new UnitInfo(JerkUnit.CentimeterPerSecondCubed, "CentimetersPerSecondCubed", new BaseUnits(length: LengthUnit.Centimeter, time: DurationUnit.Second), "Jerk"), - new UnitInfo(JerkUnit.DecimeterPerSecondCubed, "DecimetersPerSecondCubed", new BaseUnits(length: LengthUnit.Decimeter, time: DurationUnit.Second), "Jerk"), - new UnitInfo(JerkUnit.FootPerSecondCubed, "FeetPerSecondCubed", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Second), "Jerk"), - new UnitInfo(JerkUnit.InchPerSecondCubed, "InchesPerSecondCubed", new BaseUnits(length: LengthUnit.Inch, time: DurationUnit.Second), "Jerk"), - new UnitInfo(JerkUnit.KilometerPerSecondCubed, "KilometersPerSecondCubed", new BaseUnits(length: LengthUnit.Kilometer, time: DurationUnit.Second), "Jerk"), - new UnitInfo(JerkUnit.MeterPerSecondCubed, "MetersPerSecondCubed", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second), "Jerk"), - new UnitInfo(JerkUnit.MicrometerPerSecondCubed, "MicrometersPerSecondCubed", new BaseUnits(length: LengthUnit.Micrometer, time: DurationUnit.Second), "Jerk"), - new UnitInfo(JerkUnit.MillimeterPerSecondCubed, "MillimetersPerSecondCubed", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Second), "Jerk"), - new UnitInfo(JerkUnit.MillistandardGravitiesPerSecond, "MillistandardGravitiesPerSecond", BaseUnits.Undefined, "Jerk"), - new UnitInfo(JerkUnit.NanometerPerSecondCubed, "NanometersPerSecondCubed", new BaseUnits(length: LengthUnit.Nanometer, time: DurationUnit.Second), "Jerk"), - new UnitInfo(JerkUnit.StandardGravitiesPerSecond, "StandardGravitiesPerSecond", BaseUnits.Undefined, "Jerk"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(JerkInfo.CreateDefault); } /// @@ -99,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; @@ -113,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); @@ -124,159 +187,134 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Jerk, which is MeterPerSecondCubed. All conversions go via this value. /// - public static JerkUnit BaseUnit { get; } + public static JerkUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Jerk quantity. /// - public static JerkUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit MeterPerSecondCubed. /// - public static Jerk Zero { get; } - - /// - public static Jerk AdditiveIdentity => Zero; + public static Jerk Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public JerkUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Jerk.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -305,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); } @@ -313,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); } @@ -321,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); } @@ -329,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); } @@ -337,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); } @@ -345,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); } @@ -353,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); } @@ -361,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); } @@ -369,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); } @@ -377,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); } @@ -385,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); } @@ -396,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); } @@ -457,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); } /// @@ -488,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); } /// @@ -513,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")); /// @@ -521,10 +552,10 @@ public static JerkUnit ParseUnit(string str) /// Error parsing string. public static JerkUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -539,10 +570,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -558,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; } @@ -608,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Jerk. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Jerk), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -701,242 +726,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Jerk other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Jerk within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Jerk other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Jerk otherTyped - && (tolerance is Jerk toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Jerk'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Jerk other, Jerk tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Jerk. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(JerkUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(JerkUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -951,137 +758,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Jerk)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Jerk)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Jerk)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Jerk)) - return this; - else if (conversionType == typeof(JerkUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Jerk.Info; - else if (conversionType == typeof(BaseDimensions)) - return Jerk.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Jerk)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs b/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs index a1b8edc5a9..3cae9ad150 100644 --- a/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -57,45 +52,109 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class KinematicViscosityInfo: QuantityInfo + { + /// + public KinematicViscosityInfo(string name, KinematicViscosityUnit baseUnit, IEnumerable> unitMappings, KinematicViscosity zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public KinematicViscosityInfo(string name, KinematicViscosityUnit baseUnit, IEnumerable> unitMappings, KinematicViscosity zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, KinematicViscosity.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.KinematicViscosity", typeof(KinematicViscosity).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the KinematicViscosity quantity. + /// + /// A new instance of the class with the default settings. + public static KinematicViscosityInfo CreateDefault() + { + return new KinematicViscosityInfo(nameof(KinematicViscosity), DefaultBaseUnit, GetDefaultMappings(), new KinematicViscosity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the KinematicViscosity quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static KinematicViscosityInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new KinematicViscosityInfo(nameof(KinematicViscosity), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new KinematicViscosity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-1L^2. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 0, -1, 0, 0, 0, 0); + + /// + /// The default base unit of KinematicViscosity is SquareMeterPerSecond. All conversions, as defined in the , go via this value. + /// + public static KinematicViscosityUnit DefaultBaseUnit { get; } = KinematicViscosityUnit.SquareMeterPerSecond; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for KinematicViscosity. + public static IEnumerable> GetDefaultMappings() + { + 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, + 10000 + ); + } + } + static KinematicViscosity() { - BaseDimensions = new BaseDimensions(2, 0, -1, 0, 0, 0, 0); - BaseUnit = KinematicViscosityUnit.SquareMeterPerSecond; - Units = Enum.GetValues(typeof(KinematicViscosityUnit)).Cast().ToArray(); - Zero = new KinematicViscosity(0, BaseUnit); - Info = new QuantityInfo("KinematicViscosity", - new UnitInfo[] - { - new UnitInfo(KinematicViscosityUnit.Centistokes, "Centistokes", BaseUnits.Undefined, "KinematicViscosity"), - new UnitInfo(KinematicViscosityUnit.Decistokes, "Decistokes", BaseUnits.Undefined, "KinematicViscosity"), - new UnitInfo(KinematicViscosityUnit.Kilostokes, "Kilostokes", BaseUnits.Undefined, "KinematicViscosity"), - new UnitInfo(KinematicViscosityUnit.Microstokes, "Microstokes", BaseUnits.Undefined, "KinematicViscosity"), - new UnitInfo(KinematicViscosityUnit.Millistokes, "Millistokes", BaseUnits.Undefined, "KinematicViscosity"), - new UnitInfo(KinematicViscosityUnit.Nanostokes, "Nanostokes", BaseUnits.Undefined, "KinematicViscosity"), - new UnitInfo(KinematicViscosityUnit.SquareFootPerSecond, "SquareFeetPerSecond", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Second), "KinematicViscosity"), - new UnitInfo(KinematicViscosityUnit.SquareMeterPerSecond, "SquareMetersPerSecond", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second), "KinematicViscosity"), - new UnitInfo(KinematicViscosityUnit.Stokes, "Stokes", BaseUnits.Undefined, "KinematicViscosity"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(KinematicViscosityInfo.CreateDefault); } /// @@ -103,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; @@ -117,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); @@ -128,145 +187,124 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of KinematicViscosity, which is SquareMeterPerSecond. All conversions go via this value. /// - public static KinematicViscosityUnit BaseUnit { get; } + public static KinematicViscosityUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the KinematicViscosity quantity. /// - public static KinematicViscosityUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeterPerSecond. /// - public static KinematicViscosity Zero { get; } - - /// - public static KinematicViscosity AdditiveIdentity => Zero; + public static KinematicViscosity Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public KinematicViscosityUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => KinematicViscosity.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -295,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); } @@ -303,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); } @@ -311,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); } @@ -319,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); } @@ -327,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); } @@ -335,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); } @@ -343,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); } @@ -351,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); } @@ -359,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); } @@ -370,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); } @@ -431,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); } /// @@ -462,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); } /// @@ -487,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")); /// @@ -495,10 +526,10 @@ public static KinematicViscosityUnit ParseUnit(string str) /// Error parsing string. public static KinematicViscosityUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -513,10 +544,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -532,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; } @@ -600,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current KinematicViscosity. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(KinematicViscosity), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -693,238 +718,24 @@ public int CompareTo(object? obj) /// public int CompareTo(KinematicViscosity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another KinematicViscosity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(KinematicViscosity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is KinematicViscosity otherTyped - && (tolerance is KinematicViscosity toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'KinematicViscosity'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(KinematicViscosity other, KinematicViscosity tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current KinematicViscosity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(KinematicViscosityUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(KinematicViscosityUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -939,137 +750,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(KinematicViscosity)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(KinematicViscosity)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(KinematicViscosity)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(KinematicViscosity)) - return this; - else if (conversionType == typeof(KinematicViscosityUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return KinematicViscosity.Info; - else if (conversionType == typeof(BaseDimensions)) - return KinematicViscosity.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(KinematicViscosity)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/LeakRate.g.cs b/UnitsNet/GeneratedCode/Quantities/LeakRate.g.cs index 8cf019115c..ee07b11bf2 100644 --- a/UnitsNet/GeneratedCode/Quantities/LeakRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LeakRate.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,39 +46,91 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static LeakRate() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class LeakRateInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); - BaseUnit = LeakRateUnit.PascalCubicMeterPerSecond; - Units = Enum.GetValues(typeof(LeakRateUnit)).Cast().ToArray(); - Zero = new LeakRate(0, BaseUnit); - Info = new QuantityInfo("LeakRate", - new UnitInfo[] - { - new UnitInfo(LeakRateUnit.MillibarLiterPerSecond, "MillibarLitersPerSecond", BaseUnits.Undefined, "LeakRate"), - new UnitInfo(LeakRateUnit.PascalCubicMeterPerSecond, "PascalCubicMetersPerSecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "LeakRate"), - new UnitInfo(LeakRateUnit.TorrLiterPerSecond, "TorrLitersPerSecond", BaseUnits.Undefined, "LeakRate"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public LeakRateInfo(string name, LeakRateUnit baseUnit, IEnumerable> unitMappings, LeakRate zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public LeakRateInfo(string name, LeakRateUnit baseUnit, IEnumerable> unitMappings, LeakRate zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, LeakRate.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.LeakRate", typeof(LeakRate).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the LeakRate quantity. + /// + /// A new instance of the class with the default settings. + public static LeakRateInfo CreateDefault() + { + return new LeakRateInfo(nameof(LeakRate), DefaultBaseUnit, GetDefaultMappings(), new LeakRate(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the LeakRate quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static LeakRateInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new LeakRateInfo(nameof(LeakRate), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new LeakRate(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-3L^2M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); + + /// + /// The default base unit of LeakRate is PascalCubicMeterPerSecond. All conversions, as defined in the , go via this value. + /// + public static LeakRateUnit DefaultBaseUnit { get; } = LeakRateUnit.PascalCubicMeterPerSecond; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for LeakRate. + public static IEnumerable> GetDefaultMappings() + { + 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, + new QuantityValue(15, 2) + ); + } + } + + static LeakRate() + { + Info = UnitsNetSetup.CreateQuantityInfo(LeakRateInfo.CreateDefault); } /// @@ -91,7 +138,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; @@ -105,7 +152,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); @@ -116,103 +163,94 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of LeakRate, which is PascalCubicMeterPerSecond. All conversions go via this value. /// - public static LeakRateUnit BaseUnit { get; } + public static LeakRateUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the LeakRate quantity. /// - public static LeakRateUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit PascalCubicMeterPerSecond. /// - public static LeakRate Zero { get; } - - /// - public static LeakRate AdditiveIdentity => Zero; + public static LeakRate Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public LeakRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => LeakRate.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #region Conversion Properties /// - /// 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.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.MillibarLiterPerSecond, quantity => quantity.ToUnit(LeakRateUnit.MillibarLiterPerSecond)); - unitConverter.SetConversionFunction(LeakRateUnit.PascalCubicMeterPerSecond, LeakRateUnit.TorrLiterPerSecond, quantity => quantity.ToUnit(LeakRateUnit.TorrLiterPerSecond)); - } - /// /// Get unit abbreviation string. /// @@ -241,7 +279,7 @@ public static string GetAbbreviation(LeakRateUnit unit, IFormatProvider? provide /// /// Creates a from . /// - public static LeakRate FromMillibarLitersPerSecond(double value) + public static LeakRate FromMillibarLitersPerSecond(QuantityValue value) { return new LeakRate(value, LeakRateUnit.MillibarLiterPerSecond); } @@ -249,7 +287,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); } @@ -257,7 +295,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); } @@ -268,7 +306,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); } @@ -329,10 +367,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); } /// @@ -360,11 +395,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); } /// @@ -385,7 +416,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")); /// @@ -393,10 +424,10 @@ public static LeakRateUnit ParseUnit(string str) /// Error parsing string. public static LeakRateUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -411,10 +442,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -430,35 +461,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; } @@ -470,88 +501,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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current LeakRate. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(LeakRate), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -563,226 +588,24 @@ public int CompareTo(object? obj) /// public int CompareTo(LeakRate other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another LeakRate within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(LeakRate other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is LeakRate otherTyped - && (tolerance is LeakRate toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'LeakRate'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(LeakRate other, LeakRate tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current LeakRate. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(LeakRateUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(LeakRateUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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.MillibarLiterPerSecond, LeakRateUnit.PascalCubicMeterPerSecond) => new LeakRate(_value / 10, LeakRateUnit.PascalCubicMeterPerSecond), - (LeakRateUnit.TorrLiterPerSecond, LeakRateUnit.PascalCubicMeterPerSecond) => new LeakRate(_value / 7.5, LeakRateUnit.PascalCubicMeterPerSecond), - - // BaseUnit -> LeakRateUnit - (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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -797,137 +620,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(LeakRate)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(LeakRate)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(LeakRate)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(LeakRate)) - return this; - else if (conversionType == typeof(LeakRateUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return LeakRate.Info; - else if (conversionType == typeof(BaseDimensions)) - return LeakRate.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(LeakRate)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Length.g.cs b/UnitsNet/GeneratedCode/Quantities/Length.g.cs index 114cd08a40..18451e8cb1 100644 --- a/UnitsNet/GeneratedCode/Quantities/Length.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Length.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -68,78 +63,208 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class LengthInfo: QuantityInfo + { + /// + public LengthInfo(string name, LengthUnit baseUnit, IEnumerable> unitMappings, Length zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public LengthInfo(string name, LengthUnit baseUnit, IEnumerable> unitMappings, Length zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Length.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Length", typeof(Length).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Length quantity. + /// + /// A new instance of the class with the default settings. + public static LengthInfo CreateDefault() + { + return new LengthInfo(nameof(Length), DefaultBaseUnit, GetDefaultMappings(), new Length(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Length quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static LengthInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new LengthInfo(nameof(Length), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Length(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is L. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); + + /// + /// The default base unit of Length is Meter. All conversions, as defined in the , go via this value. + /// + public static LengthUnit DefaultBaseUnit { get; } = LengthUnit.Meter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Length. + public static IEnumerable> GetDefaultMappings() + { + 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), + 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() { - BaseDimensions = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); - BaseUnit = LengthUnit.Meter; - Units = Enum.GetValues(typeof(LengthUnit)).Cast().ToArray(); - Zero = new Length(0, BaseUnit); - Info = new QuantityInfo("Length", - new UnitInfo[] - { - new UnitInfo(LengthUnit.Angstrom, "Angstroms", new BaseUnits(length: LengthUnit.Angstrom), "Length"), - new UnitInfo(LengthUnit.AstronomicalUnit, "AstronomicalUnits", new BaseUnits(length: LengthUnit.AstronomicalUnit), "Length"), - new UnitInfo(LengthUnit.Centimeter, "Centimeters", new BaseUnits(length: LengthUnit.Centimeter), "Length"), - new UnitInfo(LengthUnit.Chain, "Chains", new BaseUnits(length: LengthUnit.Chain), "Length"), - new UnitInfo(LengthUnit.DataMile, "DataMiles", new BaseUnits(length: LengthUnit.DataMile), "Length"), - new UnitInfo(LengthUnit.Decameter, "Decameters", new BaseUnits(length: LengthUnit.Decameter), "Length"), - new UnitInfo(LengthUnit.Decimeter, "Decimeters", new BaseUnits(length: LengthUnit.Decimeter), "Length"), - new UnitInfo(LengthUnit.DtpPica, "DtpPicas", new BaseUnits(length: LengthUnit.DtpPica), "Length"), - new UnitInfo(LengthUnit.DtpPoint, "DtpPoints", new BaseUnits(length: LengthUnit.DtpPoint), "Length"), - new UnitInfo(LengthUnit.Fathom, "Fathoms", new BaseUnits(length: LengthUnit.Fathom), "Length"), - new UnitInfo(LengthUnit.Femtometer, "Femtometers", new BaseUnits(length: LengthUnit.Femtometer), "Length"), - new UnitInfo(LengthUnit.Foot, "Feet", new BaseUnits(length: LengthUnit.Foot), "Length"), - new UnitInfo(LengthUnit.Gigameter, "Gigameters", new BaseUnits(length: LengthUnit.Gigameter), "Length"), - new UnitInfo(LengthUnit.Hand, "Hands", new BaseUnits(length: LengthUnit.Hand), "Length"), - new UnitInfo(LengthUnit.Hectometer, "Hectometers", new BaseUnits(length: LengthUnit.Hectometer), "Length"), - new UnitInfo(LengthUnit.Inch, "Inches", new BaseUnits(length: LengthUnit.Inch), "Length"), - new UnitInfo(LengthUnit.Kilofoot, "Kilofeet", new BaseUnits(length: LengthUnit.Kilofoot), "Length"), - new UnitInfo(LengthUnit.KilolightYear, "KilolightYears", new BaseUnits(length: LengthUnit.KilolightYear), "Length"), - new UnitInfo(LengthUnit.Kilometer, "Kilometers", new BaseUnits(length: LengthUnit.Kilometer), "Length"), - new UnitInfo(LengthUnit.Kiloparsec, "Kiloparsecs", new BaseUnits(length: LengthUnit.Kiloparsec), "Length"), - new UnitInfo(LengthUnit.Kiloyard, "Kiloyards", new BaseUnits(length: LengthUnit.Kiloyard), "Length"), - new UnitInfo(LengthUnit.LightYear, "LightYears", new BaseUnits(length: LengthUnit.LightYear), "Length"), - new UnitInfo(LengthUnit.MegalightYear, "MegalightYears", new BaseUnits(length: LengthUnit.MegalightYear), "Length"), - new UnitInfo(LengthUnit.Megameter, "Megameters", new BaseUnits(length: LengthUnit.Megameter), "Length"), - new UnitInfo(LengthUnit.Megaparsec, "Megaparsecs", new BaseUnits(length: LengthUnit.Megaparsec), "Length"), - new UnitInfo(LengthUnit.Meter, "Meters", new BaseUnits(length: LengthUnit.Meter), "Length"), - new UnitInfo(LengthUnit.Microinch, "Microinches", new BaseUnits(length: LengthUnit.Microinch), "Length"), - new UnitInfo(LengthUnit.Micrometer, "Micrometers", new BaseUnits(length: LengthUnit.Micrometer), "Length"), - new UnitInfo(LengthUnit.Mil, "Mils", new BaseUnits(length: LengthUnit.Mil), "Length"), - new UnitInfo(LengthUnit.Mile, "Miles", new BaseUnits(length: LengthUnit.Mile), "Length"), - new UnitInfo(LengthUnit.Millimeter, "Millimeters", new BaseUnits(length: LengthUnit.Millimeter), "Length"), - new UnitInfo(LengthUnit.Nanometer, "Nanometers", new BaseUnits(length: LengthUnit.Nanometer), "Length"), - new UnitInfo(LengthUnit.NauticalMile, "NauticalMiles", new BaseUnits(length: LengthUnit.NauticalMile), "Length"), - new UnitInfo(LengthUnit.Parsec, "Parsecs", new BaseUnits(length: LengthUnit.Parsec), "Length"), - new UnitInfo(LengthUnit.Picometer, "Picometers", new BaseUnits(length: LengthUnit.Picometer), "Length"), - new UnitInfo(LengthUnit.PrinterPica, "PrinterPicas", new BaseUnits(length: LengthUnit.PrinterPica), "Length"), - new UnitInfo(LengthUnit.PrinterPoint, "PrinterPoints", new BaseUnits(length: LengthUnit.PrinterPoint), "Length"), - new UnitInfo(LengthUnit.Shackle, "Shackles", new BaseUnits(length: LengthUnit.Shackle), "Length"), - new UnitInfo(LengthUnit.SolarRadius, "SolarRadiuses", new BaseUnits(length: LengthUnit.SolarRadius), "Length"), - new UnitInfo(LengthUnit.Twip, "Twips", new BaseUnits(length: LengthUnit.Twip), "Length"), - new UnitInfo(LengthUnit.UsSurveyFoot, "UsSurveyFeet", new BaseUnits(length: LengthUnit.UsSurveyFoot), "Length"), - new UnitInfo(LengthUnit.Yard, "Yards", new BaseUnits(length: LengthUnit.Yard), "Length"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(LengthInfo.CreateDefault); } /// @@ -147,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; @@ -161,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); @@ -172,376 +297,289 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Length, which is Meter. All conversions go via this value. /// - public static LengthUnit BaseUnit { get; } + public static LengthUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Length quantity. /// - public static LengthUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Meter. /// - public static Length Zero { get; } - - /// - public static Length AdditiveIdentity => Zero; + public static Length Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public LengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Length.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -570,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); } @@ -578,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); } @@ -586,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); } @@ -594,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); } @@ -602,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); } @@ -610,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); } @@ -618,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); } @@ -626,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); } @@ -634,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); } @@ -642,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); } @@ -650,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); } @@ -658,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); } @@ -666,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); } @@ -674,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); } @@ -682,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); } @@ -690,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); } @@ -698,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); } @@ -706,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); } @@ -714,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); } @@ -722,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); } @@ -730,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); } @@ -738,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); } @@ -746,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); } @@ -754,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); } @@ -762,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); } @@ -770,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); } @@ -778,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); } @@ -786,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); } @@ -794,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); } @@ -802,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); } @@ -810,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); } @@ -818,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); } @@ -826,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); } @@ -834,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); } @@ -842,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); } @@ -850,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); } @@ -858,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); } @@ -866,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); } @@ -874,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); } @@ -882,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); } @@ -890,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); } @@ -898,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); } @@ -909,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); } @@ -970,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); } /// @@ -1001,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); } /// @@ -1026,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")); /// @@ -1034,10 +1065,10 @@ public static LengthUnit ParseUnit(string str) /// Error parsing string. public static LengthUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -1052,10 +1083,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -1071,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; } @@ -1112,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 * . @@ -1230,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Length. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Length), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -1323,304 +1348,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Length other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Length within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Length other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Length otherTyped - && (tolerance is Length toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Length'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Length other, Length tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Length. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(LengthUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - /// 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 NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } + IQuantity IQuantity.ToUnit(LengthUnit unit) => this.ToUnit(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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(LengthUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1635,137 +1380,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Length)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Length)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Length)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Length)) - return this; - else if (conversionType == typeof(LengthUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Length.Info; - else if (conversionType == typeof(BaseDimensions)) - return Length.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Length)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Level.g.cs b/UnitsNet/GeneratedCode/Quantities/Level.g.cs index a3471b0356..26b658fbb1 100644 --- a/UnitsNet/GeneratedCode/Quantities/Level.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Level.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,47 +33,98 @@ 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 : - IArithmeticQuantity, + ILogarithmicQuantity, #if NET7_0_OR_GREATER IComparisonOperators, IParsable, #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static Level() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class LevelInfo: QuantityInfo { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = LevelUnit.Decibel; - Units = Enum.GetValues(typeof(LevelUnit)).Cast().ToArray(); - Zero = new Level(0, BaseUnit); - Info = new QuantityInfo("Level", - new UnitInfo[] - { - new UnitInfo(LevelUnit.Decibel, "Decibels", BaseUnits.Undefined, "Level"), - new UnitInfo(LevelUnit.Neper, "Nepers", BaseUnits.Undefined, "Level"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public LevelInfo(string name, LevelUnit baseUnit, IEnumerable> unitMappings, Level zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public LevelInfo(string name, LevelUnit baseUnit, IEnumerable> unitMappings, Level zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Level.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Level", typeof(Level).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Level quantity. + /// + /// A new instance of the class with the default settings. + public static LevelInfo CreateDefault() + { + return new LevelInfo(nameof(Level), DefaultBaseUnit, GetDefaultMappings(), new Level(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Level quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static LevelInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new LevelInfo(nameof(Level), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Level(0, DefaultBaseUnit), DefaultBaseDimensions); + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// The for is . + /// + public static BaseDimensions DefaultBaseDimensions { get; } = BaseDimensions.Dimensionless; + + /// + /// The default base unit of Level is Decibel. All conversions, as defined in the , go via this value. + /// + public static LevelUnit DefaultBaseUnit { get; } = LevelUnit.Decibel; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Level. + public static IEnumerable> GetDefaultMappings() + { + yield return new (LevelUnit.Decibel, "Decibel", "Decibels", BaseUnits.Undefined); + yield return new (LevelUnit.Neper, "Neper", "Nepers", BaseUnits.Undefined, + new QuantityValue(57564627, 500000000) + ); + } + } + + static Level() + { + Info = UnitsNetSetup.CreateQuantityInfo(LevelInfo.CreateDefault); } /// @@ -87,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; @@ -98,96 +143,96 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Level, which is Decibel. All conversions go via this value. /// - public static LevelUnit BaseUnit { get; } + public static LevelUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Level quantity. /// - public static LevelUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Decibel. /// - public static Level Zero { get; } + public static Level Zero => Info.Zero; - /// - public static Level AdditiveIdentity => Zero; + /// + public static QuantityValue LogarithmicScalingFactor {get;} = 10; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public LevelUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Level.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + +#if NETSTANDARD2_0 + QuantityValue ILogarithmicQuantity.LogarithmicScalingFactor => LogarithmicScalingFactor; +#endif + + #endregion + #endregion #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. /// @@ -216,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); } @@ -224,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); } @@ -235,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); } @@ -296,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); } /// @@ -327,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); } /// @@ -352,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")); /// @@ -360,10 +398,10 @@ public static LevelUnit ParseUnit(string str) /// Error parsing string. public static LevelUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -378,10 +416,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -389,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 @@ -445,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Level. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Level), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -538,224 +578,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Level other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Level within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Level other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Level otherTyped - && (tolerance is Level toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Level'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Level other, Level tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Level. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(LevelUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(LevelUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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), - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -770,137 +610,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Level)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Level)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Level)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Level)) - return this; - else if (conversionType == typeof(LevelUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Level.Info; - else if (conversionType == typeof(BaseDimensions)) - return Level.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Level)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs index 14badeb281..b7aff71399 100644 --- a/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -56,54 +51,136 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class LinearDensityInfo: QuantityInfo + { + /// + public LinearDensityInfo(string name, LinearDensityUnit baseUnit, IEnumerable> unitMappings, LinearDensity zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public LinearDensityInfo(string name, LinearDensityUnit baseUnit, IEnumerable> unitMappings, LinearDensity zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, LinearDensity.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.LinearDensity", typeof(LinearDensity).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the LinearDensity quantity. + /// + /// A new instance of the class with the default settings. + public static LinearDensityInfo CreateDefault() + { + return new LinearDensityInfo(nameof(LinearDensity), DefaultBaseUnit, GetDefaultMappings(), new LinearDensity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the LinearDensity quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static LinearDensityInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new LinearDensityInfo(nameof(LinearDensity), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new LinearDensity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is L^-1M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-1, 1, 0, 0, 0, 0, 0); + + /// + /// The default base unit of LinearDensity is KilogramPerMeter. All conversions, as defined in the , go via this value. + /// + public static LinearDensityUnit DefaultBaseUnit { get; } = LinearDensityUnit.KilogramPerMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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), + 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() { - BaseDimensions = new BaseDimensions(-1, 1, 0, 0, 0, 0, 0); - BaseUnit = LinearDensityUnit.KilogramPerMeter; - Units = Enum.GetValues(typeof(LinearDensityUnit)).Cast().ToArray(); - Zero = new LinearDensity(0, BaseUnit); - Info = new QuantityInfo("LinearDensity", - new UnitInfo[] - { - new UnitInfo(LinearDensityUnit.GramPerCentimeter, "GramsPerCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram), "LinearDensity"), - new UnitInfo(LinearDensityUnit.GramPerFoot, "GramsPerFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Gram), "LinearDensity"), - new UnitInfo(LinearDensityUnit.GramPerMeter, "GramsPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram), "LinearDensity"), - new UnitInfo(LinearDensityUnit.GramPerMillimeter, "GramsPerMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Gram), "LinearDensity"), - new UnitInfo(LinearDensityUnit.KilogramPerCentimeter, "KilogramsPerCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilogram), "LinearDensity"), - new UnitInfo(LinearDensityUnit.KilogramPerFoot, "KilogramsPerFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Kilogram), "LinearDensity"), - new UnitInfo(LinearDensityUnit.KilogramPerMeter, "KilogramsPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram), "LinearDensity"), - new UnitInfo(LinearDensityUnit.KilogramPerMillimeter, "KilogramsPerMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram), "LinearDensity"), - new UnitInfo(LinearDensityUnit.MicrogramPerCentimeter, "MicrogramsPerCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Microgram), "LinearDensity"), - new UnitInfo(LinearDensityUnit.MicrogramPerFoot, "MicrogramsPerFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Microgram), "LinearDensity"), - new UnitInfo(LinearDensityUnit.MicrogramPerMeter, "MicrogramsPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram), "LinearDensity"), - new UnitInfo(LinearDensityUnit.MicrogramPerMillimeter, "MicrogramsPerMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Microgram), "LinearDensity"), - new UnitInfo(LinearDensityUnit.MilligramPerCentimeter, "MilligramsPerCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Milligram), "LinearDensity"), - new UnitInfo(LinearDensityUnit.MilligramPerFoot, "MilligramsPerFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Milligram), "LinearDensity"), - new UnitInfo(LinearDensityUnit.MilligramPerMeter, "MilligramsPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram), "LinearDensity"), - new UnitInfo(LinearDensityUnit.MilligramPerMillimeter, "MilligramsPerMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Milligram), "LinearDensity"), - new UnitInfo(LinearDensityUnit.PoundPerFoot, "PoundsPerFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Pound), "LinearDensity"), - new UnitInfo(LinearDensityUnit.PoundPerInch, "PoundsPerInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Pound), "LinearDensity"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(LinearDensityInfo.CreateDefault); } /// @@ -111,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; @@ -125,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); @@ -136,208 +213,169 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of LinearDensity, which is KilogramPerMeter. All conversions go via this value. /// - public static LinearDensityUnit BaseUnit { get; } + public static LinearDensityUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the LinearDensity quantity. /// - public static LinearDensityUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerMeter. /// - public static LinearDensity Zero { get; } - - /// - public static LinearDensity AdditiveIdentity => Zero; + public static LinearDensity Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public LinearDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => LinearDensity.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -366,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); } @@ -374,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); } @@ -382,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); } @@ -390,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); } @@ -398,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); } @@ -406,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); } @@ -414,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); } @@ -422,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); } @@ -430,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); } @@ -438,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); } @@ -446,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); } @@ -454,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); } @@ -462,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); } @@ -470,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); } @@ -478,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); } @@ -486,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); } @@ -494,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); } @@ -502,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); } @@ -513,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); } @@ -574,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); } /// @@ -605,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); } /// @@ -630,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")); /// @@ -638,10 +669,10 @@ public static LinearDensityUnit ParseUnit(string str) /// Error parsing string. public static LinearDensityUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -656,10 +687,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -675,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; } @@ -737,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current LinearDensity. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(LinearDensity), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -830,256 +855,24 @@ public int CompareTo(object? obj) /// public int CompareTo(LinearDensity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another LinearDensity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(LinearDensity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is LinearDensity otherTyped - && (tolerance is LinearDensity toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'LinearDensity'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(LinearDensity other, LinearDensity tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current LinearDensity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(LinearDensityUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(LinearDensityUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(LinearDensityUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1094,137 +887,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(LinearDensity)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(LinearDensity)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(LinearDensity)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(LinearDensity)) - return this; - else if (conversionType == typeof(LinearDensityUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return LinearDensity.Info; - else if (conversionType == typeof(BaseDimensions)) - return LinearDensity.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(LinearDensity)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/LinearPowerDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/LinearPowerDensity.g.cs index 67279ce157..fbdc580c48 100644 --- a/UnitsNet/GeneratedCode/Quantities/LinearPowerDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LinearPowerDensity.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,61 +46,157 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class LinearPowerDensityInfo: QuantityInfo + { + /// + public LinearPowerDensityInfo(string name, LinearPowerDensityUnit baseUnit, IEnumerable> unitMappings, LinearPowerDensity zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public LinearPowerDensityInfo(string name, LinearPowerDensityUnit baseUnit, IEnumerable> unitMappings, LinearPowerDensity zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, LinearPowerDensity.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.LinearPowerDensity", typeof(LinearPowerDensity).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the LinearPowerDensity quantity. + /// + /// A new instance of the class with the default settings. + public static LinearPowerDensityInfo CreateDefault() + { + return new LinearPowerDensityInfo(nameof(LinearPowerDensity), DefaultBaseUnit, GetDefaultMappings(), new LinearPowerDensity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the LinearPowerDensity quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static LinearPowerDensityInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new LinearPowerDensityInfo(nameof(LinearPowerDensity), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new LinearPowerDensity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-3LM. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, 1, -3, 0, 0, 0, 0); + + /// + /// The default base unit of LinearPowerDensity is WattPerMeter. All conversions, as defined in the , go via this value. + /// + public static LinearPowerDensityUnit DefaultBaseUnit { get; } = LinearPowerDensityUnit.WattPerMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for LinearPowerDensity. + public static IEnumerable> GetDefaultMappings() + { + 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, + new QuantityValue(1, 1000) + ); + } + } + static LinearPowerDensity() { - BaseDimensions = new BaseDimensions(1, 1, -3, 0, 0, 0, 0); - BaseUnit = LinearPowerDensityUnit.WattPerMeter; - Units = Enum.GetValues(typeof(LinearPowerDensityUnit)).Cast().ToArray(); - Zero = new LinearPowerDensity(0, BaseUnit); - Info = new QuantityInfo("LinearPowerDensity", - new UnitInfo[] - { - new UnitInfo(LinearPowerDensityUnit.GigawattPerCentimeter, "GigawattsPerCentimeter", BaseUnits.Undefined, "LinearPowerDensity"), - new UnitInfo(LinearPowerDensityUnit.GigawattPerFoot, "GigawattsPerFoot", BaseUnits.Undefined, "LinearPowerDensity"), - new UnitInfo(LinearPowerDensityUnit.GigawattPerInch, "GigawattsPerInch", BaseUnits.Undefined, "LinearPowerDensity"), - new UnitInfo(LinearPowerDensityUnit.GigawattPerMeter, "GigawattsPerMeter", new BaseUnits(length: LengthUnit.Gigameter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "LinearPowerDensity"), - new UnitInfo(LinearPowerDensityUnit.GigawattPerMillimeter, "GigawattsPerMillimeter", BaseUnits.Undefined, "LinearPowerDensity"), - new UnitInfo(LinearPowerDensityUnit.KilowattPerCentimeter, "KilowattsPerCentimeter", BaseUnits.Undefined, "LinearPowerDensity"), - new UnitInfo(LinearPowerDensityUnit.KilowattPerFoot, "KilowattsPerFoot", BaseUnits.Undefined, "LinearPowerDensity"), - new UnitInfo(LinearPowerDensityUnit.KilowattPerInch, "KilowattsPerInch", BaseUnits.Undefined, "LinearPowerDensity"), - new UnitInfo(LinearPowerDensityUnit.KilowattPerMeter, "KilowattsPerMeter", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "LinearPowerDensity"), - new UnitInfo(LinearPowerDensityUnit.KilowattPerMillimeter, "KilowattsPerMillimeter", BaseUnits.Undefined, "LinearPowerDensity"), - new UnitInfo(LinearPowerDensityUnit.MegawattPerCentimeter, "MegawattsPerCentimeter", BaseUnits.Undefined, "LinearPowerDensity"), - new UnitInfo(LinearPowerDensityUnit.MegawattPerFoot, "MegawattsPerFoot", BaseUnits.Undefined, "LinearPowerDensity"), - new UnitInfo(LinearPowerDensityUnit.MegawattPerInch, "MegawattsPerInch", BaseUnits.Undefined, "LinearPowerDensity"), - new UnitInfo(LinearPowerDensityUnit.MegawattPerMeter, "MegawattsPerMeter", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "LinearPowerDensity"), - new UnitInfo(LinearPowerDensityUnit.MegawattPerMillimeter, "MegawattsPerMillimeter", BaseUnits.Undefined, "LinearPowerDensity"), - new UnitInfo(LinearPowerDensityUnit.MilliwattPerCentimeter, "MilliwattsPerCentimeter", BaseUnits.Undefined, "LinearPowerDensity"), - new UnitInfo(LinearPowerDensityUnit.MilliwattPerFoot, "MilliwattsPerFoot", BaseUnits.Undefined, "LinearPowerDensity"), - new UnitInfo(LinearPowerDensityUnit.MilliwattPerInch, "MilliwattsPerInch", BaseUnits.Undefined, "LinearPowerDensity"), - new UnitInfo(LinearPowerDensityUnit.MilliwattPerMeter, "MilliwattsPerMeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "LinearPowerDensity"), - new UnitInfo(LinearPowerDensityUnit.MilliwattPerMillimeter, "MilliwattsPerMillimeter", BaseUnits.Undefined, "LinearPowerDensity"), - new UnitInfo(LinearPowerDensityUnit.WattPerCentimeter, "WattsPerCentimeter", BaseUnits.Undefined, "LinearPowerDensity"), - new UnitInfo(LinearPowerDensityUnit.WattPerFoot, "WattsPerFoot", BaseUnits.Undefined, "LinearPowerDensity"), - new UnitInfo(LinearPowerDensityUnit.WattPerInch, "WattsPerInch", BaseUnits.Undefined, "LinearPowerDensity"), - new UnitInfo(LinearPowerDensityUnit.WattPerMeter, "WattsPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "LinearPowerDensity"), - new UnitInfo(LinearPowerDensityUnit.WattPerMillimeter, "WattsPerMillimeter", BaseUnits.Undefined, "LinearPowerDensity"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(LinearPowerDensityInfo.CreateDefault); } /// @@ -113,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; @@ -127,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); @@ -138,257 +229,204 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of LinearPowerDensity, which is WattPerMeter. All conversions go via this value. /// - public static LinearPowerDensityUnit BaseUnit { get; } + public static LinearPowerDensityUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the LinearPowerDensity quantity. /// - public static LinearPowerDensityUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit WattPerMeter. /// - public static LinearPowerDensity Zero { get; } - - /// - public static LinearPowerDensity AdditiveIdentity => Zero; + public static LinearPowerDensity Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public LinearPowerDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => LinearPowerDensity.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -417,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); } @@ -425,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); } @@ -433,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); } @@ -441,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); } @@ -449,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); } @@ -457,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); } @@ -465,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); } @@ -473,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); } @@ -481,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); } @@ -489,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); } @@ -497,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); } @@ -505,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); } @@ -513,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); } @@ -521,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); } @@ -529,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); } @@ -537,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); } @@ -545,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); } @@ -553,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); } @@ -561,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); } @@ -569,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); } @@ -577,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); } @@ -585,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); } @@ -593,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); } @@ -601,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); } @@ -609,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); } @@ -620,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); } @@ -681,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); } /// @@ -712,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); } /// @@ -737,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")); /// @@ -745,10 +776,10 @@ public static LinearPowerDensityUnit ParseUnit(string str) /// Error parsing string. public static LinearPowerDensityUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -763,10 +794,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -782,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; } @@ -822,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current LinearPowerDensity. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(LinearPowerDensity), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -915,270 +940,24 @@ public int CompareTo(object? obj) /// public int CompareTo(LinearPowerDensity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another LinearPowerDensity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(LinearPowerDensity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is LinearPowerDensity otherTyped - && (tolerance is LinearPowerDensity toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'LinearPowerDensity'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(LinearPowerDensity other, LinearPowerDensity tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current LinearPowerDensity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(LinearPowerDensityUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(LinearPowerDensityUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1193,137 +972,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(LinearPowerDensity)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(LinearPowerDensity)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(LinearPowerDensity)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(LinearPowerDensity)) - return this; - else if (conversionType == typeof(LinearPowerDensityUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return LinearPowerDensity.Info; - else if (conversionType == typeof(BaseDimensions)) - return LinearPowerDensity.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(LinearPowerDensity)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Luminance.g.cs b/UnitsNet/GeneratedCode/Quantities/Luminance.g.cs index f4337dcb1f..ebbeb7c071 100644 --- a/UnitsNet/GeneratedCode/Quantities/Luminance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Luminance.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -54,46 +49,112 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class LuminanceInfo: QuantityInfo + { + /// + public LuminanceInfo(string name, LuminanceUnit baseUnit, IEnumerable> unitMappings, Luminance zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public LuminanceInfo(string name, LuminanceUnit baseUnit, IEnumerable> unitMappings, Luminance zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Luminance.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Luminance", typeof(Luminance).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Luminance quantity. + /// + /// A new instance of the class with the default settings. + public static LuminanceInfo CreateDefault() + { + return new LuminanceInfo(nameof(Luminance), DefaultBaseUnit, GetDefaultMappings(), new Luminance(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Luminance quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static LuminanceInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new LuminanceInfo(nameof(Luminance), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Luminance(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is L^-2J. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, 0, 0, 0, 0, 0, 1); + + /// + /// The default base unit of Luminance is CandelaPerSquareMeter. All conversions, as defined in the , go via this value. + /// + public static LuminanceUnit DefaultBaseUnit { get; } = LuminanceUnit.CandelaPerSquareMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Luminance. + public static IEnumerable> GetDefaultMappings() + { + 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), + 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() { - BaseDimensions = new BaseDimensions(-2, 0, 0, 0, 0, 0, 1); - BaseUnit = LuminanceUnit.CandelaPerSquareMeter; - Units = Enum.GetValues(typeof(LuminanceUnit)).Cast().ToArray(); - Zero = new Luminance(0, BaseUnit); - Info = new QuantityInfo("Luminance", - new UnitInfo[] - { - new UnitInfo(LuminanceUnit.CandelaPerSquareFoot, "CandelasPerSquareFoot", BaseUnits.Undefined, "Luminance"), - new UnitInfo(LuminanceUnit.CandelaPerSquareInch, "CandelasPerSquareInch", BaseUnits.Undefined, "Luminance"), - new UnitInfo(LuminanceUnit.CandelaPerSquareMeter, "CandelasPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, luminousIntensity: LuminousIntensityUnit.Candela), "Luminance"), - new UnitInfo(LuminanceUnit.CenticandelaPerSquareMeter, "CenticandelasPerSquareMeter", new BaseUnits(length: LengthUnit.Decameter, luminousIntensity: LuminousIntensityUnit.Candela), "Luminance"), - new UnitInfo(LuminanceUnit.DecicandelaPerSquareMeter, "DecicandelasPerSquareMeter", BaseUnits.Undefined, "Luminance"), - new UnitInfo(LuminanceUnit.KilocandelaPerSquareMeter, "KilocandelasPerSquareMeter", BaseUnits.Undefined, "Luminance"), - new UnitInfo(LuminanceUnit.MicrocandelaPerSquareMeter, "MicrocandelasPerSquareMeter", new BaseUnits(length: LengthUnit.Kilometer, luminousIntensity: LuminousIntensityUnit.Candela), "Luminance"), - new UnitInfo(LuminanceUnit.MillicandelaPerSquareMeter, "MillicandelasPerSquareMeter", BaseUnits.Undefined, "Luminance"), - new UnitInfo(LuminanceUnit.NanocandelaPerSquareMeter, "NanocandelasPerSquareMeter", BaseUnits.Undefined, "Luminance"), - new UnitInfo(LuminanceUnit.Nit, "Nits", BaseUnits.Undefined, "Luminance"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(LuminanceInfo.CreateDefault); } /// @@ -101,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; @@ -115,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); @@ -126,152 +187,129 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Luminance, which is CandelaPerSquareMeter. All conversions go via this value. /// - public static LuminanceUnit BaseUnit { get; } + public static LuminanceUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Luminance quantity. /// - public static LuminanceUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit CandelaPerSquareMeter. /// - public static Luminance Zero { get; } - - /// - public static Luminance AdditiveIdentity => Zero; + public static Luminance Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public LuminanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Luminance.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -300,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); } @@ -308,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); } @@ -316,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); } @@ -324,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); } @@ -332,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); } @@ -340,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); } @@ -348,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); } @@ -356,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); } @@ -364,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); } @@ -372,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); } @@ -383,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); } @@ -444,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); } /// @@ -475,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); } /// @@ -500,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")); /// @@ -508,10 +539,10 @@ public static LuminanceUnit ParseUnit(string str) /// Error parsing string. public static LuminanceUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -526,10 +557,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -545,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; } @@ -595,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Luminance. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Luminance), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -688,240 +713,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Luminance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Luminance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Luminance other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Luminance otherTyped - && (tolerance is Luminance toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Luminance'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Luminance other, Luminance tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Luminance. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(LuminanceUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(LuminanceUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -936,137 +745,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Luminance)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Luminance)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Luminance)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Luminance)) - return this; - else if (conversionType == typeof(LuminanceUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Luminance.Info; - else if (conversionType == typeof(BaseDimensions)) - return Luminance.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Luminance)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Luminosity.g.cs b/UnitsNet/GeneratedCode/Quantities/Luminosity.g.cs index 1ad38df36f..4e0e30b9d5 100644 --- a/UnitsNet/GeneratedCode/Quantities/Luminosity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Luminosity.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,50 +46,124 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class LuminosityInfo: QuantityInfo + { + /// + public LuminosityInfo(string name, LuminosityUnit baseUnit, IEnumerable> unitMappings, Luminosity zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public LuminosityInfo(string name, LuminosityUnit baseUnit, IEnumerable> unitMappings, Luminosity zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Luminosity.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Luminosity", typeof(Luminosity).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Luminosity quantity. + /// + /// A new instance of the class with the default settings. + public static LuminosityInfo CreateDefault() + { + return new LuminosityInfo(nameof(Luminosity), DefaultBaseUnit, GetDefaultMappings(), new Luminosity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Luminosity quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static LuminosityInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new LuminosityInfo(nameof(Luminosity), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Luminosity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-3L^2M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); + + /// + /// The default base unit of Luminosity is Watt. All conversions, as defined in the , go via this value. + /// + public static LuminosityUnit DefaultBaseUnit { get; } = LuminosityUnit.Watt; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Luminosity. + public static IEnumerable> GetDefaultMappings() + { + 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() { - BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); - BaseUnit = LuminosityUnit.Watt; - Units = Enum.GetValues(typeof(LuminosityUnit)).Cast().ToArray(); - Zero = new Luminosity(0, BaseUnit); - Info = new QuantityInfo("Luminosity", - new UnitInfo[] - { - new UnitInfo(LuminosityUnit.Decawatt, "Decawatts", BaseUnits.Undefined, "Luminosity"), - new UnitInfo(LuminosityUnit.Deciwatt, "Deciwatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Hectogram, time: DurationUnit.Second), "Luminosity"), - new UnitInfo(LuminosityUnit.Femtowatt, "Femtowatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Picogram, time: DurationUnit.Second), "Luminosity"), - new UnitInfo(LuminosityUnit.Gigawatt, "Gigawatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond), "Luminosity"), - new UnitInfo(LuminosityUnit.Kilowatt, "Kilowatts", BaseUnits.Undefined, "Luminosity"), - new UnitInfo(LuminosityUnit.Megawatt, "Megawatts", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Luminosity"), - new UnitInfo(LuminosityUnit.Microwatt, "Microwatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second), "Luminosity"), - new UnitInfo(LuminosityUnit.Milliwatt, "Milliwatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second), "Luminosity"), - new UnitInfo(LuminosityUnit.Nanowatt, "Nanowatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second), "Luminosity"), - new UnitInfo(LuminosityUnit.Petawatt, "Petawatts", BaseUnits.Undefined, "Luminosity"), - new UnitInfo(LuminosityUnit.Picowatt, "Picowatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Nanogram, time: DurationUnit.Second), "Luminosity"), - new UnitInfo(LuminosityUnit.SolarLuminosity, "SolarLuminosities", BaseUnits.Undefined, "Luminosity"), - new UnitInfo(LuminosityUnit.Terawatt, "Terawatts", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Luminosity"), - new UnitInfo(LuminosityUnit.Watt, "Watts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Luminosity"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(LuminosityInfo.CreateDefault); } /// @@ -102,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; @@ -116,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); @@ -127,180 +196,149 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Luminosity, which is Watt. All conversions go via this value. /// - public static LuminosityUnit BaseUnit { get; } + public static LuminosityUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Luminosity quantity. /// - public static LuminosityUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Watt. /// - public static Luminosity Zero { get; } - - /// - public static Luminosity AdditiveIdentity => Zero; + public static Luminosity Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public LuminosityUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Luminosity.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -329,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); } @@ -337,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); } @@ -345,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); } @@ -353,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); } @@ -361,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); } @@ -369,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); } @@ -377,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); } @@ -385,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); } @@ -393,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); } @@ -401,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); } @@ -409,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); } @@ -417,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); } @@ -425,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); } @@ -433,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); } @@ -444,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); } @@ -505,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); } /// @@ -536,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); } /// @@ -561,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")); /// @@ -569,10 +600,10 @@ public static LuminosityUnit ParseUnit(string str) /// Error parsing string. public static LuminosityUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -587,10 +618,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -606,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; } @@ -646,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Luminosity. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Luminosity), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -739,248 +764,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Luminosity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Luminosity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Luminosity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Luminosity otherTyped - && (tolerance is Luminosity toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Luminosity'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Luminosity other, Luminosity tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Luminosity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(LuminosityUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(LuminosityUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -995,137 +796,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Luminosity)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Luminosity)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Luminosity)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Luminosity)) - return this; - else if (conversionType == typeof(LuminosityUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Luminosity.Info; - else if (conversionType == typeof(BaseDimensions)) - return Luminosity.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Luminosity)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs b/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs index f7db868075..2f3148a603 100644 --- a/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -55,37 +50,85 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static LuminousFlux() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class LuminousFluxInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); - BaseUnit = LuminousFluxUnit.Lumen; - Units = Enum.GetValues(typeof(LuminousFluxUnit)).Cast().ToArray(); - Zero = new LuminousFlux(0, BaseUnit); - Info = new QuantityInfo("LuminousFlux", - new UnitInfo[] - { - new UnitInfo(LuminousFluxUnit.Lumen, "Lumens", new BaseUnits(luminousIntensity: LuminousIntensityUnit.Candela), "LuminousFlux"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public LuminousFluxInfo(string name, LuminousFluxUnit baseUnit, IEnumerable> unitMappings, LuminousFlux zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public LuminousFluxInfo(string name, LuminousFluxUnit baseUnit, IEnumerable> unitMappings, LuminousFlux zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, LuminousFlux.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.LuminousFlux", typeof(LuminousFlux).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the LuminousFlux quantity. + /// + /// A new instance of the class with the default settings. + public static LuminousFluxInfo CreateDefault() + { + return new LuminousFluxInfo(nameof(LuminousFlux), DefaultBaseUnit, GetDefaultMappings(), new LuminousFlux(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the LuminousFlux quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static LuminousFluxInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new LuminousFluxInfo(nameof(LuminousFlux), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new LuminousFlux(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is J. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); + + /// + /// The default base unit of LuminousFlux is Lumen. All conversions, as defined in the , go via this value. + /// + public static LuminousFluxUnit DefaultBaseUnit { get; } = LuminousFluxUnit.Lumen; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for LuminousFlux. + public static IEnumerable> GetDefaultMappings() + { + yield return new (LuminousFluxUnit.Lumen, "Lumen", "Lumens", new BaseUnits(luminousIntensity: LuminousIntensityUnit.Candela)); + } + } + + static LuminousFlux() + { + Info = UnitsNetSetup.CreateQuantityInfo(LuminousFluxInfo.CreateDefault); } /// @@ -93,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; @@ -107,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); @@ -118,88 +161,83 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of LuminousFlux, which is Lumen. All conversions go via this value. /// - public static LuminousFluxUnit BaseUnit { get; } + public static LuminousFluxUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the LuminousFlux quantity. /// - public static LuminousFluxUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Lumen. /// - public static LuminousFlux Zero { get; } - - /// - public static LuminousFlux AdditiveIdentity => Zero; + public static LuminousFlux Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public LuminousFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => LuminousFlux.BaseDimensions; - #endregion + #region Explicit implementations - #region Conversion Properties + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); - /// - /// Gets a value of this quantity converted into - /// - public double Lumens => As(LuminousFluxUnit.Lumen); + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif #endregion - #region Static Methods + #endregion + + #region Conversion Properties /// - /// Registers the default conversion functions in the given instance. + /// Gets a value of this quantity converted into /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: LuminousFluxUnit -> BaseUnit + public QuantityValue Lumens => this.As(LuminousFluxUnit.Lumen); - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(LuminousFluxUnit.Lumen, LuminousFluxUnit.Lumen, quantity => quantity); + #endregion - // Register in unit converter: BaseUnit -> LuminousFluxUnit - } + #region Static Methods /// /// Get unit abbreviation string. @@ -229,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); } @@ -240,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); } @@ -301,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); } /// @@ -332,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); } /// @@ -357,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")); /// @@ -365,10 +396,10 @@ public static LuminousFluxUnit ParseUnit(string str) /// Error parsing string. public static LuminousFluxUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -383,10 +414,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -402,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; } @@ -458,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current LuminousFlux. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(LuminousFlux), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -551,222 +576,24 @@ public int CompareTo(object? obj) /// public int CompareTo(LuminousFlux other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another LuminousFlux within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(LuminousFlux other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is LuminousFlux otherTyped - && (tolerance is LuminousFlux toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'LuminousFlux'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(LuminousFlux other, LuminousFlux tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current LuminousFlux. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(LuminousFluxUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(LuminousFluxUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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 - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -781,137 +608,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(LuminousFlux)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(LuminousFlux)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(LuminousFlux)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(LuminousFlux)) - return this; - else if (conversionType == typeof(LuminousFluxUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return LuminousFlux.Info; - else if (conversionType == typeof(BaseDimensions)) - return LuminousFlux.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(LuminousFlux)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs b/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs index 7e2d128ea3..3035093472 100644 --- a/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -55,37 +50,85 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static LuminousIntensity() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class LuminousIntensityInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); - BaseUnit = LuminousIntensityUnit.Candela; - Units = Enum.GetValues(typeof(LuminousIntensityUnit)).Cast().ToArray(); - Zero = new LuminousIntensity(0, BaseUnit); - Info = new QuantityInfo("LuminousIntensity", - new UnitInfo[] - { - new UnitInfo(LuminousIntensityUnit.Candela, "Candela", new BaseUnits(luminousIntensity: LuminousIntensityUnit.Candela), "LuminousIntensity"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public LuminousIntensityInfo(string name, LuminousIntensityUnit baseUnit, IEnumerable> unitMappings, LuminousIntensity zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public LuminousIntensityInfo(string name, LuminousIntensityUnit baseUnit, IEnumerable> unitMappings, LuminousIntensity zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, LuminousIntensity.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.LuminousIntensity", typeof(LuminousIntensity).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the LuminousIntensity quantity. + /// + /// A new instance of the class with the default settings. + public static LuminousIntensityInfo CreateDefault() + { + return new LuminousIntensityInfo(nameof(LuminousIntensity), DefaultBaseUnit, GetDefaultMappings(), new LuminousIntensity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the LuminousIntensity quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static LuminousIntensityInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new LuminousIntensityInfo(nameof(LuminousIntensity), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new LuminousIntensity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is J. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); + + /// + /// The default base unit of LuminousIntensity is Candela. All conversions, as defined in the , go via this value. + /// + public static LuminousIntensityUnit DefaultBaseUnit { get; } = LuminousIntensityUnit.Candela; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for LuminousIntensity. + public static IEnumerable> GetDefaultMappings() + { + yield return new (LuminousIntensityUnit.Candela, "Candela", "Candela", new BaseUnits(luminousIntensity: LuminousIntensityUnit.Candela)); + } + } + + static LuminousIntensity() + { + Info = UnitsNetSetup.CreateQuantityInfo(LuminousIntensityInfo.CreateDefault); } /// @@ -93,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; @@ -107,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); @@ -118,88 +161,83 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of LuminousIntensity, which is Candela. All conversions go via this value. /// - public static LuminousIntensityUnit BaseUnit { get; } + public static LuminousIntensityUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the LuminousIntensity quantity. /// - public static LuminousIntensityUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Candela. /// - public static LuminousIntensity Zero { get; } - - /// - public static LuminousIntensity AdditiveIdentity => Zero; + public static LuminousIntensity Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public LuminousIntensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => LuminousIntensity.BaseDimensions; - #endregion + #region Explicit implementations - #region Conversion Properties + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); - /// - /// Gets a value of this quantity converted into - /// - public double Candela => As(LuminousIntensityUnit.Candela); + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif #endregion - #region Static Methods + #endregion + + #region Conversion Properties /// - /// Registers the default conversion functions in the given instance. + /// Gets a value of this quantity converted into /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: LuminousIntensityUnit -> BaseUnit + public QuantityValue Candela => this.As(LuminousIntensityUnit.Candela); - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(LuminousIntensityUnit.Candela, LuminousIntensityUnit.Candela, quantity => quantity); + #endregion - // Register in unit converter: BaseUnit -> LuminousIntensityUnit - } + #region Static Methods /// /// Get unit abbreviation string. @@ -229,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); } @@ -240,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); } @@ -301,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); } /// @@ -332,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); } /// @@ -357,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")); /// @@ -365,10 +396,10 @@ public static LuminousIntensityUnit ParseUnit(string str) /// Error parsing string. public static LuminousIntensityUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -383,10 +414,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -402,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; } @@ -458,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current LuminousIntensity. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(LuminousIntensity), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -551,222 +576,24 @@ public int CompareTo(object? obj) /// public int CompareTo(LuminousIntensity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another LuminousIntensity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(LuminousIntensity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is LuminousIntensity otherTyped - && (tolerance is LuminousIntensity toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'LuminousIntensity'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(LuminousIntensity other, LuminousIntensity tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current LuminousIntensity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(LuminousIntensityUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(LuminousIntensityUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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 - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -781,137 +608,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(LuminousIntensity)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(LuminousIntensity)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(LuminousIntensity)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(LuminousIntensity)) - return this; - else if (conversionType == typeof(LuminousIntensityUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return LuminousIntensity.Info; - else if (conversionType == typeof(BaseDimensions)) - return LuminousIntensity.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(LuminousIntensity)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs b/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs index cf5eff0f76..cbdcdfb0e9 100644 --- a/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,42 +46,100 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static MagneticField() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class MagneticFieldInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(0, 1, -2, -1, 0, 0, 0); - BaseUnit = MagneticFieldUnit.Tesla; - Units = Enum.GetValues(typeof(MagneticFieldUnit)).Cast().ToArray(); - Zero = new MagneticField(0, BaseUnit); - Info = new QuantityInfo("MagneticField", - new UnitInfo[] - { - new UnitInfo(MagneticFieldUnit.Gauss, "Gausses", BaseUnits.Undefined, "MagneticField"), - new UnitInfo(MagneticFieldUnit.Microtesla, "Microteslas", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, current: ElectricCurrentUnit.Ampere), "MagneticField"), - new UnitInfo(MagneticFieldUnit.Milligauss, "Milligausses", BaseUnits.Undefined, "MagneticField"), - new UnitInfo(MagneticFieldUnit.Millitesla, "Milliteslas", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, current: ElectricCurrentUnit.Ampere), "MagneticField"), - new UnitInfo(MagneticFieldUnit.Nanotesla, "Nanoteslas", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, current: ElectricCurrentUnit.Ampere), "MagneticField"), - new UnitInfo(MagneticFieldUnit.Tesla, "Teslas", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, current: ElectricCurrentUnit.Ampere), "MagneticField"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public MagneticFieldInfo(string name, MagneticFieldUnit baseUnit, IEnumerable> unitMappings, MagneticField zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public MagneticFieldInfo(string name, MagneticFieldUnit baseUnit, IEnumerable> unitMappings, MagneticField zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, MagneticField.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.MagneticField", typeof(MagneticField).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the MagneticField quantity. + /// + /// A new instance of the class with the default settings. + public static MagneticFieldInfo CreateDefault() + { + return new MagneticFieldInfo(nameof(MagneticField), DefaultBaseUnit, GetDefaultMappings(), new MagneticField(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the MagneticField quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static MagneticFieldInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new MagneticFieldInfo(nameof(MagneticField), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new MagneticField(0, DefaultBaseUnit), DefaultBaseDimensions); + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// The for is T^-2MI^-1. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 1, -2, -1, 0, 0, 0); + + /// + /// The default base unit of MagneticField is Tesla. All conversions, as defined in the , go via this value. + /// + public static MagneticFieldUnit DefaultBaseUnit { get; } = MagneticFieldUnit.Tesla; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for MagneticField. + public static IEnumerable> GetDefaultMappings() + { + 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 = UnitsNetSetup.CreateQuantityInfo(MagneticFieldInfo.CreateDefault); } /// @@ -94,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; @@ -108,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); @@ -119,124 +172,109 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of MagneticField, which is Tesla. All conversions go via this value. /// - public static MagneticFieldUnit BaseUnit { get; } + public static MagneticFieldUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the MagneticField quantity. /// - public static MagneticFieldUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Tesla. /// - public static MagneticField Zero { get; } - - /// - public static MagneticField AdditiveIdentity => Zero; + public static MagneticField Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public MagneticFieldUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => MagneticField.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -265,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); } @@ -273,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); } @@ -281,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); } @@ -289,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); } @@ -297,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); } @@ -305,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); } @@ -316,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); } @@ -377,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); } /// @@ -408,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); } /// @@ -433,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")); /// @@ -441,10 +472,10 @@ public static MagneticFieldUnit ParseUnit(string str) /// Error parsing string. public static MagneticFieldUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -459,10 +490,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -478,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; } @@ -518,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current MagneticField. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(MagneticField), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -611,232 +636,24 @@ public int CompareTo(object? obj) /// public int CompareTo(MagneticField other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another MagneticField within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(MagneticField other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is MagneticField otherTyped - && (tolerance is MagneticField toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'MagneticField'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(MagneticField other, MagneticField tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MagneticField. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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)); + #region Conversion Methods (explicit implementations for netstandard2.0) - 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 MagneticFieldUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MagneticFieldUnit)} 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(MagneticFieldUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(MagneticFieldUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -851,137 +668,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MagneticField)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MagneticField)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MagneticField)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(MagneticField)) - return this; - else if (conversionType == typeof(MagneticFieldUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return MagneticField.Info; - else if (conversionType == typeof(BaseDimensions)) - return MagneticField.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(MagneticField)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs b/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs index 308eb4923c..f86c23e51b 100644 --- a/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,37 +46,85 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static MagneticFlux() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class MagneticFluxInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(2, 1, -2, -1, 0, 0, 0); - BaseUnit = MagneticFluxUnit.Weber; - Units = Enum.GetValues(typeof(MagneticFluxUnit)).Cast().ToArray(); - Zero = new MagneticFlux(0, BaseUnit); - Info = new QuantityInfo("MagneticFlux", - new UnitInfo[] - { - new UnitInfo(MagneticFluxUnit.Weber, "Webers", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "MagneticFlux"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public MagneticFluxInfo(string name, MagneticFluxUnit baseUnit, IEnumerable> unitMappings, MagneticFlux zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public MagneticFluxInfo(string name, MagneticFluxUnit baseUnit, IEnumerable> unitMappings, MagneticFlux zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, MagneticFlux.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.MagneticFlux", typeof(MagneticFlux).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the MagneticFlux quantity. + /// + /// A new instance of the class with the default settings. + public static MagneticFluxInfo CreateDefault() + { + return new MagneticFluxInfo(nameof(MagneticFlux), DefaultBaseUnit, GetDefaultMappings(), new MagneticFlux(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the MagneticFlux quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static MagneticFluxInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new MagneticFluxInfo(nameof(MagneticFlux), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new MagneticFlux(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-2L^2MI^-1. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -2, -1, 0, 0, 0); + + /// + /// The default base unit of MagneticFlux is Weber. All conversions, as defined in the , go via this value. + /// + public static MagneticFluxUnit DefaultBaseUnit { get; } = MagneticFluxUnit.Weber; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for MagneticFlux. + public static IEnumerable> GetDefaultMappings() + { + yield return new (MagneticFluxUnit.Weber, "Weber", "Webers", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); + } + } + + static MagneticFlux() + { + Info = UnitsNetSetup.CreateQuantityInfo(MagneticFluxInfo.CreateDefault); } /// @@ -89,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; @@ -103,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); @@ -114,88 +157,83 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of MagneticFlux, which is Weber. All conversions go via this value. /// - public static MagneticFluxUnit BaseUnit { get; } + public static MagneticFluxUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the MagneticFlux quantity. /// - public static MagneticFluxUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Weber. /// - public static MagneticFlux Zero { get; } - - /// - public static MagneticFlux AdditiveIdentity => Zero; + public static MagneticFlux Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public MagneticFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => MagneticFlux.BaseDimensions; - #endregion + #region Explicit implementations - #region Conversion Properties + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); - /// - /// Gets a value of this quantity converted into - /// - public double Webers => As(MagneticFluxUnit.Weber); + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif #endregion - #region Static Methods + #endregion + + #region Conversion Properties /// - /// Registers the default conversion functions in the given instance. + /// Gets a value of this quantity converted into /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: MagneticFluxUnit -> BaseUnit + public QuantityValue Webers => this.As(MagneticFluxUnit.Weber); - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(MagneticFluxUnit.Weber, MagneticFluxUnit.Weber, quantity => quantity); + #endregion - // Register in unit converter: BaseUnit -> MagneticFluxUnit - } + #region Static Methods /// /// Get unit abbreviation string. @@ -225,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); } @@ -236,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); } @@ -297,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); } /// @@ -328,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); } /// @@ -353,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")); /// @@ -361,10 +392,10 @@ public static MagneticFluxUnit ParseUnit(string str) /// Error parsing string. public static MagneticFluxUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -379,10 +410,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -398,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; } @@ -438,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current MagneticFlux. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(MagneticFlux), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -531,222 +556,24 @@ public int CompareTo(object? obj) /// public int CompareTo(MagneticFlux other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another MagneticFlux within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(MagneticFlux other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is MagneticFlux otherTyped - && (tolerance is MagneticFlux toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'MagneticFlux'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(MagneticFlux other, MagneticFlux tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MagneticFlux. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(MagneticFluxUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(MagneticFluxUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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 - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -761,137 +588,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MagneticFlux)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MagneticFlux)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MagneticFlux)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(MagneticFlux)) - return this; - else if (conversionType == typeof(MagneticFluxUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return MagneticFlux.Info; - else if (conversionType == typeof(BaseDimensions)) - return MagneticFlux.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(MagneticFlux)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs b/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs index 6497d0312e..cb78465ed8 100644 --- a/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,37 +46,85 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static Magnetization() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class MagnetizationInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(-1, 0, 0, 1, 0, 0, 0); - BaseUnit = MagnetizationUnit.AmperePerMeter; - Units = Enum.GetValues(typeof(MagnetizationUnit)).Cast().ToArray(); - Zero = new Magnetization(0, BaseUnit); - Info = new QuantityInfo("Magnetization", - new UnitInfo[] - { - new UnitInfo(MagnetizationUnit.AmperePerMeter, "AmperesPerMeter", new BaseUnits(length: LengthUnit.Meter, current: ElectricCurrentUnit.Ampere), "Magnetization"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public MagnetizationInfo(string name, MagnetizationUnit baseUnit, IEnumerable> unitMappings, Magnetization zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public MagnetizationInfo(string name, MagnetizationUnit baseUnit, IEnumerable> unitMappings, Magnetization zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Magnetization.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Magnetization", typeof(Magnetization).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the Magnetization quantity. + /// + /// A new instance of the class with the default settings. + public static MagnetizationInfo CreateDefault() + { + return new MagnetizationInfo(nameof(Magnetization), DefaultBaseUnit, GetDefaultMappings(), new Magnetization(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Magnetization quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static MagnetizationInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new MagnetizationInfo(nameof(Magnetization), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Magnetization(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is L^-1I. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-1, 0, 0, 1, 0, 0, 0); + + /// + /// The default base unit of Magnetization is AmperePerMeter. All conversions, as defined in the , go via this value. + /// + public static MagnetizationUnit DefaultBaseUnit { get; } = MagnetizationUnit.AmperePerMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Magnetization. + public static IEnumerable> GetDefaultMappings() + { + yield return new (MagnetizationUnit.AmperePerMeter, "AmperePerMeter", "AmperesPerMeter", new BaseUnits(length: LengthUnit.Meter, current: ElectricCurrentUnit.Ampere)); + } + } + + static Magnetization() + { + Info = UnitsNetSetup.CreateQuantityInfo(MagnetizationInfo.CreateDefault); } /// @@ -89,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; @@ -103,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); @@ -114,88 +157,83 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Magnetization, which is AmperePerMeter. All conversions go via this value. /// - public static MagnetizationUnit BaseUnit { get; } + public static MagnetizationUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Magnetization quantity. /// - public static MagnetizationUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit AmperePerMeter. /// - public static Magnetization Zero { get; } - - /// - public static Magnetization AdditiveIdentity => Zero; + public static Magnetization Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public MagnetizationUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Magnetization.BaseDimensions; - #endregion + #region Explicit implementations - #region Conversion Properties + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); - /// - /// Gets a value of this quantity converted into - /// - public double AmperesPerMeter => As(MagnetizationUnit.AmperePerMeter); + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif #endregion - #region Static Methods + #endregion + + #region Conversion Properties /// - /// Registers the default conversion functions in the given instance. + /// Gets a value of this quantity converted into /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: MagnetizationUnit -> BaseUnit + public QuantityValue AmperesPerMeter => this.As(MagnetizationUnit.AmperePerMeter); - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(MagnetizationUnit.AmperePerMeter, MagnetizationUnit.AmperePerMeter, quantity => quantity); + #endregion - // Register in unit converter: BaseUnit -> MagnetizationUnit - } + #region Static Methods /// /// Get unit abbreviation string. @@ -225,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); } @@ -236,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); } @@ -297,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); } /// @@ -328,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); } /// @@ -353,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")); /// @@ -361,10 +392,10 @@ public static MagnetizationUnit ParseUnit(string str) /// Error parsing string. public static MagnetizationUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -379,10 +410,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -398,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; } @@ -438,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Magnetization. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Magnetization), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -531,222 +556,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Magnetization other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Magnetization within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Magnetization other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Magnetization otherTyped - && (tolerance is Magnetization toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Magnetization'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Magnetization other, Magnetization tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Magnetization. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(MagnetizationUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(MagnetizationUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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 - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -761,137 +588,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Magnetization)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Magnetization)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Magnetization)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Magnetization)) - return this; - else if (conversionType == typeof(MagnetizationUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Magnetization.Info; - else if (conversionType == typeof(BaseDimensions)) - return Magnetization.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Magnetization)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Mass.g.cs b/UnitsNet/GeneratedCode/Quantities/Mass.g.cs index f53a806f6b..fbce13ff2a 100644 --- a/UnitsNet/GeneratedCode/Quantities/Mass.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Mass.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -66,63 +61,163 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class MassInfo: QuantityInfo + { + /// + public MassInfo(string name, MassUnit baseUnit, IEnumerable> unitMappings, Mass zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public MassInfo(string name, MassUnit baseUnit, IEnumerable> unitMappings, Mass zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Mass.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Mass", typeof(Mass).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Mass quantity. + /// + /// A new instance of the class with the default settings. + public static MassInfo CreateDefault() + { + return new MassInfo(nameof(Mass), DefaultBaseUnit, GetDefaultMappings(), new Mass(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Mass quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static MassInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new MassInfo(nameof(Mass), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Mass(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 1, 0, 0, 0, 0, 0); + + /// + /// The default base unit of Mass is Kilogram. All conversions, as defined in the , go via this value. + /// + public static MassUnit DefaultBaseUnit { get; } = MassUnit.Kilogram; + + /// + /// Retrieves the default mappings for . + /// + /// 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), + 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), + 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() { - BaseDimensions = new BaseDimensions(0, 1, 0, 0, 0, 0, 0); - BaseUnit = MassUnit.Kilogram; - Units = Enum.GetValues(typeof(MassUnit)).Cast().ToArray(); - Zero = new Mass(0, BaseUnit); - Info = new QuantityInfo("Mass", - new UnitInfo[] - { - new UnitInfo(MassUnit.Centigram, "Centigrams", new BaseUnits(mass: MassUnit.Centigram), "Mass"), - new UnitInfo(MassUnit.Decagram, "Decagrams", new BaseUnits(mass: MassUnit.Decagram), "Mass"), - new UnitInfo(MassUnit.Decigram, "Decigrams", new BaseUnits(mass: MassUnit.Decigram), "Mass"), - new UnitInfo(MassUnit.EarthMass, "EarthMasses", new BaseUnits(mass: MassUnit.EarthMass), "Mass"), - new UnitInfo(MassUnit.Femtogram, "Femtograms", new BaseUnits(mass: MassUnit.Femtogram), "Mass"), - new UnitInfo(MassUnit.Grain, "Grains", new BaseUnits(mass: MassUnit.Grain), "Mass"), - new UnitInfo(MassUnit.Gram, "Grams", new BaseUnits(mass: MassUnit.Gram), "Mass"), - new UnitInfo(MassUnit.Hectogram, "Hectograms", new BaseUnits(mass: MassUnit.Hectogram), "Mass"), - new UnitInfo(MassUnit.Kilogram, "Kilograms", new BaseUnits(mass: MassUnit.Kilogram), "Mass"), - new UnitInfo(MassUnit.Kilopound, "Kilopounds", new BaseUnits(mass: MassUnit.Kilopound), "Mass"), - new UnitInfo(MassUnit.Kilotonne, "Kilotonnes", new BaseUnits(mass: MassUnit.Kilotonne), "Mass"), - new UnitInfo(MassUnit.LongHundredweight, "LongHundredweight", new BaseUnits(mass: MassUnit.LongHundredweight), "Mass"), - new UnitInfo(MassUnit.LongTon, "LongTons", new BaseUnits(mass: MassUnit.LongTon), "Mass"), - new UnitInfo(MassUnit.Megapound, "Megapounds", new BaseUnits(mass: MassUnit.Megapound), "Mass"), - new UnitInfo(MassUnit.Megatonne, "Megatonnes", new BaseUnits(mass: MassUnit.Megatonne), "Mass"), - new UnitInfo(MassUnit.Microgram, "Micrograms", new BaseUnits(mass: MassUnit.Microgram), "Mass"), - new UnitInfo(MassUnit.Milligram, "Milligrams", new BaseUnits(mass: MassUnit.Milligram), "Mass"), - new UnitInfo(MassUnit.Nanogram, "Nanograms", new BaseUnits(mass: MassUnit.Nanogram), "Mass"), - new UnitInfo(MassUnit.Ounce, "Ounces", new BaseUnits(mass: MassUnit.Ounce), "Mass"), - new UnitInfo(MassUnit.Picogram, "Picograms", new BaseUnits(mass: MassUnit.Picogram), "Mass"), - new UnitInfo(MassUnit.Pound, "Pounds", new BaseUnits(mass: MassUnit.Pound), "Mass"), - new UnitInfo(MassUnit.ShortHundredweight, "ShortHundredweight", new BaseUnits(mass: MassUnit.ShortHundredweight), "Mass"), - new UnitInfo(MassUnit.ShortTon, "ShortTons", new BaseUnits(mass: MassUnit.ShortTon), "Mass"), - new UnitInfo(MassUnit.Slug, "Slugs", new BaseUnits(mass: MassUnit.Slug), "Mass"), - new UnitInfo(MassUnit.SolarMass, "SolarMasses", new BaseUnits(mass: MassUnit.SolarMass), "Mass"), - new UnitInfo(MassUnit.Stone, "Stone", new BaseUnits(mass: MassUnit.Stone), "Mass"), - new UnitInfo(MassUnit.Tonne, "Tonnes", new BaseUnits(mass: MassUnit.Tonne), "Mass"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(MassInfo.CreateDefault); } /// @@ -130,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; @@ -144,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); @@ -155,271 +250,214 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Mass, which is Kilogram. All conversions go via this value. /// - public static MassUnit BaseUnit { get; } + public static MassUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Mass quantity. /// - public static MassUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Kilogram. /// - public static Mass Zero { get; } - - /// - public static Mass AdditiveIdentity => Zero; + public static Mass Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public MassUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Mass.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -448,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); } @@ -456,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); } @@ -464,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); } @@ -472,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); } @@ -480,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); } @@ -488,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); } @@ -496,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); } @@ -504,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); } @@ -512,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); } @@ -520,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); } @@ -528,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); } @@ -536,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); } @@ -544,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); } @@ -552,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); } @@ -560,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); } @@ -568,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); } @@ -576,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); } @@ -584,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); } @@ -592,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); } @@ -600,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); } @@ -608,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); } @@ -616,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); } @@ -624,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); } @@ -632,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); } @@ -640,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); } @@ -648,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); } @@ -656,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); } @@ -667,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); } @@ -728,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); } /// @@ -759,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); } /// @@ -784,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")); /// @@ -792,10 +823,10 @@ public static MassUnit ParseUnit(string str) /// Error parsing string. public static MassUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -810,10 +841,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -829,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; } @@ -969,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Mass. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Mass), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -1062,274 +1087,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Mass other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Mass within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Mass other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Mass otherTyped - && (tolerance is Mass toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Mass'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Mass other, Mass tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Mass. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(MassUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - /// 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 NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } + IQuantity IQuantity.ToUnit(MassUnit unit) => this.ToUnit(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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(MassUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1344,137 +1119,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Mass)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Mass)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Mass)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Mass)) - return this; - else if (conversionType == typeof(MassUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Mass.Info; - else if (conversionType == typeof(BaseDimensions)) - return Mass.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Mass)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/MassConcentration.g.cs b/UnitsNet/GeneratedCode/Quantities/MassConcentration.g.cs index 97d2cee9f9..af90d66b30 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassConcentration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassConcentration.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -58,85 +53,229 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class MassConcentrationInfo: QuantityInfo + { + /// + public MassConcentrationInfo(string name, MassConcentrationUnit baseUnit, IEnumerable> unitMappings, MassConcentration zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public MassConcentrationInfo(string name, MassConcentrationUnit baseUnit, IEnumerable> unitMappings, MassConcentration zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, MassConcentration.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.MassConcentration", typeof(MassConcentration).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the MassConcentration quantity. + /// + /// A new instance of the class with the default settings. + public static MassConcentrationInfo CreateDefault() + { + return new MassConcentrationInfo(nameof(MassConcentration), DefaultBaseUnit, GetDefaultMappings(), new MassConcentration(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the MassConcentration quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static MassConcentrationInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new MassConcentrationInfo(nameof(MassConcentration), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new MassConcentration(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is L^-3M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-3, 1, 0, 0, 0, 0, 0); + + /// + /// The default base unit of MassConcentration is KilogramPerCubicMeter. All conversions, as defined in the , go via this value. + /// + public static MassConcentrationUnit DefaultBaseUnit { get; } = MassConcentrationUnit.KilogramPerCubicMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for MassConcentration. + public static IEnumerable> GetDefaultMappings() + { + 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), + 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() { - BaseDimensions = new BaseDimensions(-3, 1, 0, 0, 0, 0, 0); - BaseUnit = MassConcentrationUnit.KilogramPerCubicMeter; - Units = Enum.GetValues(typeof(MassConcentrationUnit)).Cast().ToArray(); - Zero = new MassConcentration(0, BaseUnit); - Info = new QuantityInfo("MassConcentration", - new UnitInfo[] - { - new UnitInfo(MassConcentrationUnit.CentigramPerDeciliter, "CentigramsPerDeciliter", BaseUnits.Undefined, "MassConcentration"), - new UnitInfo(MassConcentrationUnit.CentigramPerLiter, "CentigramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Centigram), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.CentigramPerMicroliter, "CentigramsPerMicroliter", BaseUnits.Undefined, "MassConcentration"), - new UnitInfo(MassConcentrationUnit.CentigramPerMilliliter, "CentigramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Centigram), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.DecigramPerDeciliter, "DecigramsPerDeciliter", BaseUnits.Undefined, "MassConcentration"), - new UnitInfo(MassConcentrationUnit.DecigramPerLiter, "DecigramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Decigram), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.DecigramPerMicroliter, "DecigramsPerMicroliter", BaseUnits.Undefined, "MassConcentration"), - new UnitInfo(MassConcentrationUnit.DecigramPerMilliliter, "DecigramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Decigram), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.GramPerCubicCentimeter, "GramsPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.GramPerCubicMeter, "GramsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.GramPerCubicMillimeter, "GramsPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Gram), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.GramPerDeciliter, "GramsPerDeciliter", BaseUnits.Undefined, "MassConcentration"), - new UnitInfo(MassConcentrationUnit.GramPerLiter, "GramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Gram), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.GramPerMicroliter, "GramsPerMicroliter", BaseUnits.Undefined, "MassConcentration"), - new UnitInfo(MassConcentrationUnit.GramPerMilliliter, "GramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.KilogramPerCubicCentimeter, "KilogramsPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilogram), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.KilogramPerCubicMeter, "KilogramsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.KilogramPerCubicMillimeter, "KilogramsPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.KilogramPerLiter, "KilogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilogram), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.KilopoundPerCubicFoot, "KilopoundsPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Kilopound), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.KilopoundPerCubicInch, "KilopoundsPerCubicInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Kilopound), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.MicrogramPerCubicMeter, "MicrogramsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.MicrogramPerDeciliter, "MicrogramsPerDeciliter", BaseUnits.Undefined, "MassConcentration"), - new UnitInfo(MassConcentrationUnit.MicrogramPerLiter, "MicrogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Microgram), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.MicrogramPerMicroliter, "MicrogramsPerMicroliter", BaseUnits.Undefined, "MassConcentration"), - new UnitInfo(MassConcentrationUnit.MicrogramPerMilliliter, "MicrogramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Microgram), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.MilligramPerCubicMeter, "MilligramsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.MilligramPerDeciliter, "MilligramsPerDeciliter", BaseUnits.Undefined, "MassConcentration"), - new UnitInfo(MassConcentrationUnit.MilligramPerLiter, "MilligramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Milligram), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.MilligramPerMicroliter, "MilligramsPerMicroliter", BaseUnits.Undefined, "MassConcentration"), - new UnitInfo(MassConcentrationUnit.MilligramPerMilliliter, "MilligramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Milligram), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.NanogramPerDeciliter, "NanogramsPerDeciliter", BaseUnits.Undefined, "MassConcentration"), - new UnitInfo(MassConcentrationUnit.NanogramPerLiter, "NanogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Nanogram), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.NanogramPerMicroliter, "NanogramsPerMicroliter", BaseUnits.Undefined, "MassConcentration"), - new UnitInfo(MassConcentrationUnit.NanogramPerMilliliter, "NanogramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Nanogram), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.OuncePerImperialGallon, "OuncesPerImperialGallon", BaseUnits.Undefined, "MassConcentration"), - new UnitInfo(MassConcentrationUnit.OuncePerUSGallon, "OuncesPerUSGallon", BaseUnits.Undefined, "MassConcentration"), - new UnitInfo(MassConcentrationUnit.PicogramPerDeciliter, "PicogramsPerDeciliter", BaseUnits.Undefined, "MassConcentration"), - new UnitInfo(MassConcentrationUnit.PicogramPerLiter, "PicogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Picogram), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.PicogramPerMicroliter, "PicogramsPerMicroliter", BaseUnits.Undefined, "MassConcentration"), - new UnitInfo(MassConcentrationUnit.PicogramPerMilliliter, "PicogramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Picogram), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.PoundPerCubicFoot, "PoundsPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Pound), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.PoundPerCubicInch, "PoundsPerCubicInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Pound), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.PoundPerImperialGallon, "PoundsPerImperialGallon", BaseUnits.Undefined, "MassConcentration"), - new UnitInfo(MassConcentrationUnit.PoundPerUSGallon, "PoundsPerUSGallon", BaseUnits.Undefined, "MassConcentration"), - new UnitInfo(MassConcentrationUnit.SlugPerCubicFoot, "SlugsPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Slug), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.TonnePerCubicCentimeter, "TonnesPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Tonne), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.TonnePerCubicMeter, "TonnesPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Tonne), "MassConcentration"), - new UnitInfo(MassConcentrationUnit.TonnePerCubicMillimeter, "TonnesPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Tonne), "MassConcentration"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(MassConcentrationInfo.CreateDefault); } /// @@ -144,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; @@ -158,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); @@ -169,425 +308,324 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of MassConcentration, which is KilogramPerCubicMeter. All conversions go via this value. /// - public static MassConcentrationUnit BaseUnit { get; } + public static MassConcentrationUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the MassConcentration quantity. /// - public static MassConcentrationUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerCubicMeter. /// - public static MassConcentration Zero { get; } - - /// - public static MassConcentration AdditiveIdentity => Zero; + public static MassConcentration Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public MassConcentrationUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => MassConcentration.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -616,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); } @@ -624,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); } @@ -632,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); } @@ -640,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); } @@ -648,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); } @@ -656,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); } @@ -664,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); } @@ -672,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); } @@ -680,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); } @@ -688,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); } @@ -696,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); } @@ -704,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); } @@ -712,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); } @@ -720,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); } @@ -728,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); } @@ -736,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); } @@ -744,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); } @@ -752,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); } @@ -760,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); } @@ -768,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); } @@ -776,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); } @@ -784,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); } @@ -792,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); } @@ -800,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); } @@ -808,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); } @@ -816,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); } @@ -824,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); } @@ -832,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); } @@ -840,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); } @@ -848,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); } @@ -856,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); } @@ -864,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); } @@ -872,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); } @@ -880,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); } @@ -888,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); } @@ -896,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); } @@ -904,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); } @@ -912,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); } @@ -920,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); } @@ -928,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); } @@ -936,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); } @@ -944,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); } @@ -952,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); } @@ -960,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); } @@ -968,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); } @@ -976,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); } @@ -984,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); } @@ -992,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); } @@ -1000,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); } @@ -1011,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); } @@ -1072,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); } /// @@ -1103,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); } /// @@ -1128,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")); /// @@ -1136,10 +1167,10 @@ public static MassConcentrationUnit ParseUnit(string str) /// Error parsing string. public static MassConcentrationUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -1154,10 +1185,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -1173,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; } @@ -1247,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current MassConcentration. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(MassConcentration), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -1340,318 +1365,24 @@ public int CompareTo(object? obj) /// public int CompareTo(MassConcentration other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another MassConcentration within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(MassConcentration other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is MassConcentration otherTyped - && (tolerance is MassConcentration toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'MassConcentration'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(MassConcentration other, MassConcentration tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MassConcentration. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(MassConcentrationUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - /// 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 NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } + IQuantity IQuantity.ToUnit(MassConcentrationUnit unit) => this.ToUnit(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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(MassConcentrationUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1666,137 +1397,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MassConcentration)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MassConcentration)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MassConcentration)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(MassConcentration)) - return this; - else if (conversionType == typeof(MassConcentrationUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return MassConcentration.Info; - else if (conversionType == typeof(BaseDimensions)) - return MassConcentration.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(MassConcentration)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs b/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs index 7a3afff7ed..c4b35ad3a7 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -60,69 +55,181 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class MassFlowInfo: QuantityInfo + { + /// + public MassFlowInfo(string name, MassFlowUnit baseUnit, IEnumerable> unitMappings, MassFlow zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public MassFlowInfo(string name, MassFlowUnit baseUnit, IEnumerable> unitMappings, MassFlow zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, MassFlow.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.MassFlow", typeof(MassFlow).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the MassFlow quantity. + /// + /// A new instance of the class with the default settings. + public static MassFlowInfo CreateDefault() + { + return new MassFlowInfo(nameof(MassFlow), DefaultBaseUnit, GetDefaultMappings(), new MassFlow(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the MassFlow quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static MassFlowInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new MassFlowInfo(nameof(MassFlow), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new MassFlow(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-1M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 1, -1, 0, 0, 0, 0); + + /// + /// The default base unit of MassFlow is GramPerSecond. All conversions, as defined in the , go via this value. + /// + public static MassFlowUnit DefaultBaseUnit { get; } = MassFlowUnit.GramPerSecond; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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), + 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() { - BaseDimensions = new BaseDimensions(0, 1, -1, 0, 0, 0, 0); - BaseUnit = MassFlowUnit.GramPerSecond; - Units = Enum.GetValues(typeof(MassFlowUnit)).Cast().ToArray(); - Zero = new MassFlow(0, BaseUnit); - Info = new QuantityInfo("MassFlow", - new UnitInfo[] - { - new UnitInfo(MassFlowUnit.CentigramPerDay, "CentigramsPerDay", new BaseUnits(mass: MassUnit.Centigram, time: DurationUnit.Day), "MassFlow"), - new UnitInfo(MassFlowUnit.CentigramPerSecond, "CentigramsPerSecond", new BaseUnits(mass: MassUnit.Centigram, time: DurationUnit.Second), "MassFlow"), - new UnitInfo(MassFlowUnit.DecagramPerDay, "DecagramsPerDay", new BaseUnits(mass: MassUnit.Decagram, time: DurationUnit.Day), "MassFlow"), - new UnitInfo(MassFlowUnit.DecagramPerSecond, "DecagramsPerSecond", new BaseUnits(mass: MassUnit.Decagram, time: DurationUnit.Second), "MassFlow"), - new UnitInfo(MassFlowUnit.DecigramPerDay, "DecigramsPerDay", new BaseUnits(mass: MassUnit.Decigram, time: DurationUnit.Day), "MassFlow"), - new UnitInfo(MassFlowUnit.DecigramPerSecond, "DecigramsPerSecond", new BaseUnits(mass: MassUnit.Decigram, time: DurationUnit.Second), "MassFlow"), - new UnitInfo(MassFlowUnit.GramPerDay, "GramsPerDay", new BaseUnits(mass: MassUnit.Gram, time: DurationUnit.Day), "MassFlow"), - new UnitInfo(MassFlowUnit.GramPerHour, "GramsPerHour", new BaseUnits(mass: MassUnit.Gram, time: DurationUnit.Hour), "MassFlow"), - new UnitInfo(MassFlowUnit.GramPerSecond, "GramsPerSecond", new BaseUnits(mass: MassUnit.Gram, time: DurationUnit.Second), "MassFlow"), - new UnitInfo(MassFlowUnit.HectogramPerDay, "HectogramsPerDay", new BaseUnits(mass: MassUnit.Hectogram, time: DurationUnit.Day), "MassFlow"), - new UnitInfo(MassFlowUnit.HectogramPerSecond, "HectogramsPerSecond", new BaseUnits(mass: MassUnit.Hectogram, time: DurationUnit.Second), "MassFlow"), - new UnitInfo(MassFlowUnit.KilogramPerDay, "KilogramsPerDay", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Day), "MassFlow"), - new UnitInfo(MassFlowUnit.KilogramPerHour, "KilogramsPerHour", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Hour), "MassFlow"), - new UnitInfo(MassFlowUnit.KilogramPerMinute, "KilogramsPerMinute", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Minute), "MassFlow"), - new UnitInfo(MassFlowUnit.KilogramPerSecond, "KilogramsPerSecond", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second), "MassFlow"), - new UnitInfo(MassFlowUnit.MegagramPerDay, "MegagramsPerDay", BaseUnits.Undefined, "MassFlow"), - new UnitInfo(MassFlowUnit.MegapoundPerDay, "MegapoundsPerDay", new BaseUnits(mass: MassUnit.Megapound, time: DurationUnit.Day), "MassFlow"), - new UnitInfo(MassFlowUnit.MegapoundPerHour, "MegapoundsPerHour", new BaseUnits(mass: MassUnit.Megapound, time: DurationUnit.Hour), "MassFlow"), - new UnitInfo(MassFlowUnit.MegapoundPerMinute, "MegapoundsPerMinute", new BaseUnits(mass: MassUnit.Megapound, time: DurationUnit.Minute), "MassFlow"), - new UnitInfo(MassFlowUnit.MegapoundPerSecond, "MegapoundsPerSecond", new BaseUnits(mass: MassUnit.Megapound, time: DurationUnit.Second), "MassFlow"), - new UnitInfo(MassFlowUnit.MicrogramPerDay, "MicrogramsPerDay", new BaseUnits(mass: MassUnit.Microgram, time: DurationUnit.Day), "MassFlow"), - new UnitInfo(MassFlowUnit.MicrogramPerSecond, "MicrogramsPerSecond", new BaseUnits(mass: MassUnit.Microgram, time: DurationUnit.Second), "MassFlow"), - new UnitInfo(MassFlowUnit.MilligramPerDay, "MilligramsPerDay", new BaseUnits(mass: MassUnit.Milligram, time: DurationUnit.Day), "MassFlow"), - new UnitInfo(MassFlowUnit.MilligramPerSecond, "MilligramsPerSecond", new BaseUnits(mass: MassUnit.Milligram, time: DurationUnit.Second), "MassFlow"), - new UnitInfo(MassFlowUnit.NanogramPerDay, "NanogramsPerDay", new BaseUnits(mass: MassUnit.Nanogram, time: DurationUnit.Day), "MassFlow"), - new UnitInfo(MassFlowUnit.NanogramPerSecond, "NanogramsPerSecond", new BaseUnits(mass: MassUnit.Nanogram, time: DurationUnit.Second), "MassFlow"), - new UnitInfo(MassFlowUnit.PoundPerDay, "PoundsPerDay", new BaseUnits(mass: MassUnit.Pound, time: DurationUnit.Day), "MassFlow"), - new UnitInfo(MassFlowUnit.PoundPerHour, "PoundsPerHour", new BaseUnits(mass: MassUnit.Pound, time: DurationUnit.Hour), "MassFlow"), - new UnitInfo(MassFlowUnit.PoundPerMinute, "PoundsPerMinute", new BaseUnits(mass: MassUnit.Pound, time: DurationUnit.Minute), "MassFlow"), - new UnitInfo(MassFlowUnit.PoundPerSecond, "PoundsPerSecond", new BaseUnits(mass: MassUnit.Pound, time: DurationUnit.Second), "MassFlow"), - new UnitInfo(MassFlowUnit.ShortTonPerHour, "ShortTonsPerHour", new BaseUnits(mass: MassUnit.ShortTon, time: DurationUnit.Hour), "MassFlow"), - new UnitInfo(MassFlowUnit.TonnePerDay, "TonnesPerDay", new BaseUnits(mass: MassUnit.Tonne, time: DurationUnit.Day), "MassFlow"), - new UnitInfo(MassFlowUnit.TonnePerHour, "TonnesPerHour", new BaseUnits(mass: MassUnit.Tonne, time: DurationUnit.Hour), "MassFlow"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(MassFlowInfo.CreateDefault); } /// @@ -130,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; @@ -144,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); @@ -155,313 +262,244 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of MassFlow, which is GramPerSecond. All conversions go via this value. /// - public static MassFlowUnit BaseUnit { get; } + public static MassFlowUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the MassFlow quantity. /// - public static MassFlowUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit GramPerSecond. /// - public static MassFlow Zero { get; } - - /// - public static MassFlow AdditiveIdentity => Zero; + public static MassFlow Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public MassFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => MassFlow.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -490,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); } @@ -498,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); } @@ -506,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); } @@ -514,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); } @@ -522,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); } @@ -530,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); } @@ -538,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); } @@ -546,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); } @@ -554,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); } @@ -562,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); } @@ -570,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); } @@ -578,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); } @@ -586,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); } @@ -594,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); } @@ -602,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); } @@ -610,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); } @@ -618,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); } @@ -626,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); } @@ -634,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); } @@ -642,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); } @@ -650,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); } @@ -658,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); } @@ -666,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); } @@ -674,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); } @@ -682,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); } @@ -690,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); } @@ -698,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); } @@ -706,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); } @@ -714,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); } @@ -722,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); } @@ -730,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); } @@ -738,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); } @@ -746,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); } @@ -757,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); } @@ -818,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); } /// @@ -849,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); } /// @@ -874,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")); /// @@ -882,10 +913,10 @@ public static MassFlowUnit ParseUnit(string str) /// Error parsing string. public static MassFlowUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -900,10 +931,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -919,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; } @@ -1023,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current MassFlow. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(MassFlow), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -1116,286 +1141,24 @@ public int CompareTo(object? obj) /// public int CompareTo(MassFlow other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another MassFlow within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(MassFlow other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is MassFlow otherTyped - && (tolerance is MassFlow toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'MassFlow'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(MassFlow other, MassFlow tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MassFlow. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(MassFlowUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - /// 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 NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } + IQuantity IQuantity.ToUnit(MassFlowUnit unit) => this.ToUnit(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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(MassFlowUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1410,137 +1173,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MassFlow)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MassFlow)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MassFlow)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(MassFlow)) - return this; - else if (conversionType == typeof(MassFlowUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return MassFlow.Info; - else if (conversionType == typeof(BaseDimensions)) - return MassFlow.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(MassFlow)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs b/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs index eb5fcc27cc..a5370e66e3 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -53,48 +48,118 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class MassFluxInfo: QuantityInfo + { + /// + public MassFluxInfo(string name, MassFluxUnit baseUnit, IEnumerable> unitMappings, MassFlux zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public MassFluxInfo(string name, MassFluxUnit baseUnit, IEnumerable> unitMappings, MassFlux zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, MassFlux.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.MassFlux", typeof(MassFlux).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the MassFlux quantity. + /// + /// A new instance of the class with the default settings. + public static MassFluxInfo CreateDefault() + { + return new MassFluxInfo(nameof(MassFlux), DefaultBaseUnit, GetDefaultMappings(), new MassFlux(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the MassFlux quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static MassFluxInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new MassFluxInfo(nameof(MassFlux), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new MassFlux(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-1L^-2M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, 1, -1, 0, 0, 0, 0); + + /// + /// The default base unit of MassFlux is KilogramPerSecondPerSquareMeter. All conversions, as defined in the , go via this value. + /// + public static MassFluxUnit DefaultBaseUnit { get; } = MassFluxUnit.KilogramPerSecondPerSquareMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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), + new QuantityValue(1, 1000000) + ); + } + } + static MassFlux() { - BaseDimensions = new BaseDimensions(-2, 1, -1, 0, 0, 0, 0); - BaseUnit = MassFluxUnit.KilogramPerSecondPerSquareMeter; - Units = Enum.GetValues(typeof(MassFluxUnit)).Cast().ToArray(); - Zero = new MassFlux(0, BaseUnit); - Info = new QuantityInfo("MassFlux", - new UnitInfo[] - { - new UnitInfo(MassFluxUnit.GramPerHourPerSquareCentimeter, "GramsPerHourPerSquareCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram, time: DurationUnit.Hour), "MassFlux"), - new UnitInfo(MassFluxUnit.GramPerHourPerSquareMeter, "GramsPerHourPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Hour), "MassFlux"), - new UnitInfo(MassFluxUnit.GramPerHourPerSquareMillimeter, "GramsPerHourPerSquareMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Gram, time: DurationUnit.Hour), "MassFlux"), - new UnitInfo(MassFluxUnit.GramPerSecondPerSquareCentimeter, "GramsPerSecondPerSquareCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram, time: DurationUnit.Second), "MassFlux"), - new UnitInfo(MassFluxUnit.GramPerSecondPerSquareMeter, "GramsPerSecondPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second), "MassFlux"), - new UnitInfo(MassFluxUnit.GramPerSecondPerSquareMillimeter, "GramsPerSecondPerSquareMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Gram, time: DurationUnit.Second), "MassFlux"), - new UnitInfo(MassFluxUnit.KilogramPerHourPerSquareCentimeter, "KilogramsPerHourPerSquareCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilogram, time: DurationUnit.Hour), "MassFlux"), - new UnitInfo(MassFluxUnit.KilogramPerHourPerSquareMeter, "KilogramsPerHourPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Hour), "MassFlux"), - new UnitInfo(MassFluxUnit.KilogramPerHourPerSquareMillimeter, "KilogramsPerHourPerSquareMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Hour), "MassFlux"), - new UnitInfo(MassFluxUnit.KilogramPerSecondPerSquareCentimeter, "KilogramsPerSecondPerSquareCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "MassFlux"), - new UnitInfo(MassFluxUnit.KilogramPerSecondPerSquareMeter, "KilogramsPerSecondPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "MassFlux"), - new UnitInfo(MassFluxUnit.KilogramPerSecondPerSquareMillimeter, "KilogramsPerSecondPerSquareMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "MassFlux"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(MassFluxInfo.CreateDefault); } /// @@ -102,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; @@ -116,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); @@ -127,166 +192,139 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of MassFlux, which is KilogramPerSecondPerSquareMeter. All conversions go via this value. /// - public static MassFluxUnit BaseUnit { get; } + public static MassFluxUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the MassFlux quantity. /// - public static MassFluxUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerSecondPerSquareMeter. /// - public static MassFlux Zero { get; } - - /// - public static MassFlux AdditiveIdentity => Zero; + public static MassFlux Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public MassFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => MassFlux.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -315,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); } @@ -323,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); } @@ -331,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); } @@ -339,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); } @@ -347,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); } @@ -355,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); } @@ -363,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); } @@ -371,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); } @@ -379,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); } @@ -387,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); } @@ -395,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); } @@ -403,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); } @@ -414,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); } @@ -475,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); } /// @@ -506,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); } /// @@ -531,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")); /// @@ -539,10 +570,10 @@ public static MassFluxUnit ParseUnit(string str) /// Error parsing string. public static MassFluxUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -557,10 +588,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -576,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; } @@ -638,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current MassFlux. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(MassFlux), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -731,244 +756,24 @@ public int CompareTo(object? obj) /// public int CompareTo(MassFlux other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another MassFlux within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(MassFlux other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is MassFlux otherTyped - && (tolerance is MassFlux toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'MassFlux'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(MassFlux other, MassFlux tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MassFlux. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(MassFluxUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(MassFluxUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -983,137 +788,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MassFlux)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MassFlux)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MassFlux)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(MassFlux)) - return this; - else if (conversionType == typeof(MassFluxUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return MassFlux.Info; - else if (conversionType == typeof(BaseDimensions)) - return MassFlux.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(MassFlux)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/MassFraction.g.cs b/UnitsNet/GeneratedCode/Quantities/MassFraction.g.cs index d8992b1464..d6c5eebb25 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassFraction.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassFraction.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -54,60 +49,154 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class MassFractionInfo: QuantityInfo + { + /// + public MassFractionInfo(string name, MassFractionUnit baseUnit, IEnumerable> unitMappings, MassFraction zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public MassFractionInfo(string name, MassFractionUnit baseUnit, IEnumerable> unitMappings, MassFraction zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, MassFraction.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.MassFraction", typeof(MassFraction).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the MassFraction quantity. + /// + /// A new instance of the class with the default settings. + public static MassFractionInfo CreateDefault() + { + return new MassFractionInfo(nameof(MassFraction), DefaultBaseUnit, GetDefaultMappings(), new MassFraction(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the MassFraction quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static MassFractionInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new MassFractionInfo(nameof(MassFraction), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new MassFraction(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is . + /// + public static BaseDimensions DefaultBaseDimensions { get; } = BaseDimensions.Dimensionless; + + /// + /// The default base unit of MassFraction is DecimalFraction. All conversions, as defined in the , go via this value. + /// + public static MassFractionUnit DefaultBaseUnit { get; } = MassFractionUnit.DecimalFraction; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for MassFraction. + public static IEnumerable> GetDefaultMappings() + { + 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, + 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() { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = MassFractionUnit.DecimalFraction; - Units = Enum.GetValues(typeof(MassFractionUnit)).Cast().ToArray(); - Zero = new MassFraction(0, BaseUnit); - Info = new QuantityInfo("MassFraction", - new UnitInfo[] - { - new UnitInfo(MassFractionUnit.CentigramPerGram, "CentigramsPerGram", BaseUnits.Undefined, "MassFraction"), - new UnitInfo(MassFractionUnit.CentigramPerKilogram, "CentigramsPerKilogram", BaseUnits.Undefined, "MassFraction"), - new UnitInfo(MassFractionUnit.DecagramPerGram, "DecagramsPerGram", BaseUnits.Undefined, "MassFraction"), - new UnitInfo(MassFractionUnit.DecagramPerKilogram, "DecagramsPerKilogram", BaseUnits.Undefined, "MassFraction"), - new UnitInfo(MassFractionUnit.DecigramPerGram, "DecigramsPerGram", BaseUnits.Undefined, "MassFraction"), - new UnitInfo(MassFractionUnit.DecigramPerKilogram, "DecigramsPerKilogram", BaseUnits.Undefined, "MassFraction"), - new UnitInfo(MassFractionUnit.DecimalFraction, "DecimalFractions", BaseUnits.Undefined, "MassFraction"), - new UnitInfo(MassFractionUnit.GramPerGram, "GramsPerGram", BaseUnits.Undefined, "MassFraction"), - new UnitInfo(MassFractionUnit.GramPerKilogram, "GramsPerKilogram", BaseUnits.Undefined, "MassFraction"), - new UnitInfo(MassFractionUnit.HectogramPerGram, "HectogramsPerGram", BaseUnits.Undefined, "MassFraction"), - new UnitInfo(MassFractionUnit.HectogramPerKilogram, "HectogramsPerKilogram", BaseUnits.Undefined, "MassFraction"), - new UnitInfo(MassFractionUnit.KilogramPerGram, "KilogramsPerGram", BaseUnits.Undefined, "MassFraction"), - new UnitInfo(MassFractionUnit.KilogramPerKilogram, "KilogramsPerKilogram", BaseUnits.Undefined, "MassFraction"), - new UnitInfo(MassFractionUnit.MicrogramPerGram, "MicrogramsPerGram", BaseUnits.Undefined, "MassFraction"), - new UnitInfo(MassFractionUnit.MicrogramPerKilogram, "MicrogramsPerKilogram", BaseUnits.Undefined, "MassFraction"), - new UnitInfo(MassFractionUnit.MilligramPerGram, "MilligramsPerGram", BaseUnits.Undefined, "MassFraction"), - new UnitInfo(MassFractionUnit.MilligramPerKilogram, "MilligramsPerKilogram", BaseUnits.Undefined, "MassFraction"), - new UnitInfo(MassFractionUnit.NanogramPerGram, "NanogramsPerGram", BaseUnits.Undefined, "MassFraction"), - new UnitInfo(MassFractionUnit.NanogramPerKilogram, "NanogramsPerKilogram", BaseUnits.Undefined, "MassFraction"), - new UnitInfo(MassFractionUnit.PartPerBillion, "PartsPerBillion", BaseUnits.Undefined, "MassFraction"), - new UnitInfo(MassFractionUnit.PartPerMillion, "PartsPerMillion", BaseUnits.Undefined, "MassFraction"), - new UnitInfo(MassFractionUnit.PartPerThousand, "PartsPerThousand", BaseUnits.Undefined, "MassFraction"), - new UnitInfo(MassFractionUnit.PartPerTrillion, "PartsPerTrillion", BaseUnits.Undefined, "MassFraction"), - new UnitInfo(MassFractionUnit.Percent, "Percent", BaseUnits.Undefined, "MassFraction"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(MassFractionInfo.CreateDefault); } /// @@ -115,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; @@ -126,250 +215,199 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of MassFraction, which is DecimalFraction. All conversions go via this value. /// - public static MassFractionUnit BaseUnit { get; } + public static MassFractionUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the MassFraction quantity. /// - public static MassFractionUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit DecimalFraction. /// - public static MassFraction Zero { get; } - - /// - public static MassFraction AdditiveIdentity => Zero; + public static MassFraction Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public MassFractionUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => MassFraction.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -398,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); } @@ -406,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); } @@ -414,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); } @@ -422,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); } @@ -430,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); } @@ -438,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); } @@ -446,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); } @@ -454,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); } @@ -462,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); } @@ -470,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); } @@ -478,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); } @@ -486,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); } @@ -494,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); } @@ -502,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); } @@ -510,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); } @@ -518,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); } @@ -526,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); } @@ -534,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); } @@ -542,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); } @@ -550,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); } @@ -558,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); } @@ -566,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); } @@ -574,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); } @@ -582,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); } @@ -593,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); } @@ -654,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); } /// @@ -685,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); } /// @@ -710,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")); /// @@ -718,10 +749,10 @@ public static MassFractionUnit ParseUnit(string str) /// Error parsing string. public static MassFractionUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -736,10 +767,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -755,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; } @@ -805,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current MassFraction. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(MassFraction), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -898,268 +923,24 @@ public int CompareTo(object? obj) /// public int CompareTo(MassFraction other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another MassFraction within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(MassFraction other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is MassFraction otherTyped - && (tolerance is MassFraction toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'MassFraction'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(MassFraction other, MassFraction tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MassFraction. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(MassFractionUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(MassFractionUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1174,137 +955,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MassFraction)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MassFraction)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MassFraction)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(MassFraction)) - return this; - else if (conversionType == typeof(MassFractionUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return MassFraction.Info; - else if (conversionType == typeof(BaseDimensions)) - return MassFraction.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(MassFraction)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs b/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs index d1c6c45b8b..3544032edf 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -48,64 +43,166 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class MassMomentOfInertiaInfo: QuantityInfo + { + /// + public MassMomentOfInertiaInfo(string name, MassMomentOfInertiaUnit baseUnit, IEnumerable> unitMappings, MassMomentOfInertia zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public MassMomentOfInertiaInfo(string name, MassMomentOfInertiaUnit baseUnit, IEnumerable> unitMappings, MassMomentOfInertia zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, MassMomentOfInertia.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.MassMomentOfInertia", typeof(MassMomentOfInertia).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the MassMomentOfInertia quantity. + /// + /// A new instance of the class with the default settings. + public static MassMomentOfInertiaInfo CreateDefault() + { + return new MassMomentOfInertiaInfo(nameof(MassMomentOfInertia), DefaultBaseUnit, GetDefaultMappings(), new MassMomentOfInertia(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the MassMomentOfInertia quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static MassMomentOfInertiaInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new MassMomentOfInertiaInfo(nameof(MassMomentOfInertia), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new MassMomentOfInertia(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is L^2M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, 0, 0, 0, 0, 0); + + /// + /// The default base unit of MassMomentOfInertia is KilogramSquareMeter. All conversions, as defined in the , go via this value. + /// + public static MassMomentOfInertiaUnit DefaultBaseUnit { get; } = MassMomentOfInertiaUnit.KilogramSquareMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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), + 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() { - BaseDimensions = new BaseDimensions(2, 1, 0, 0, 0, 0, 0); - BaseUnit = MassMomentOfInertiaUnit.KilogramSquareMeter; - Units = Enum.GetValues(typeof(MassMomentOfInertiaUnit)).Cast().ToArray(); - Zero = new MassMomentOfInertia(0, BaseUnit); - Info = new QuantityInfo("MassMomentOfInertia", - new UnitInfo[] - { - new UnitInfo(MassMomentOfInertiaUnit.GramSquareCentimeter, "GramSquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram), "MassMomentOfInertia"), - new UnitInfo(MassMomentOfInertiaUnit.GramSquareDecimeter, "GramSquareDecimeters", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Gram), "MassMomentOfInertia"), - new UnitInfo(MassMomentOfInertiaUnit.GramSquareMeter, "GramSquareMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram), "MassMomentOfInertia"), - new UnitInfo(MassMomentOfInertiaUnit.GramSquareMillimeter, "GramSquareMillimeters", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Gram), "MassMomentOfInertia"), - new UnitInfo(MassMomentOfInertiaUnit.KilogramSquareCentimeter, "KilogramSquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilogram), "MassMomentOfInertia"), - new UnitInfo(MassMomentOfInertiaUnit.KilogramSquareDecimeter, "KilogramSquareDecimeters", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilogram), "MassMomentOfInertia"), - new UnitInfo(MassMomentOfInertiaUnit.KilogramSquareMeter, "KilogramSquareMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram), "MassMomentOfInertia"), - new UnitInfo(MassMomentOfInertiaUnit.KilogramSquareMillimeter, "KilogramSquareMillimeters", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram), "MassMomentOfInertia"), - new UnitInfo(MassMomentOfInertiaUnit.KilotonneSquareCentimeter, "KilotonneSquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilotonne), "MassMomentOfInertia"), - new UnitInfo(MassMomentOfInertiaUnit.KilotonneSquareDecimeter, "KilotonneSquareDecimeters", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilotonne), "MassMomentOfInertia"), - new UnitInfo(MassMomentOfInertiaUnit.KilotonneSquareMeter, "KilotonneSquareMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilotonne), "MassMomentOfInertia"), - new UnitInfo(MassMomentOfInertiaUnit.KilotonneSquareMillimeter, "KilotonneSquareMillimeters", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilotonne), "MassMomentOfInertia"), - new UnitInfo(MassMomentOfInertiaUnit.MegatonneSquareCentimeter, "MegatonneSquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Megatonne), "MassMomentOfInertia"), - new UnitInfo(MassMomentOfInertiaUnit.MegatonneSquareDecimeter, "MegatonneSquareDecimeters", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Megatonne), "MassMomentOfInertia"), - new UnitInfo(MassMomentOfInertiaUnit.MegatonneSquareMeter, "MegatonneSquareMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Megatonne), "MassMomentOfInertia"), - new UnitInfo(MassMomentOfInertiaUnit.MegatonneSquareMillimeter, "MegatonneSquareMillimeters", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Megatonne), "MassMomentOfInertia"), - new UnitInfo(MassMomentOfInertiaUnit.MilligramSquareCentimeter, "MilligramSquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Milligram), "MassMomentOfInertia"), - new UnitInfo(MassMomentOfInertiaUnit.MilligramSquareDecimeter, "MilligramSquareDecimeters", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Milligram), "MassMomentOfInertia"), - new UnitInfo(MassMomentOfInertiaUnit.MilligramSquareMeter, "MilligramSquareMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram), "MassMomentOfInertia"), - new UnitInfo(MassMomentOfInertiaUnit.MilligramSquareMillimeter, "MilligramSquareMillimeters", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Milligram), "MassMomentOfInertia"), - new UnitInfo(MassMomentOfInertiaUnit.PoundSquareFoot, "PoundSquareFeet", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Pound), "MassMomentOfInertia"), - new UnitInfo(MassMomentOfInertiaUnit.PoundSquareInch, "PoundSquareInches", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Pound), "MassMomentOfInertia"), - new UnitInfo(MassMomentOfInertiaUnit.SlugSquareFoot, "SlugSquareFeet", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Slug), "MassMomentOfInertia"), - new UnitInfo(MassMomentOfInertiaUnit.SlugSquareInch, "SlugSquareInches", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Slug), "MassMomentOfInertia"), - new UnitInfo(MassMomentOfInertiaUnit.TonneSquareCentimeter, "TonneSquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Tonne), "MassMomentOfInertia"), - new UnitInfo(MassMomentOfInertiaUnit.TonneSquareDecimeter, "TonneSquareDecimeters", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Tonne), "MassMomentOfInertia"), - new UnitInfo(MassMomentOfInertiaUnit.TonneSquareMeter, "TonneSquareMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Tonne), "MassMomentOfInertia"), - new UnitInfo(MassMomentOfInertiaUnit.TonneSquareMillimeter, "TonneSquareMillimeters", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Tonne), "MassMomentOfInertia"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(MassMomentOfInertiaInfo.CreateDefault); } /// @@ -113,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; @@ -127,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); @@ -138,278 +235,219 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of MassMomentOfInertia, which is KilogramSquareMeter. All conversions go via this value. /// - public static MassMomentOfInertiaUnit BaseUnit { get; } + public static MassMomentOfInertiaUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the MassMomentOfInertia quantity. /// - public static MassMomentOfInertiaUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit KilogramSquareMeter. /// - public static MassMomentOfInertia Zero { get; } - - /// - public static MassMomentOfInertia AdditiveIdentity => Zero; + public static MassMomentOfInertia Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public MassMomentOfInertiaUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => MassMomentOfInertia.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -438,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); } @@ -446,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); } @@ -454,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); } @@ -462,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); } @@ -470,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); } @@ -478,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); } @@ -486,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); } @@ -494,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); } @@ -502,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); } @@ -510,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); } @@ -518,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); } @@ -526,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); } @@ -534,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); } @@ -542,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); } @@ -550,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); } @@ -558,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); } @@ -566,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); } @@ -574,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); } @@ -582,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); } @@ -590,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); } @@ -598,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); } @@ -606,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); } @@ -614,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); } @@ -622,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); } @@ -630,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); } @@ -638,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); } @@ -646,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); } @@ -654,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); } @@ -665,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); } @@ -726,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); } /// @@ -757,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); } /// @@ -782,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")); /// @@ -790,10 +821,10 @@ public static MassMomentOfInertiaUnit ParseUnit(string str) /// Error parsing string. public static MassMomentOfInertiaUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -808,10 +839,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -827,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; } @@ -867,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current MassMomentOfInertia. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(MassMomentOfInertia), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -960,276 +985,24 @@ public int CompareTo(object? obj) /// public int CompareTo(MassMomentOfInertia other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another MassMomentOfInertia within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(MassMomentOfInertia other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is MassMomentOfInertia otherTyped - && (tolerance is MassMomentOfInertia toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'MassMomentOfInertia'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(MassMomentOfInertia other, MassMomentOfInertia tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MassMomentOfInertia. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(MassMomentOfInertiaUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(MassMomentOfInertiaUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1244,137 +1017,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MassMomentOfInertia)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MassMomentOfInertia)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MassMomentOfInertia)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(MassMomentOfInertia)) - return this; - else if (conversionType == typeof(MassMomentOfInertiaUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return MassMomentOfInertia.Info; - else if (conversionType == typeof(BaseDimensions)) - return MassMomentOfInertia.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(MassMomentOfInertia)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Molality.g.cs b/UnitsNet/GeneratedCode/Quantities/Molality.g.cs index 1b1f031ebd..92b1d56ab6 100644 --- a/UnitsNet/GeneratedCode/Quantities/Molality.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Molality.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,39 +46,91 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static Molality() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class MolalityInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(0, -1, 0, 0, 0, 1, 0); - BaseUnit = MolalityUnit.MolePerKilogram; - Units = Enum.GetValues(typeof(MolalityUnit)).Cast().ToArray(); - Zero = new Molality(0, BaseUnit); - Info = new QuantityInfo("Molality", - new UnitInfo[] - { - new UnitInfo(MolalityUnit.MillimolePerKilogram, "MillimolesPerKilogram", new BaseUnits(mass: MassUnit.Kilogram, amount: AmountOfSubstanceUnit.Millimole), "Molality"), - new UnitInfo(MolalityUnit.MolePerGram, "MolesPerGram", new BaseUnits(mass: MassUnit.Gram, amount: AmountOfSubstanceUnit.Mole), "Molality"), - new UnitInfo(MolalityUnit.MolePerKilogram, "MolesPerKilogram", new BaseUnits(mass: MassUnit.Kilogram, amount: AmountOfSubstanceUnit.Mole), "Molality"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public MolalityInfo(string name, MolalityUnit baseUnit, IEnumerable> unitMappings, Molality zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public MolalityInfo(string name, MolalityUnit baseUnit, IEnumerable> unitMappings, Molality zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Molality.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Molality", typeof(Molality).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the Molality quantity. + /// + /// A new instance of the class with the default settings. + public static MolalityInfo CreateDefault() + { + return new MolalityInfo(nameof(Molality), DefaultBaseUnit, GetDefaultMappings(), new Molality(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Molality quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static MolalityInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new MolalityInfo(nameof(Molality), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Molality(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is M^-1N. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, -1, 0, 0, 0, 1, 0); + + /// + /// The default base unit of Molality is MolePerKilogram. All conversions, as defined in the , go via this value. + /// + public static MolalityUnit DefaultBaseUnit { get; } = MolalityUnit.MolePerKilogram; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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 = UnitsNetSetup.CreateQuantityInfo(MolalityInfo.CreateDefault); } /// @@ -91,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; @@ -105,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); @@ -116,103 +163,94 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Molality, which is MolePerKilogram. All conversions go via this value. /// - public static MolalityUnit BaseUnit { get; } + public static MolalityUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Molality quantity. /// - public static MolalityUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit MolePerKilogram. /// - public static Molality Zero { get; } - - /// - public static Molality AdditiveIdentity => Zero; + public static Molality Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public MolalityUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Molality.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -241,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); } @@ -249,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); } @@ -257,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); } @@ -268,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); } @@ -329,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); } /// @@ -360,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); } /// @@ -385,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")); /// @@ -393,10 +424,10 @@ public static MolalityUnit ParseUnit(string str) /// Error parsing string. public static MolalityUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -411,10 +442,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -430,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; } @@ -470,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Molality. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Molality), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -563,226 +588,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Molality other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Molality within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Molality other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Molality otherTyped - && (tolerance is Molality toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Molality'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Molality other, Molality tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Molality. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(MolalityUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(MolalityUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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), - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -797,137 +620,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Molality)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Molality)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Molality)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Molality)) - return this; - else if (conversionType == typeof(MolalityUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Molality.Info; - else if (conversionType == typeof(BaseDimensions)) - return Molality.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Molality)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs index b0a2ccea3a..95327691d5 100644 --- a/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -51,39 +46,91 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static MolarEnergy() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class MolarEnergyInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, -1, 0); - BaseUnit = MolarEnergyUnit.JoulePerMole; - Units = Enum.GetValues(typeof(MolarEnergyUnit)).Cast().ToArray(); - Zero = new MolarEnergy(0, BaseUnit); - Info = new QuantityInfo("MolarEnergy", - new UnitInfo[] - { - new UnitInfo(MolarEnergyUnit.JoulePerMole, "JoulesPerMole", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, amount: AmountOfSubstanceUnit.Mole), "MolarEnergy"), - new UnitInfo(MolarEnergyUnit.KilojoulePerMole, "KilojoulesPerMole", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, amount: AmountOfSubstanceUnit.Millimole), "MolarEnergy"), - new UnitInfo(MolarEnergyUnit.MegajoulePerMole, "MegajoulesPerMole", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, amount: AmountOfSubstanceUnit.Micromole), "MolarEnergy"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public MolarEnergyInfo(string name, MolarEnergyUnit baseUnit, IEnumerable> unitMappings, MolarEnergy zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public MolarEnergyInfo(string name, MolarEnergyUnit baseUnit, IEnumerable> unitMappings, MolarEnergy zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, MolarEnergy.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.MolarEnergy", typeof(MolarEnergy).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the MolarEnergy quantity. + /// + /// A new instance of the class with the default settings. + public static MolarEnergyInfo CreateDefault() + { + return new MolarEnergyInfo(nameof(MolarEnergy), DefaultBaseUnit, GetDefaultMappings(), new MolarEnergy(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the MolarEnergy quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static MolarEnergyInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new MolarEnergyInfo(nameof(MolarEnergy), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new MolarEnergy(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-2L^2MN^-1. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -2, 0, 0, -1, 0); + + /// + /// The default base unit of MolarEnergy is JoulePerMole. All conversions, as defined in the , go via this value. + /// + public static MolarEnergyUnit DefaultBaseUnit { get; } = MolarEnergyUnit.JoulePerMole; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for MolarEnergy. + public static IEnumerable> 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), + 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 = UnitsNetSetup.CreateQuantityInfo(MolarEnergyInfo.CreateDefault); } /// @@ -91,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; @@ -105,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); @@ -116,103 +163,94 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of MolarEnergy, which is JoulePerMole. All conversions go via this value. /// - public static MolarEnergyUnit BaseUnit { get; } + public static MolarEnergyUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the MolarEnergy quantity. /// - public static MolarEnergyUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerMole. /// - public static MolarEnergy Zero { get; } - - /// - public static MolarEnergy AdditiveIdentity => Zero; + public static MolarEnergy Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public MolarEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => MolarEnergy.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -241,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); } @@ -249,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); } @@ -257,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); } @@ -268,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); } @@ -329,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); } /// @@ -360,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); } /// @@ -385,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")); /// @@ -393,10 +424,10 @@ public static MolarEnergyUnit ParseUnit(string str) /// Error parsing string. public static MolarEnergyUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -411,10 +442,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -430,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; } @@ -480,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current MolarEnergy. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(MolarEnergy), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -573,226 +598,24 @@ public int CompareTo(object? obj) /// public int CompareTo(MolarEnergy other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another MolarEnergy within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(MolarEnergy other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is MolarEnergy otherTyped - && (tolerance is MolarEnergy toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'MolarEnergy'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(MolarEnergy other, MolarEnergy tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MolarEnergy. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(MolarEnergyUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(MolarEnergyUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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), - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -807,137 +630,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MolarEnergy)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MolarEnergy)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MolarEnergy)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(MolarEnergy)) - return this; - else if (conversionType == typeof(MolarEnergyUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return MolarEnergy.Info; - else if (conversionType == typeof(BaseDimensions)) - return MolarEnergy.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(MolarEnergy)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs index b73d38497f..b3a38fa45a 100644 --- a/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -48,39 +43,91 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static MolarEntropy() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class MolarEntropyInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, -1, -1, 0); - BaseUnit = MolarEntropyUnit.JoulePerMoleKelvin; - Units = Enum.GetValues(typeof(MolarEntropyUnit)).Cast().ToArray(); - Zero = new MolarEntropy(0, BaseUnit); - Info = new QuantityInfo("MolarEntropy", - new UnitInfo[] - { - new UnitInfo(MolarEntropyUnit.JoulePerMoleKelvin, "JoulesPerMoleKelvin", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin, amount: AmountOfSubstanceUnit.Mole), "MolarEntropy"), - new UnitInfo(MolarEntropyUnit.KilojoulePerMoleKelvin, "KilojoulesPerMoleKelvin", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin, amount: AmountOfSubstanceUnit.Millimole), "MolarEntropy"), - new UnitInfo(MolarEntropyUnit.MegajoulePerMoleKelvin, "MegajoulesPerMoleKelvin", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin, amount: AmountOfSubstanceUnit.Micromole), "MolarEntropy"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public MolarEntropyInfo(string name, MolarEntropyUnit baseUnit, IEnumerable> unitMappings, MolarEntropy zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public MolarEntropyInfo(string name, MolarEntropyUnit baseUnit, IEnumerable> unitMappings, MolarEntropy zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, MolarEntropy.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.MolarEntropy", typeof(MolarEntropy).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the MolarEntropy quantity. + /// + /// A new instance of the class with the default settings. + public static MolarEntropyInfo CreateDefault() + { + return new MolarEntropyInfo(nameof(MolarEntropy), DefaultBaseUnit, GetDefaultMappings(), new MolarEntropy(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the MolarEntropy quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static MolarEntropyInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new MolarEntropyInfo(nameof(MolarEntropy), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new MolarEntropy(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-2L^2MΘ^-1N^-1. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -2, 0, -1, -1, 0); + + /// + /// The default base unit of MolarEntropy is JoulePerMoleKelvin. All conversions, as defined in the , go via this value. + /// + public static MolarEntropyUnit DefaultBaseUnit { get; } = MolarEntropyUnit.JoulePerMoleKelvin; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for MolarEntropy. + public static IEnumerable> 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), + 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 = UnitsNetSetup.CreateQuantityInfo(MolarEntropyInfo.CreateDefault); } /// @@ -88,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; @@ -102,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); @@ -113,103 +160,94 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of MolarEntropy, which is JoulePerMoleKelvin. All conversions go via this value. /// - public static MolarEntropyUnit BaseUnit { get; } + public static MolarEntropyUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the MolarEntropy quantity. /// - public static MolarEntropyUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerMoleKelvin. /// - public static MolarEntropy Zero { get; } - - /// - public static MolarEntropy AdditiveIdentity => Zero; + public static MolarEntropy Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public MolarEntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => MolarEntropy.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -238,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); } @@ -246,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); } @@ -254,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); } @@ -265,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); } @@ -326,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); } /// @@ -357,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); } /// @@ -382,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")); /// @@ -390,10 +421,10 @@ public static MolarEntropyUnit ParseUnit(string str) /// Error parsing string. public static MolarEntropyUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -408,10 +439,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -427,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; } @@ -467,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current MolarEntropy. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(MolarEntropy), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -560,226 +585,24 @@ public int CompareTo(object? obj) /// public int CompareTo(MolarEntropy other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another MolarEntropy within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(MolarEntropy other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is MolarEntropy otherTyped - && (tolerance is MolarEntropy toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'MolarEntropy'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(MolarEntropy other, MolarEntropy tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MolarEntropy. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(MolarEntropyUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(MolarEntropyUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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), - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -794,137 +617,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MolarEntropy)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MolarEntropy)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MolarEntropy)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(MolarEntropy)) - return this; - else if (conversionType == typeof(MolarEntropyUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return MolarEntropy.Info; - else if (conversionType == typeof(BaseDimensions)) - return MolarEntropy.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(MolarEntropy)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/MolarFlow.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarFlow.g.cs index 6e9b728f67..134f04b55e 100644 --- a/UnitsNet/GeneratedCode/Quantities/MolarFlow.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MolarFlow.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -54,45 +49,109 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class MolarFlowInfo: QuantityInfo + { + /// + public MolarFlowInfo(string name, MolarFlowUnit baseUnit, IEnumerable> unitMappings, MolarFlow zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public MolarFlowInfo(string name, MolarFlowUnit baseUnit, IEnumerable> unitMappings, MolarFlow zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, MolarFlow.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.MolarFlow", typeof(MolarFlow).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the MolarFlow quantity. + /// + /// A new instance of the class with the default settings. + public static MolarFlowInfo CreateDefault() + { + return new MolarFlowInfo(nameof(MolarFlow), DefaultBaseUnit, GetDefaultMappings(), new MolarFlow(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the MolarFlow quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static MolarFlowInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new MolarFlowInfo(nameof(MolarFlow), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new MolarFlow(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-1N. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, -1, 0, 0, 1, 0); + + /// + /// The default base unit of MolarFlow is MolePerSecond. All conversions, as defined in the , go via this value. + /// + public static MolarFlowUnit DefaultBaseUnit { get; } = MolarFlowUnit.MolePerSecond; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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), + 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() { - BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 1, 0); - BaseUnit = MolarFlowUnit.MolePerSecond; - Units = Enum.GetValues(typeof(MolarFlowUnit)).Cast().ToArray(); - Zero = new MolarFlow(0, BaseUnit); - Info = new QuantityInfo("MolarFlow", - new UnitInfo[] - { - new UnitInfo(MolarFlowUnit.KilomolePerHour, "KilomolesPerHour", new BaseUnits(time: DurationUnit.Hour, amount: AmountOfSubstanceUnit.Kilomole), "MolarFlow"), - new UnitInfo(MolarFlowUnit.KilomolePerMinute, "KilomolesPerMinute", new BaseUnits(time: DurationUnit.Minute, amount: AmountOfSubstanceUnit.Kilomole), "MolarFlow"), - new UnitInfo(MolarFlowUnit.KilomolePerSecond, "KilomolesPerSecond", new BaseUnits(time: DurationUnit.Second, amount: AmountOfSubstanceUnit.Kilomole), "MolarFlow"), - new UnitInfo(MolarFlowUnit.MolePerHour, "MolesPerHour", new BaseUnits(time: DurationUnit.Hour, amount: AmountOfSubstanceUnit.Mole), "MolarFlow"), - new UnitInfo(MolarFlowUnit.MolePerMinute, "MolesPerMinute", new BaseUnits(time: DurationUnit.Minute, amount: AmountOfSubstanceUnit.Mole), "MolarFlow"), - new UnitInfo(MolarFlowUnit.MolePerSecond, "MolesPerSecond", new BaseUnits(time: DurationUnit.Second, amount: AmountOfSubstanceUnit.Mole), "MolarFlow"), - new UnitInfo(MolarFlowUnit.PoundMolePerHour, "PoundMolesPerHour", new BaseUnits(time: DurationUnit.Hour, amount: AmountOfSubstanceUnit.PoundMole), "MolarFlow"), - new UnitInfo(MolarFlowUnit.PoundMolePerMinute, "PoundMolesPerMinute", new BaseUnits(time: DurationUnit.Minute, amount: AmountOfSubstanceUnit.PoundMole), "MolarFlow"), - new UnitInfo(MolarFlowUnit.PoundMolePerSecond, "PoundMolesPerSecond", new BaseUnits(time: DurationUnit.Second, amount: AmountOfSubstanceUnit.PoundMole), "MolarFlow"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(MolarFlowInfo.CreateDefault); } /// @@ -100,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; @@ -114,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); @@ -125,145 +184,124 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of MolarFlow, which is MolePerSecond. All conversions go via this value. /// - public static MolarFlowUnit BaseUnit { get; } + public static MolarFlowUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the MolarFlow quantity. /// - public static MolarFlowUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit MolePerSecond. /// - public static MolarFlow Zero { get; } - - /// - public static MolarFlow AdditiveIdentity => Zero; + public static MolarFlow Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public MolarFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => MolarFlow.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -292,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); } @@ -300,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); } @@ -308,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); } @@ -316,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); } @@ -324,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); } @@ -332,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); } @@ -340,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); } @@ -348,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); } @@ -356,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); } @@ -367,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); } @@ -428,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); } /// @@ -459,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); } /// @@ -484,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")); /// @@ -492,10 +523,10 @@ public static MolarFlowUnit ParseUnit(string str) /// Error parsing string. public static MolarFlowUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -510,10 +541,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -529,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; } @@ -597,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current MolarFlow. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(MolarFlow), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -690,238 +715,24 @@ public int CompareTo(object? obj) /// public int CompareTo(MolarFlow other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another MolarFlow within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(MolarFlow other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is MolarFlow otherTyped - && (tolerance is MolarFlow toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'MolarFlow'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(MolarFlow other, MolarFlow tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MolarFlow. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(MolarFlowUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(MolarFlowUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -936,137 +747,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MolarFlow)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MolarFlow)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MolarFlow)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(MolarFlow)) - return this; - else if (conversionType == typeof(MolarFlowUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return MolarFlow.Info; - else if (conversionType == typeof(BaseDimensions)) - return MolarFlow.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(MolarFlow)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs index ed8423a77b..6b64dad801 100644 --- a/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -53,49 +48,121 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class MolarMassInfo: QuantityInfo + { + /// + public MolarMassInfo(string name, MolarMassUnit baseUnit, IEnumerable> unitMappings, MolarMass zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public MolarMassInfo(string name, MolarMassUnit baseUnit, IEnumerable> unitMappings, MolarMass zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, MolarMass.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.MolarMass", typeof(MolarMass).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the MolarMass quantity. + /// + /// A new instance of the class with the default settings. + public static MolarMassInfo CreateDefault() + { + return new MolarMassInfo(nameof(MolarMass), DefaultBaseUnit, GetDefaultMappings(), new MolarMass(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the MolarMass quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static MolarMassInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new MolarMassInfo(nameof(MolarMass), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new MolarMass(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is MN^-1. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 1, 0, 0, 0, -1, 0); + + /// + /// The default base unit of MolarMass is KilogramPerMole. All conversions, as defined in the , go via this value. + /// + public static MolarMassUnit DefaultBaseUnit { get; } = MolarMassUnit.KilogramPerMole; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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), + 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() { - BaseDimensions = new BaseDimensions(0, 1, 0, 0, 0, -1, 0); - BaseUnit = MolarMassUnit.KilogramPerMole; - Units = Enum.GetValues(typeof(MolarMassUnit)).Cast().ToArray(); - Zero = new MolarMass(0, BaseUnit); - Info = new QuantityInfo("MolarMass", - new UnitInfo[] - { - new UnitInfo(MolarMassUnit.CentigramPerMole, "CentigramsPerMole", new BaseUnits(mass: MassUnit.Centigram, amount: AmountOfSubstanceUnit.Mole), "MolarMass"), - new UnitInfo(MolarMassUnit.DecagramPerMole, "DecagramsPerMole", new BaseUnits(mass: MassUnit.Decagram, amount: AmountOfSubstanceUnit.Mole), "MolarMass"), - new UnitInfo(MolarMassUnit.DecigramPerMole, "DecigramsPerMole", new BaseUnits(mass: MassUnit.Decigram, amount: AmountOfSubstanceUnit.Mole), "MolarMass"), - new UnitInfo(MolarMassUnit.GramPerMole, "GramsPerMole", new BaseUnits(mass: MassUnit.Gram, amount: AmountOfSubstanceUnit.Mole), "MolarMass"), - new UnitInfo(MolarMassUnit.HectogramPerMole, "HectogramsPerMole", new BaseUnits(mass: MassUnit.Hectogram, amount: AmountOfSubstanceUnit.Mole), "MolarMass"), - new UnitInfo(MolarMassUnit.KilogramPerKilomole, "KilogramsPerKilomole", new BaseUnits(mass: MassUnit.Kilogram, amount: AmountOfSubstanceUnit.Kilomole), "MolarMass"), - new UnitInfo(MolarMassUnit.KilogramPerMole, "KilogramsPerMole", new BaseUnits(mass: MassUnit.Kilogram, amount: AmountOfSubstanceUnit.Mole), "MolarMass"), - new UnitInfo(MolarMassUnit.KilopoundPerMole, "KilopoundsPerMole", new BaseUnits(mass: MassUnit.Kilopound, amount: AmountOfSubstanceUnit.Mole), "MolarMass"), - new UnitInfo(MolarMassUnit.MegapoundPerMole, "MegapoundsPerMole", new BaseUnits(mass: MassUnit.Megapound, amount: AmountOfSubstanceUnit.Mole), "MolarMass"), - new UnitInfo(MolarMassUnit.MicrogramPerMole, "MicrogramsPerMole", new BaseUnits(mass: MassUnit.Microgram, amount: AmountOfSubstanceUnit.Mole), "MolarMass"), - new UnitInfo(MolarMassUnit.MilligramPerMole, "MilligramsPerMole", new BaseUnits(mass: MassUnit.Milligram, amount: AmountOfSubstanceUnit.Mole), "MolarMass"), - new UnitInfo(MolarMassUnit.NanogramPerMole, "NanogramsPerMole", new BaseUnits(mass: MassUnit.Nanogram, amount: AmountOfSubstanceUnit.Mole), "MolarMass"), - new UnitInfo(MolarMassUnit.PoundPerMole, "PoundsPerMole", new BaseUnits(mass: MassUnit.Pound, amount: AmountOfSubstanceUnit.Mole), "MolarMass"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(MolarMassInfo.CreateDefault); } /// @@ -103,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; @@ -117,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); @@ -128,173 +195,144 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of MolarMass, which is KilogramPerMole. All conversions go via this value. /// - public static MolarMassUnit BaseUnit { get; } + public static MolarMassUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the MolarMass quantity. /// - public static MolarMassUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit KilogramPerMole. /// - public static MolarMass Zero { get; } - - /// - public static MolarMass AdditiveIdentity => Zero; + public static MolarMass Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public MolarMassUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => MolarMass.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -323,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); } @@ -331,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); } @@ -339,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); } @@ -347,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); } @@ -355,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); } @@ -363,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); } @@ -371,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); } @@ -379,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); } @@ -387,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); } @@ -395,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); } @@ -403,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); } @@ -411,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); } @@ -419,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); } @@ -430,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); } @@ -491,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); } /// @@ -522,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); } /// @@ -547,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")); /// @@ -555,10 +586,10 @@ public static MolarMassUnit ParseUnit(string str) /// Error parsing string. public static MolarMassUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -573,10 +604,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -592,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; } @@ -654,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current MolarMass. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(MolarMass), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -747,246 +772,24 @@ public int CompareTo(object? obj) /// public int CompareTo(MolarMass other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another MolarMass within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(MolarMass other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is MolarMass otherTyped - && (tolerance is MolarMass toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'MolarMass'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(MolarMass other, MolarMass tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current MolarMass. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(MolarMassUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(MolarMassUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1001,137 +804,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MolarMass)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MolarMass)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(MolarMass)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(MolarMass)) - return this; - else if (conversionType == typeof(MolarMassUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return MolarMass.Info; - else if (conversionType == typeof(BaseDimensions)) - return MolarMass.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(MolarMass)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs b/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs index 09ea4ce616..02372ef6eb 100644 --- a/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -58,47 +53,115 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class MolarityInfo: QuantityInfo + { + /// + public MolarityInfo(string name, MolarityUnit baseUnit, IEnumerable> unitMappings, Molarity zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public MolarityInfo(string name, MolarityUnit baseUnit, IEnumerable> unitMappings, Molarity zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Molarity.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Molarity", typeof(Molarity).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Molarity quantity. + /// + /// A new instance of the class with the default settings. + public static MolarityInfo CreateDefault() + { + return new MolarityInfo(nameof(Molarity), DefaultBaseUnit, GetDefaultMappings(), new Molarity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Molarity quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static MolarityInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new MolarityInfo(nameof(Molarity), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Molarity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is L^-3N. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-3, 0, 0, 0, 0, 1, 0); + + /// + /// The default base unit of Molarity is MolePerCubicMeter. All conversions, as defined in the , go via this value. + /// + public static MolarityUnit DefaultBaseUnit { get; } = MolarityUnit.MolePerCubicMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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), + 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() { - BaseDimensions = new BaseDimensions(-3, 0, 0, 0, 0, 1, 0); - BaseUnit = MolarityUnit.MolePerCubicMeter; - Units = Enum.GetValues(typeof(MolarityUnit)).Cast().ToArray(); - Zero = new Molarity(0, BaseUnit); - Info = new QuantityInfo("Molarity", - new UnitInfo[] - { - new UnitInfo(MolarityUnit.CentimolePerLiter, "CentimolesPerLiter", new BaseUnits(length: LengthUnit.Decimeter, amount: AmountOfSubstanceUnit.Centimole), "Molarity"), - new UnitInfo(MolarityUnit.DecimolePerLiter, "DecimolesPerLiter", new BaseUnits(length: LengthUnit.Decimeter, amount: AmountOfSubstanceUnit.Decimole), "Molarity"), - new UnitInfo(MolarityUnit.FemtomolePerLiter, "FemtomolesPerLiter", new BaseUnits(length: LengthUnit.Decimeter, amount: AmountOfSubstanceUnit.Femtomole), "Molarity"), - new UnitInfo(MolarityUnit.KilomolePerCubicMeter, "KilomolesPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, amount: AmountOfSubstanceUnit.Kilomole), "Molarity"), - new UnitInfo(MolarityUnit.MicromolePerLiter, "MicromolesPerLiter", new BaseUnits(length: LengthUnit.Decimeter, amount: AmountOfSubstanceUnit.Micromole), "Molarity"), - new UnitInfo(MolarityUnit.MillimolePerLiter, "MillimolesPerLiter", new BaseUnits(length: LengthUnit.Decimeter, amount: AmountOfSubstanceUnit.Millimole), "Molarity"), - new UnitInfo(MolarityUnit.MolePerCubicMeter, "MolesPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, amount: AmountOfSubstanceUnit.Mole), "Molarity"), - new UnitInfo(MolarityUnit.MolePerLiter, "MolesPerLiter", new BaseUnits(length: LengthUnit.Decimeter, amount: AmountOfSubstanceUnit.Mole), "Molarity"), - new UnitInfo(MolarityUnit.NanomolePerLiter, "NanomolesPerLiter", new BaseUnits(length: LengthUnit.Decimeter, amount: AmountOfSubstanceUnit.Nanomole), "Molarity"), - new UnitInfo(MolarityUnit.PicomolePerLiter, "PicomolesPerLiter", new BaseUnits(length: LengthUnit.Decimeter, amount: AmountOfSubstanceUnit.Picomole), "Molarity"), - new UnitInfo(MolarityUnit.PoundMolePerCubicFoot, "PoundMolesPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, amount: AmountOfSubstanceUnit.PoundMole), "Molarity"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(MolarityInfo.CreateDefault); } /// @@ -106,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; @@ -120,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); @@ -131,159 +194,134 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Molarity, which is MolePerCubicMeter. All conversions go via this value. /// - public static MolarityUnit BaseUnit { get; } + public static MolarityUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Molarity quantity. /// - public static MolarityUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit MolePerCubicMeter. /// - public static Molarity Zero { get; } - - /// - public static Molarity AdditiveIdentity => Zero; + public static Molarity Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public MolarityUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Molarity.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -312,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); } @@ -320,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); } @@ -328,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); } @@ -336,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); } @@ -344,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); } @@ -352,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); } @@ -360,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); } @@ -368,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); } @@ -376,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); } @@ -384,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); } @@ -392,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); } @@ -403,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); } @@ -464,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); } /// @@ -495,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); } /// @@ -520,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")); /// @@ -528,10 +559,10 @@ public static MolarityUnit ParseUnit(string str) /// Error parsing string. public static MolarityUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -546,10 +577,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -565,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; } @@ -639,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Molarity. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Molarity), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -732,242 +757,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Molarity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Molarity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Molarity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Molarity otherTyped - && (tolerance is Molarity toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Molarity'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Molarity other, Molarity tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Molarity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(MolarityUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(MolarityUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -982,137 +789,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Molarity)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Molarity)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Molarity)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Molarity)) - return this; - else if (conversionType == typeof(MolarityUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Molarity.Info; - else if (conversionType == typeof(BaseDimensions)) - return Molarity.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Molarity)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs b/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs index 5c7f960069..14798f601b 100644 --- a/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,37 +46,85 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static Permeability() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class PermeabilityInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(1, 1, -2, -2, 0, 0, 0); - BaseUnit = PermeabilityUnit.HenryPerMeter; - Units = Enum.GetValues(typeof(PermeabilityUnit)).Cast().ToArray(); - Zero = new Permeability(0, BaseUnit); - Info = new QuantityInfo("Permeability", - new UnitInfo[] - { - new UnitInfo(PermeabilityUnit.HenryPerMeter, "HenriesPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "Permeability"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public PermeabilityInfo(string name, PermeabilityUnit baseUnit, IEnumerable> unitMappings, Permeability zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public PermeabilityInfo(string name, PermeabilityUnit baseUnit, IEnumerable> unitMappings, Permeability zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Permeability.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Permeability", typeof(Permeability).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the Permeability quantity. + /// + /// A new instance of the class with the default settings. + public static PermeabilityInfo CreateDefault() + { + return new PermeabilityInfo(nameof(Permeability), DefaultBaseUnit, GetDefaultMappings(), new Permeability(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Permeability quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static PermeabilityInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new PermeabilityInfo(nameof(Permeability), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Permeability(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-2LMI^-2. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, 1, -2, -2, 0, 0, 0); + + /// + /// The default base unit of Permeability is HenryPerMeter. All conversions, as defined in the , go via this value. + /// + public static PermeabilityUnit DefaultBaseUnit { get; } = PermeabilityUnit.HenryPerMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Permeability. + public static IEnumerable> GetDefaultMappings() + { + yield return new (PermeabilityUnit.HenryPerMeter, "HenryPerMeter", "HenriesPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); + } + } + + static Permeability() + { + Info = UnitsNetSetup.CreateQuantityInfo(PermeabilityInfo.CreateDefault); } /// @@ -89,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; @@ -103,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); @@ -114,88 +157,83 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Permeability, which is HenryPerMeter. All conversions go via this value. /// - public static PermeabilityUnit BaseUnit { get; } + public static PermeabilityUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Permeability quantity. /// - public static PermeabilityUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit HenryPerMeter. /// - public static Permeability Zero { get; } - - /// - public static Permeability AdditiveIdentity => Zero; + public static Permeability Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public PermeabilityUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Permeability.BaseDimensions; - #endregion + #region Explicit implementations - #region Conversion Properties + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); - /// - /// Gets a value of this quantity converted into - /// - public double HenriesPerMeter => As(PermeabilityUnit.HenryPerMeter); + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif #endregion - #region Static Methods + #endregion + + #region Conversion Properties /// - /// Registers the default conversion functions in the given instance. + /// Gets a value of this quantity converted into /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: PermeabilityUnit -> BaseUnit + public QuantityValue HenriesPerMeter => this.As(PermeabilityUnit.HenryPerMeter); - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(PermeabilityUnit.HenryPerMeter, PermeabilityUnit.HenryPerMeter, quantity => quantity); + #endregion - // Register in unit converter: BaseUnit -> PermeabilityUnit - } + #region Static Methods /// /// Get unit abbreviation string. @@ -225,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); } @@ -236,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); } @@ -297,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); } /// @@ -328,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); } /// @@ -353,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")); /// @@ -361,10 +392,10 @@ public static PermeabilityUnit ParseUnit(string str) /// Error parsing string. public static PermeabilityUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -379,10 +410,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -398,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; } @@ -438,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Permeability. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Permeability), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -531,222 +556,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Permeability other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Permeability within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Permeability other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Permeability otherTyped - && (tolerance is Permeability toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Permeability'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Permeability other, Permeability tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Permeability. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(PermeabilityUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(PermeabilityUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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 - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -761,137 +588,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Permeability)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Permeability)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Permeability)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Permeability)) - return this; - else if (conversionType == typeof(PermeabilityUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Permeability.Info; - else if (conversionType == typeof(BaseDimensions)) - return Permeability.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Permeability)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs b/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs index 4383a6ed83..1fc79fbfb6 100644 --- a/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,37 +46,85 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static Permittivity() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class PermittivityInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(-3, -1, 4, 2, 0, 0, 0); - BaseUnit = PermittivityUnit.FaradPerMeter; - Units = Enum.GetValues(typeof(PermittivityUnit)).Cast().ToArray(); - Zero = new Permittivity(0, BaseUnit); - Info = new QuantityInfo("Permittivity", - new UnitInfo[] - { - new UnitInfo(PermittivityUnit.FaradPerMeter, "FaradsPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "Permittivity"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public PermittivityInfo(string name, PermittivityUnit baseUnit, IEnumerable> unitMappings, Permittivity zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public PermittivityInfo(string name, PermittivityUnit baseUnit, IEnumerable> unitMappings, Permittivity zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Permittivity.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Permittivity", typeof(Permittivity).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the Permittivity quantity. + /// + /// A new instance of the class with the default settings. + public static PermittivityInfo CreateDefault() + { + return new PermittivityInfo(nameof(Permittivity), DefaultBaseUnit, GetDefaultMappings(), new Permittivity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Permittivity quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static PermittivityInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new PermittivityInfo(nameof(Permittivity), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Permittivity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^4L^-3M^-1I^2. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-3, -1, 4, 2, 0, 0, 0); + + /// + /// The default base unit of Permittivity is FaradPerMeter. All conversions, as defined in the , go via this value. + /// + public static PermittivityUnit DefaultBaseUnit { get; } = PermittivityUnit.FaradPerMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Permittivity. + public static IEnumerable> GetDefaultMappings() + { + yield return new (PermittivityUnit.FaradPerMeter, "FaradPerMeter", "FaradsPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); + } + } + + static Permittivity() + { + Info = UnitsNetSetup.CreateQuantityInfo(PermittivityInfo.CreateDefault); } /// @@ -89,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; @@ -103,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); @@ -114,88 +157,83 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Permittivity, which is FaradPerMeter. All conversions go via this value. /// - public static PermittivityUnit BaseUnit { get; } + public static PermittivityUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Permittivity quantity. /// - public static PermittivityUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit FaradPerMeter. /// - public static Permittivity Zero { get; } - - /// - public static Permittivity AdditiveIdentity => Zero; + public static Permittivity Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public PermittivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Permittivity.BaseDimensions; - #endregion + #region Explicit implementations - #region Conversion Properties + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); - /// - /// Gets a value of this quantity converted into - /// - public double FaradsPerMeter => As(PermittivityUnit.FaradPerMeter); + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif #endregion - #region Static Methods + #endregion + + #region Conversion Properties /// - /// Registers the default conversion functions in the given instance. + /// Gets a value of this quantity converted into /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: PermittivityUnit -> BaseUnit + public QuantityValue FaradsPerMeter => this.As(PermittivityUnit.FaradPerMeter); - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(PermittivityUnit.FaradPerMeter, PermittivityUnit.FaradPerMeter, quantity => quantity); + #endregion - // Register in unit converter: BaseUnit -> PermittivityUnit - } + #region Static Methods /// /// Get unit abbreviation string. @@ -225,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); } @@ -236,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); } @@ -297,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); } /// @@ -328,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); } /// @@ -353,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")); /// @@ -361,10 +392,10 @@ public static PermittivityUnit ParseUnit(string str) /// Error parsing string. public static PermittivityUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -379,10 +410,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -398,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; } @@ -438,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Permittivity. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Permittivity), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -531,222 +556,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Permittivity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Permittivity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Permittivity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Permittivity otherTyped - && (tolerance is Permittivity toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Permittivity'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Permittivity other, Permittivity tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Permittivity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(PermittivityUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(PermittivityUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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 - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -761,137 +588,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Permittivity)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Permittivity)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Permittivity)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Permittivity)) - return this; - else if (conversionType == typeof(PermittivityUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Permittivity.Info; - else if (conversionType == typeof(BaseDimensions)) - return Permittivity.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Permittivity)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/PorousMediumPermeability.g.cs b/UnitsNet/GeneratedCode/Quantities/PorousMediumPermeability.g.cs index f17e84f4e8..ab92b767d8 100644 --- a/UnitsNet/GeneratedCode/Quantities/PorousMediumPermeability.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PorousMediumPermeability.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,41 +46,97 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static PorousMediumPermeability() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class PorousMediumPermeabilityInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); - BaseUnit = PorousMediumPermeabilityUnit.SquareMeter; - Units = Enum.GetValues(typeof(PorousMediumPermeabilityUnit)).Cast().ToArray(); - Zero = new PorousMediumPermeability(0, BaseUnit); - Info = new QuantityInfo("PorousMediumPermeability", - new UnitInfo[] - { - new UnitInfo(PorousMediumPermeabilityUnit.Darcy, "Darcys", BaseUnits.Undefined, "PorousMediumPermeability"), - new UnitInfo(PorousMediumPermeabilityUnit.Microdarcy, "Microdarcys", BaseUnits.Undefined, "PorousMediumPermeability"), - new UnitInfo(PorousMediumPermeabilityUnit.Millidarcy, "Millidarcys", BaseUnits.Undefined, "PorousMediumPermeability"), - new UnitInfo(PorousMediumPermeabilityUnit.SquareCentimeter, "SquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter), "PorousMediumPermeability"), - new UnitInfo(PorousMediumPermeabilityUnit.SquareMeter, "SquareMeters", new BaseUnits(length: LengthUnit.Meter), "PorousMediumPermeability"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public PorousMediumPermeabilityInfo(string name, PorousMediumPermeabilityUnit baseUnit, IEnumerable> unitMappings, PorousMediumPermeability zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public PorousMediumPermeabilityInfo(string name, PorousMediumPermeabilityUnit baseUnit, IEnumerable> unitMappings, PorousMediumPermeability zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, PorousMediumPermeability.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.PorousMediumPermeability", typeof(PorousMediumPermeability).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the PorousMediumPermeability quantity. + /// + /// A new instance of the class with the default settings. + public static PorousMediumPermeabilityInfo CreateDefault() + { + return new PorousMediumPermeabilityInfo(nameof(PorousMediumPermeability), DefaultBaseUnit, GetDefaultMappings(), new PorousMediumPermeability(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the PorousMediumPermeability quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static PorousMediumPermeabilityInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new PorousMediumPermeabilityInfo(nameof(PorousMediumPermeability), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new PorousMediumPermeability(0, DefaultBaseUnit), DefaultBaseDimensions); + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// The for is L^2. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); + + /// + /// The default base unit of PorousMediumPermeability is SquareMeter. All conversions, as defined in the , go via this value. + /// + public static PorousMediumPermeabilityUnit DefaultBaseUnit { get; } = PorousMediumPermeabilityUnit.SquareMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for PorousMediumPermeability. + public static IEnumerable> GetDefaultMappings() + { + 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 = UnitsNetSetup.CreateQuantityInfo(PorousMediumPermeabilityInfo.CreateDefault); } /// @@ -93,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; @@ -107,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); @@ -118,117 +169,104 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of PorousMediumPermeability, which is SquareMeter. All conversions go via this value. /// - public static PorousMediumPermeabilityUnit BaseUnit { get; } + public static PorousMediumPermeabilityUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the PorousMediumPermeability quantity. /// - public static PorousMediumPermeabilityUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeter. /// - public static PorousMediumPermeability Zero { get; } - - /// - public static PorousMediumPermeability AdditiveIdentity => Zero; + public static PorousMediumPermeability Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public PorousMediumPermeabilityUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => PorousMediumPermeability.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -257,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); } @@ -265,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); } @@ -273,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); } @@ -281,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); } @@ -289,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); } @@ -300,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); } @@ -361,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); } /// @@ -392,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); } /// @@ -417,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")); /// @@ -425,10 +456,10 @@ public static PorousMediumPermeabilityUnit ParseUnit(string str) /// Error parsing string. public static PorousMediumPermeabilityUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -443,10 +474,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -462,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; } @@ -502,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current PorousMediumPermeability. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(PorousMediumPermeability), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -595,230 +620,24 @@ public int CompareTo(object? obj) /// public int CompareTo(PorousMediumPermeability other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another PorousMediumPermeability within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(PorousMediumPermeability other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is PorousMediumPermeability otherTyped - && (tolerance is PorousMediumPermeability toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'PorousMediumPermeability'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(PorousMediumPermeability other, PorousMediumPermeability tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current PorousMediumPermeability. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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)); + #region Conversion Methods (explicit implementations for netstandard2.0) - 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 PorousMediumPermeabilityUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PorousMediumPermeabilityUnit)} 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(PorousMediumPermeabilityUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(PorousMediumPermeabilityUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -833,137 +652,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(PorousMediumPermeability)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(PorousMediumPermeability)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(PorousMediumPermeability)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(PorousMediumPermeability)) - return this; - else if (conversionType == typeof(PorousMediumPermeabilityUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return PorousMediumPermeability.Info; - else if (conversionType == typeof(BaseDimensions)) - return PorousMediumPermeability.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(PorousMediumPermeability)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Power.g.cs b/UnitsNet/GeneratedCode/Quantities/Power.g.cs index 6c8b2cb6a7..dd52fb8d52 100644 --- a/UnitsNet/GeneratedCode/Quantities/Power.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Power.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -64,63 +59,163 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class PowerInfo: QuantityInfo + { + /// + public PowerInfo(string name, PowerUnit baseUnit, IEnumerable> unitMappings, Power zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public PowerInfo(string name, PowerUnit baseUnit, IEnumerable> unitMappings, Power zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Power.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Power", typeof(Power).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Power quantity. + /// + /// A new instance of the class with the default settings. + public static PowerInfo CreateDefault() + { + return new PowerInfo(nameof(Power), DefaultBaseUnit, GetDefaultMappings(), new Power(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Power quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static PowerInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new PowerInfo(nameof(Power), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Power(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-3L^2M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); + + /// + /// The default base unit of Power is Watt. All conversions, as defined in the , go via this value. + /// + public static PowerUnit DefaultBaseUnit { get; } = PowerUnit.Watt; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Power. + public static IEnumerable> GetDefaultMappings() + { + 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() { - BaseDimensions = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); - BaseUnit = PowerUnit.Watt; - Units = Enum.GetValues(typeof(PowerUnit)).Cast().ToArray(); - Zero = new Power(0, BaseUnit); - Info = new QuantityInfo("Power", - new UnitInfo[] - { - new UnitInfo(PowerUnit.BoilerHorsepower, "BoilerHorsepower", BaseUnits.Undefined, "Power"), - new UnitInfo(PowerUnit.BritishThermalUnitPerHour, "BritishThermalUnitsPerHour", BaseUnits.Undefined, "Power"), - new UnitInfo(PowerUnit.Decawatt, "Decawatts", BaseUnits.Undefined, "Power"), - new UnitInfo(PowerUnit.Deciwatt, "Deciwatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Hectogram, time: DurationUnit.Second), "Power"), - new UnitInfo(PowerUnit.ElectricalHorsepower, "ElectricalHorsepower", BaseUnits.Undefined, "Power"), - new UnitInfo(PowerUnit.Femtowatt, "Femtowatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Picogram, time: DurationUnit.Second), "Power"), - new UnitInfo(PowerUnit.GigajoulePerHour, "GigajoulesPerHour", BaseUnits.Undefined, "Power"), - new UnitInfo(PowerUnit.Gigawatt, "Gigawatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond), "Power"), - new UnitInfo(PowerUnit.HydraulicHorsepower, "HydraulicHorsepower", BaseUnits.Undefined, "Power"), - new UnitInfo(PowerUnit.JoulePerHour, "JoulesPerHour", BaseUnits.Undefined, "Power"), - new UnitInfo(PowerUnit.KilobritishThermalUnitPerHour, "KilobritishThermalUnitsPerHour", BaseUnits.Undefined, "Power"), - new UnitInfo(PowerUnit.KilojoulePerHour, "KilojoulesPerHour", BaseUnits.Undefined, "Power"), - new UnitInfo(PowerUnit.Kilowatt, "Kilowatts", BaseUnits.Undefined, "Power"), - new UnitInfo(PowerUnit.MechanicalHorsepower, "MechanicalHorsepower", BaseUnits.Undefined, "Power"), - new UnitInfo(PowerUnit.MegabritishThermalUnitPerHour, "MegabritishThermalUnitsPerHour", BaseUnits.Undefined, "Power"), - new UnitInfo(PowerUnit.MegajoulePerHour, "MegajoulesPerHour", BaseUnits.Undefined, "Power"), - new UnitInfo(PowerUnit.Megawatt, "Megawatts", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Power"), - new UnitInfo(PowerUnit.MetricHorsepower, "MetricHorsepower", BaseUnits.Undefined, "Power"), - new UnitInfo(PowerUnit.Microwatt, "Microwatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second), "Power"), - new UnitInfo(PowerUnit.MillijoulePerHour, "MillijoulesPerHour", BaseUnits.Undefined, "Power"), - new UnitInfo(PowerUnit.Milliwatt, "Milliwatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second), "Power"), - new UnitInfo(PowerUnit.Nanowatt, "Nanowatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second), "Power"), - new UnitInfo(PowerUnit.Petawatt, "Petawatts", BaseUnits.Undefined, "Power"), - new UnitInfo(PowerUnit.Picowatt, "Picowatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Nanogram, time: DurationUnit.Second), "Power"), - new UnitInfo(PowerUnit.Terawatt, "Terawatts", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Power"), - new UnitInfo(PowerUnit.TonOfRefrigeration, "TonsOfRefrigeration", BaseUnits.Undefined, "Power"), - new UnitInfo(PowerUnit.Watt, "Watts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Power"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(PowerInfo.CreateDefault); } /// @@ -128,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; @@ -142,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); @@ -153,271 +248,214 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Power, which is Watt. All conversions go via this value. /// - public static PowerUnit BaseUnit { get; } + public static PowerUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Power quantity. /// - public static PowerUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Watt. /// - public static Power Zero { get; } - - /// - public static Power AdditiveIdentity => Zero; + public static Power Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public PowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Power.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -446,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); } @@ -454,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); } @@ -462,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); } @@ -470,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); } @@ -478,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); } @@ -486,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); } @@ -494,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); } @@ -502,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); } @@ -510,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); } @@ -518,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); } @@ -526,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); } @@ -534,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); } @@ -542,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); } @@ -550,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); } @@ -558,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); } @@ -566,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); } @@ -574,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); } @@ -582,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); } @@ -590,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); } @@ -598,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); } @@ -606,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); } @@ -614,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); } @@ -622,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); } @@ -630,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); } @@ -638,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); } @@ -646,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); } @@ -654,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); } @@ -665,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); } @@ -726,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); } /// @@ -757,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); } /// @@ -782,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")); /// @@ -790,10 +821,10 @@ public static PowerUnit ParseUnit(string str) /// Error parsing string. public static PowerUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -808,10 +839,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -827,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; } @@ -955,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Power. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Power), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -1048,274 +1073,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Power other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Power within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Power other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Power otherTyped - && (tolerance is Power toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Power'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Power other, Power tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Power. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(PowerUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - /// 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 NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } + IQuantity IQuantity.ToUnit(PowerUnit unit) => this.ToUnit(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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(PowerUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1330,137 +1105,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Power)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Power)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Power)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Power)) - return this; - else if (conversionType == typeof(PowerUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Power.Info; - else if (conversionType == typeof(BaseDimensions)) - return Power.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Power)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/PowerDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/PowerDensity.g.cs index e89c8e059c..e1252a7765 100644 --- a/UnitsNet/GeneratedCode/Quantities/PowerDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PowerDensity.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -48,80 +43,214 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class PowerDensityInfo: QuantityInfo + { + /// + public PowerDensityInfo(string name, PowerDensityUnit baseUnit, IEnumerable> unitMappings, PowerDensity zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public PowerDensityInfo(string name, PowerDensityUnit baseUnit, IEnumerable> unitMappings, PowerDensity zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, PowerDensity.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.PowerDensity", typeof(PowerDensity).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the PowerDensity quantity. + /// + /// A new instance of the class with the default settings. + public static PowerDensityInfo CreateDefault() + { + return new PowerDensityInfo(nameof(PowerDensity), DefaultBaseUnit, GetDefaultMappings(), new PowerDensity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the PowerDensity quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static PowerDensityInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new PowerDensityInfo(nameof(PowerDensity), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new PowerDensity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-3L^-1M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-1, 1, -3, 0, 0, 0, 0); + + /// + /// The default base unit of PowerDensity is WattPerCubicMeter. All conversions, as defined in the , go via this value. + /// + public static PowerDensityUnit DefaultBaseUnit { get; } = PowerDensityUnit.WattPerCubicMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for PowerDensity. + public static IEnumerable> GetDefaultMappings() + { + 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, + new QuantityValue(1, 1000) + ); + } + } + static PowerDensity() { - BaseDimensions = new BaseDimensions(-1, 1, -3, 0, 0, 0, 0); - BaseUnit = PowerDensityUnit.WattPerCubicMeter; - Units = Enum.GetValues(typeof(PowerDensityUnit)).Cast().ToArray(); - Zero = new PowerDensity(0, BaseUnit); - Info = new QuantityInfo("PowerDensity", - new UnitInfo[] - { - new UnitInfo(PowerDensityUnit.DecawattPerCubicFoot, "DecawattsPerCubicFoot", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.DecawattPerCubicInch, "DecawattsPerCubicInch", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.DecawattPerCubicMeter, "DecawattsPerCubicMeter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "PowerDensity"), - new UnitInfo(PowerDensityUnit.DecawattPerLiter, "DecawattsPerLiter", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.DeciwattPerCubicFoot, "DeciwattsPerCubicFoot", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.DeciwattPerCubicInch, "DeciwattsPerCubicInch", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.DeciwattPerCubicMeter, "DeciwattsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Hectogram, time: DurationUnit.Second), "PowerDensity"), - new UnitInfo(PowerDensityUnit.DeciwattPerLiter, "DeciwattsPerLiter", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.GigawattPerCubicFoot, "GigawattsPerCubicFoot", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.GigawattPerCubicInch, "GigawattsPerCubicInch", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.GigawattPerCubicMeter, "GigawattsPerCubicMeter", new BaseUnits(length: LengthUnit.Nanometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "PowerDensity"), - new UnitInfo(PowerDensityUnit.GigawattPerLiter, "GigawattsPerLiter", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.KilowattPerCubicFoot, "KilowattsPerCubicFoot", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.KilowattPerCubicInch, "KilowattsPerCubicInch", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.KilowattPerCubicMeter, "KilowattsPerCubicMeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "PowerDensity"), - new UnitInfo(PowerDensityUnit.KilowattPerLiter, "KilowattsPerLiter", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.MegawattPerCubicFoot, "MegawattsPerCubicFoot", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.MegawattPerCubicInch, "MegawattsPerCubicInch", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.MegawattPerCubicMeter, "MegawattsPerCubicMeter", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "PowerDensity"), - new UnitInfo(PowerDensityUnit.MegawattPerLiter, "MegawattsPerLiter", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.MicrowattPerCubicFoot, "MicrowattsPerCubicFoot", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.MicrowattPerCubicInch, "MicrowattsPerCubicInch", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.MicrowattPerCubicMeter, "MicrowattsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second), "PowerDensity"), - new UnitInfo(PowerDensityUnit.MicrowattPerLiter, "MicrowattsPerLiter", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.MilliwattPerCubicFoot, "MilliwattsPerCubicFoot", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.MilliwattPerCubicInch, "MilliwattsPerCubicInch", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.MilliwattPerCubicMeter, "MilliwattsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second), "PowerDensity"), - new UnitInfo(PowerDensityUnit.MilliwattPerLiter, "MilliwattsPerLiter", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.NanowattPerCubicFoot, "NanowattsPerCubicFoot", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.NanowattPerCubicInch, "NanowattsPerCubicInch", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.NanowattPerCubicMeter, "NanowattsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second), "PowerDensity"), - new UnitInfo(PowerDensityUnit.NanowattPerLiter, "NanowattsPerLiter", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.PicowattPerCubicFoot, "PicowattsPerCubicFoot", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.PicowattPerCubicInch, "PicowattsPerCubicInch", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.PicowattPerCubicMeter, "PicowattsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Nanogram, time: DurationUnit.Second), "PowerDensity"), - new UnitInfo(PowerDensityUnit.PicowattPerLiter, "PicowattsPerLiter", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.TerawattPerCubicFoot, "TerawattsPerCubicFoot", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.TerawattPerCubicInch, "TerawattsPerCubicInch", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.TerawattPerCubicMeter, "TerawattsPerCubicMeter", new BaseUnits(length: LengthUnit.Picometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "PowerDensity"), - new UnitInfo(PowerDensityUnit.TerawattPerLiter, "TerawattsPerLiter", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.WattPerCubicFoot, "WattsPerCubicFoot", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.WattPerCubicInch, "WattsPerCubicInch", BaseUnits.Undefined, "PowerDensity"), - new UnitInfo(PowerDensityUnit.WattPerCubicMeter, "WattsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "PowerDensity"), - new UnitInfo(PowerDensityUnit.WattPerLiter, "WattsPerLiter", BaseUnits.Undefined, "PowerDensity"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(PowerDensityInfo.CreateDefault); } /// @@ -129,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; @@ -143,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); @@ -154,390 +283,299 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of PowerDensity, which is WattPerCubicMeter. All conversions go via this value. /// - public static PowerDensityUnit BaseUnit { get; } + public static PowerDensityUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the PowerDensity quantity. /// - public static PowerDensityUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit WattPerCubicMeter. /// - public static PowerDensity Zero { get; } - - /// - public static PowerDensity AdditiveIdentity => Zero; + public static PowerDensity Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public PowerDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => PowerDensity.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -566,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); } @@ -574,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); } @@ -582,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); } @@ -590,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); } @@ -598,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); } @@ -606,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); } @@ -614,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); } @@ -622,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); } @@ -630,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); } @@ -638,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); } @@ -646,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); } @@ -654,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); } @@ -662,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); } @@ -670,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); } @@ -678,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); } @@ -686,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); } @@ -694,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); } @@ -702,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); } @@ -710,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); } @@ -718,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); } @@ -726,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); } @@ -734,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); } @@ -742,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); } @@ -750,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); } @@ -758,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); } @@ -766,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); } @@ -774,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); } @@ -782,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); } @@ -790,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); } @@ -798,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); } @@ -806,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); } @@ -814,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); } @@ -822,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); } @@ -830,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); } @@ -838,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); } @@ -846,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); } @@ -854,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); } @@ -862,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); } @@ -870,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); } @@ -878,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); } @@ -886,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); } @@ -894,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); } @@ -902,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); } @@ -910,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); } @@ -921,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); } @@ -982,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); } /// @@ -1013,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); } /// @@ -1038,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")); /// @@ -1046,10 +1077,10 @@ public static PowerDensityUnit ParseUnit(string str) /// Error parsing string. public static PowerDensityUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -1064,10 +1095,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -1083,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; } @@ -1123,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current PowerDensity. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(PowerDensity), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -1216,308 +1241,24 @@ public int CompareTo(object? obj) /// public int CompareTo(PowerDensity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another PowerDensity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(PowerDensity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is PowerDensity otherTyped - && (tolerance is PowerDensity toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'PowerDensity'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(PowerDensity other, PowerDensity tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current PowerDensity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(PowerDensityUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - /// 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 NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } + IQuantity IQuantity.ToUnit(PowerDensityUnit unit) => this.ToUnit(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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(PowerDensityUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1532,137 +1273,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(PowerDensity)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(PowerDensity)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(PowerDensity)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(PowerDensity)) - return this; - else if (conversionType == typeof(PowerDensityUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return PowerDensity.Info; - else if (conversionType == typeof(BaseDimensions)) - return PowerDensity.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(PowerDensity)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs b/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs index 1b98d9cf78..3aec0043f8 100644 --- a/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,47 +33,99 @@ 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 : - IArithmeticQuantity, + ILogarithmicQuantity, #if NET7_0_OR_GREATER IComparisonOperators, IParsable, #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static PowerRatio() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class PowerRatioInfo: QuantityInfo { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = PowerRatioUnit.DecibelWatt; - Units = Enum.GetValues(typeof(PowerRatioUnit)).Cast().ToArray(); - Zero = new PowerRatio(0, BaseUnit); - Info = new QuantityInfo("PowerRatio", - new UnitInfo[] - { - new UnitInfo(PowerRatioUnit.DecibelMilliwatt, "DecibelMilliwatts", BaseUnits.Undefined, "PowerRatio"), - new UnitInfo(PowerRatioUnit.DecibelWatt, "DecibelWatts", BaseUnits.Undefined, "PowerRatio"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public PowerRatioInfo(string name, PowerRatioUnit baseUnit, IEnumerable> unitMappings, PowerRatio zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public PowerRatioInfo(string name, PowerRatioUnit baseUnit, IEnumerable> unitMappings, PowerRatio zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, PowerRatio.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.PowerRatio", typeof(PowerRatio).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the PowerRatio quantity. + /// + /// A new instance of the class with the default settings. + public static PowerRatioInfo CreateDefault() + { + return new PowerRatioInfo(nameof(PowerRatio), DefaultBaseUnit, GetDefaultMappings(), new PowerRatio(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the PowerRatio quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static PowerRatioInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new PowerRatioInfo(nameof(PowerRatio), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new PowerRatio(0, DefaultBaseUnit), DefaultBaseDimensions); + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// The for is . + /// + public static BaseDimensions DefaultBaseDimensions { get; } = BaseDimensions.Dimensionless; + + /// + /// The default base unit of PowerRatio is DecibelWatt. All conversions, as defined in the , go via this value. + /// + public static PowerRatioUnit DefaultBaseUnit { get; } = PowerRatioUnit.DecibelWatt; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for PowerRatio. + public static IEnumerable> GetDefaultMappings() + { + 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 = UnitsNetSetup.CreateQuantityInfo(PowerRatioInfo.CreateDefault); } /// @@ -87,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; @@ -98,96 +144,96 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of PowerRatio, which is DecibelWatt. All conversions go via this value. /// - public static PowerRatioUnit BaseUnit { get; } + public static PowerRatioUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the PowerRatio quantity. /// - public static PowerRatioUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit DecibelWatt. /// - public static PowerRatio Zero { get; } + public static PowerRatio Zero => Info.Zero; - /// - public static PowerRatio AdditiveIdentity => Zero; + /// + public static QuantityValue LogarithmicScalingFactor {get;} = 10; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public PowerRatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => PowerRatio.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + +#if NETSTANDARD2_0 + QuantityValue ILogarithmicQuantity.LogarithmicScalingFactor => LogarithmicScalingFactor; +#endif + + #endregion + #endregion #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. /// @@ -216,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); } @@ -224,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); } @@ -235,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); } @@ -296,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); } /// @@ -327,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); } /// @@ -352,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")); /// @@ -360,10 +399,10 @@ public static PowerRatioUnit ParseUnit(string str) /// Error parsing string. public static PowerRatioUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -378,10 +417,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -389,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 @@ -445,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current PowerRatio. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(PowerRatio), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -538,224 +579,24 @@ public int CompareTo(object? obj) /// public int CompareTo(PowerRatio other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another PowerRatio within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(PowerRatio other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is PowerRatio otherTyped - && (tolerance is PowerRatio toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'PowerRatio'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(PowerRatio other, PowerRatio tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current PowerRatio. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(PowerRatioUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(PowerRatioUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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), - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -770,137 +611,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(PowerRatio)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(PowerRatio)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(PowerRatio)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(PowerRatio)) - return this; - else if (conversionType == typeof(PowerRatioUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return PowerRatio.Info; - else if (conversionType == typeof(BaseDimensions)) - return PowerRatio.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(PowerRatio)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs b/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs index 94f6297f27..f7534e67b8 100644 --- a/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -60,83 +55,223 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class PressureInfo: QuantityInfo + { + /// + public PressureInfo(string name, PressureUnit baseUnit, IEnumerable> unitMappings, Pressure zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public PressureInfo(string name, PressureUnit baseUnit, IEnumerable> unitMappings, Pressure zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Pressure.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Pressure", typeof(Pressure).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Pressure quantity. + /// + /// A new instance of the class with the default settings. + public static PressureInfo CreateDefault() + { + return new PressureInfo(nameof(Pressure), DefaultBaseUnit, GetDefaultMappings(), new Pressure(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Pressure quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static PressureInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new PressureInfo(nameof(Pressure), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Pressure(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-2L^-1M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-1, 1, -2, 0, 0, 0, 0); + + /// + /// The default base unit of Pressure is Pascal. All conversions, as defined in the , go via this value. + /// + public static PressureUnit DefaultBaseUnit { get; } = PressureUnit.Pascal; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Pressure. + public static IEnumerable> GetDefaultMappings() + { + 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.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, + 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() { - BaseDimensions = new BaseDimensions(-1, 1, -2, 0, 0, 0, 0); - BaseUnit = PressureUnit.Pascal; - Units = Enum.GetValues(typeof(PressureUnit)).Cast().ToArray(); - Zero = new Pressure(0, BaseUnit); - Info = new QuantityInfo("Pressure", - new UnitInfo[] - { - new UnitInfo(PressureUnit.Atmosphere, "Atmospheres", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.Bar, "Bars", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.Centibar, "Centibars", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.CentimeterOfWaterColumn, "CentimetersOfWaterColumn", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.Decapascal, "Decapascals", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Pressure"), - new UnitInfo(PressureUnit.Decibar, "Decibars", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.DynePerSquareCentimeter, "DynesPerSquareCentimeter", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.FootOfHead, "FeetOfHead", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.Gigapascal, "Gigapascals", new BaseUnits(length: LengthUnit.Nanometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Pressure"), - new UnitInfo(PressureUnit.Hectopascal, "Hectopascals", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Pressure"), - new UnitInfo(PressureUnit.InchOfMercury, "InchesOfMercury", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.InchOfWaterColumn, "InchesOfWaterColumn", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.Kilobar, "Kilobars", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.KilogramForcePerSquareCentimeter, "KilogramsForcePerSquareCentimeter", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.KilogramForcePerSquareMeter, "KilogramsForcePerSquareMeter", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.KilogramForcePerSquareMillimeter, "KilogramsForcePerSquareMillimeter", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.KilonewtonPerSquareCentimeter, "KilonewtonsPerSquareCentimeter", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.KilonewtonPerSquareMeter, "KilonewtonsPerSquareMeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Pressure"), - new UnitInfo(PressureUnit.KilonewtonPerSquareMillimeter, "KilonewtonsPerSquareMillimeter", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.Kilopascal, "Kilopascals", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Pressure"), - new UnitInfo(PressureUnit.KilopoundForcePerSquareFoot, "KilopoundsForcePerSquareFoot", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.KilopoundForcePerSquareInch, "KilopoundsForcePerSquareInch", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.KilopoundForcePerSquareMil, "KilopoundsForcePerSquareMil", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.Megabar, "Megabars", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.MeganewtonPerSquareMeter, "MeganewtonsPerSquareMeter", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Pressure"), - new UnitInfo(PressureUnit.Megapascal, "Megapascals", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Pressure"), - new UnitInfo(PressureUnit.MeterOfHead, "MetersOfHead", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.MeterOfWaterColumn, "MetersOfWaterColumn", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.Microbar, "Microbars", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.Micropascal, "Micropascals", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second), "Pressure"), - new UnitInfo(PressureUnit.Millibar, "Millibars", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.MillimeterOfMercury, "MillimetersOfMercury", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.MillimeterOfWaterColumn, "MillimetersOfWaterColumn", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.Millipascal, "Millipascals", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second), "Pressure"), - new UnitInfo(PressureUnit.NewtonPerSquareCentimeter, "NewtonsPerSquareCentimeter", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.NewtonPerSquareMeter, "NewtonsPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Pressure"), - new UnitInfo(PressureUnit.NewtonPerSquareMillimeter, "NewtonsPerSquareMillimeter", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.Pascal, "Pascals", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Pressure"), - new UnitInfo(PressureUnit.PoundForcePerSquareFoot, "PoundsForcePerSquareFoot", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.PoundForcePerSquareInch, "PoundsForcePerSquareInch", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.PoundForcePerSquareMil, "PoundsForcePerSquareMil", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.PoundPerInchSecondSquared, "PoundsPerInchSecondSquared", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.TechnicalAtmosphere, "TechnicalAtmospheres", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.TonneForcePerSquareCentimeter, "TonnesForcePerSquareCentimeter", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.TonneForcePerSquareMeter, "TonnesForcePerSquareMeter", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.TonneForcePerSquareMillimeter, "TonnesForcePerSquareMillimeter", BaseUnits.Undefined, "Pressure"), - new UnitInfo(PressureUnit.Torr, "Torrs", BaseUnits.Undefined, "Pressure"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(PressureInfo.CreateDefault); } /// @@ -144,7 +279,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; @@ -158,7 +293,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); @@ -169,411 +304,314 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Pressure, which is Pascal. All conversions go via this value. /// - public static PressureUnit BaseUnit { get; } + public static PressureUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Pressure quantity. /// - public static PressureUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Pascal. /// - public static Pressure Zero { get; } - - /// - public static Pressure AdditiveIdentity => Zero; + public static Pressure Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public PressureUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Pressure.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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 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.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.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. /// @@ -602,7 +640,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); } @@ -610,7 +648,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); } @@ -618,7 +656,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); } @@ -626,7 +664,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); } @@ -634,7 +672,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); } @@ -642,7 +680,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); } @@ -650,7 +688,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); } @@ -658,7 +696,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); } @@ -666,7 +704,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); } @@ -674,7 +712,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); } @@ -682,7 +720,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); } @@ -690,7 +728,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); } @@ -698,7 +736,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); } @@ -706,7 +744,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); } @@ -714,7 +752,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); } @@ -722,7 +760,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); } @@ -730,7 +768,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); } @@ -738,7 +776,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); } @@ -746,7 +784,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); } @@ -754,7 +792,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); } @@ -762,7 +800,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); } @@ -770,7 +808,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); } @@ -778,7 +816,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); } @@ -786,7 +824,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); } @@ -794,7 +832,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); } @@ -802,7 +840,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); } @@ -810,7 +848,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); } @@ -818,7 +856,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); } @@ -826,7 +864,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); } @@ -834,7 +872,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); } @@ -842,7 +880,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); } @@ -850,7 +888,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); } @@ -858,7 +896,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); } @@ -866,7 +904,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); } @@ -874,7 +912,7 @@ public static Pressure FromMillipascals(double value) /// /// Creates a from . /// - public static Pressure FromNewtonsPerSquareCentimeter(double value) + public static Pressure FromNewtonsPerSquareCentimeter(QuantityValue value) { return new Pressure(value, PressureUnit.NewtonPerSquareCentimeter); } @@ -882,7 +920,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); } @@ -890,7 +928,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); } @@ -898,7 +936,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); } @@ -906,7 +944,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); } @@ -914,7 +952,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); } @@ -922,7 +960,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); } @@ -930,7 +968,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); } @@ -938,7 +976,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); } @@ -946,7 +984,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); } @@ -954,7 +992,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); } @@ -962,7 +1000,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); } @@ -970,7 +1008,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); } @@ -981,7 +1019,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); } @@ -1042,10 +1080,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); } /// @@ -1073,11 +1108,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); } /// @@ -1098,7 +1129,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")); /// @@ -1106,10 +1137,10 @@ public static PressureUnit ParseUnit(string str) /// Error parsing string. public static PressureUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -1124,10 +1155,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -1143,35 +1174,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; } @@ -1247,88 +1278,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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Pressure. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Pressure), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -1340,314 +1365,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Pressure other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Pressure within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Pressure other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Pressure otherTyped - && (tolerance is Pressure toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Pressure'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Pressure other, Pressure tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Pressure. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(PressureUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - /// 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 NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } + IQuantity IQuantity.ToUnit(PressureUnit unit) => this.ToUnit(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.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.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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(PressureUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1662,137 +1397,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Pressure)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Pressure)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Pressure)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Pressure)) - return this; - else if (conversionType == typeof(PressureUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Pressure.Info; - else if (conversionType == typeof(BaseDimensions)) - return Pressure.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Pressure)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs index c8021d851b..8906d79e93 100644 --- a/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -51,54 +46,136 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class PressureChangeRateInfo: QuantityInfo + { + /// + public PressureChangeRateInfo(string name, PressureChangeRateUnit baseUnit, IEnumerable> unitMappings, PressureChangeRate zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public PressureChangeRateInfo(string name, PressureChangeRateUnit baseUnit, IEnumerable> unitMappings, PressureChangeRate zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, PressureChangeRate.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.PressureChangeRate", typeof(PressureChangeRate).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the PressureChangeRate quantity. + /// + /// A new instance of the class with the default settings. + public static PressureChangeRateInfo CreateDefault() + { + return new PressureChangeRateInfo(nameof(PressureChangeRate), DefaultBaseUnit, GetDefaultMappings(), new PressureChangeRate(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the PressureChangeRate quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static PressureChangeRateInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new PressureChangeRateInfo(nameof(PressureChangeRate), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new PressureChangeRate(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-3L^-1M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-1, 1, -3, 0, 0, 0, 0); + + /// + /// The default base unit of PressureChangeRate is PascalPerSecond. All conversions, as defined in the , go via this value. + /// + public static PressureChangeRateUnit DefaultBaseUnit { get; } = PressureChangeRateUnit.PascalPerSecond; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for PressureChangeRate. + public static IEnumerable> GetDefaultMappings() + { + 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), + 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() { - BaseDimensions = new BaseDimensions(-1, 1, -3, 0, 0, 0, 0); - BaseUnit = PressureChangeRateUnit.PascalPerSecond; - Units = Enum.GetValues(typeof(PressureChangeRateUnit)).Cast().ToArray(); - Zero = new PressureChangeRate(0, BaseUnit); - Info = new QuantityInfo("PressureChangeRate", - new UnitInfo[] - { - new UnitInfo(PressureChangeRateUnit.AtmospherePerSecond, "AtmospheresPerSecond", BaseUnits.Undefined, "PressureChangeRate"), - new UnitInfo(PressureChangeRateUnit.BarPerMinute, "BarsPerMinute", BaseUnits.Undefined, "PressureChangeRate"), - new UnitInfo(PressureChangeRateUnit.BarPerSecond, "BarsPerSecond", BaseUnits.Undefined, "PressureChangeRate"), - new UnitInfo(PressureChangeRateUnit.KilopascalPerMinute, "KilopascalsPerMinute", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Minute), "PressureChangeRate"), - new UnitInfo(PressureChangeRateUnit.KilopascalPerSecond, "KilopascalsPerSecond", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "PressureChangeRate"), - new UnitInfo(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, "KilopoundsForcePerSquareInchPerMinute", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Kilopound, time: DurationUnit.Minute), "PressureChangeRate"), - new UnitInfo(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, "KilopoundsForcePerSquareInchPerSecond", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Kilopound, time: DurationUnit.Second), "PressureChangeRate"), - new UnitInfo(PressureChangeRateUnit.MegapascalPerMinute, "MegapascalsPerMinute", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Minute), "PressureChangeRate"), - new UnitInfo(PressureChangeRateUnit.MegapascalPerSecond, "MegapascalsPerSecond", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "PressureChangeRate"), - new UnitInfo(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, "MegapoundsForcePerSquareInchPerMinute", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Megapound, time: DurationUnit.Minute), "PressureChangeRate"), - new UnitInfo(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, "MegapoundsForcePerSquareInchPerSecond", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Megapound, time: DurationUnit.Second), "PressureChangeRate"), - new UnitInfo(PressureChangeRateUnit.MillibarPerMinute, "MillibarsPerMinute", BaseUnits.Undefined, "PressureChangeRate"), - new UnitInfo(PressureChangeRateUnit.MillibarPerSecond, "MillibarsPerSecond", BaseUnits.Undefined, "PressureChangeRate"), - new UnitInfo(PressureChangeRateUnit.MillimeterOfMercuryPerSecond, "MillimetersOfMercuryPerSecond", BaseUnits.Undefined, "PressureChangeRate"), - new UnitInfo(PressureChangeRateUnit.PascalPerMinute, "PascalsPerMinute", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Minute), "PressureChangeRate"), - new UnitInfo(PressureChangeRateUnit.PascalPerSecond, "PascalsPerSecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "PressureChangeRate"), - new UnitInfo(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, "PoundsForcePerSquareInchPerMinute", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Pound, time: DurationUnit.Minute), "PressureChangeRate"), - new UnitInfo(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, "PoundsForcePerSquareInchPerSecond", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Pound, time: DurationUnit.Second), "PressureChangeRate"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(PressureChangeRateInfo.CreateDefault); } /// @@ -106,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; @@ -120,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); @@ -131,208 +208,169 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of PressureChangeRate, which is PascalPerSecond. All conversions go via this value. /// - public static PressureChangeRateUnit BaseUnit { get; } + public static PressureChangeRateUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the PressureChangeRate quantity. /// - public static PressureChangeRateUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit PascalPerSecond. /// - public static PressureChangeRate Zero { get; } - - /// - public static PressureChangeRate AdditiveIdentity => Zero; + public static PressureChangeRate Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public PressureChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => PressureChangeRate.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -361,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); } @@ -369,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); } @@ -377,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); } @@ -385,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); } @@ -393,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); } @@ -401,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); } @@ -409,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); } @@ -417,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); } @@ -425,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); } @@ -433,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); } @@ -441,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); } @@ -449,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); } @@ -457,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); } @@ -465,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); } @@ -473,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); } @@ -481,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); } @@ -489,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); } @@ -497,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); } @@ -508,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); } @@ -569,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); } /// @@ -600,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); } /// @@ -625,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")); /// @@ -633,10 +664,10 @@ public static PressureChangeRateUnit ParseUnit(string str) /// Error parsing string. public static PressureChangeRateUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -651,10 +682,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -670,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; } @@ -720,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current PressureChangeRate. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(PressureChangeRate), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -813,256 +838,24 @@ public int CompareTo(object? obj) /// public int CompareTo(PressureChangeRate other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another PressureChangeRate within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(PressureChangeRate other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is PressureChangeRate otherTyped - && (tolerance is PressureChangeRate toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'PressureChangeRate'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(PressureChangeRate other, PressureChangeRate tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current PressureChangeRate. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(PressureChangeRateUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(PressureChangeRateUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(PressureChangeRateUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1077,137 +870,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(PressureChangeRate)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(PressureChangeRate)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(PressureChangeRate)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(PressureChangeRate)) - return this; - else if (conversionType == typeof(PressureChangeRateUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return PressureChangeRate.Info; - else if (conversionType == typeof(BaseDimensions)) - return PressureChangeRate.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(PressureChangeRate)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/RadiationEquivalentDose.g.cs b/UnitsNet/GeneratedCode/Quantities/RadiationEquivalentDose.g.cs index 4b9f3943db..cacf6382eb 100644 --- a/UnitsNet/GeneratedCode/Quantities/RadiationEquivalentDose.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RadiationEquivalentDose.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -52,42 +47,100 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static RadiationEquivalentDose() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class RadiationEquivalentDoseInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(2, 0, -2, 0, 0, 0, 0); - BaseUnit = RadiationEquivalentDoseUnit.Sievert; - Units = Enum.GetValues(typeof(RadiationEquivalentDoseUnit)).Cast().ToArray(); - Zero = new RadiationEquivalentDose(0, BaseUnit); - Info = new QuantityInfo("RadiationEquivalentDose", - new UnitInfo[] - { - new UnitInfo(RadiationEquivalentDoseUnit.Microsievert, "Microsieverts", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Second), "RadiationEquivalentDose"), - new UnitInfo(RadiationEquivalentDoseUnit.MilliroentgenEquivalentMan, "MilliroentgensEquivalentMan", BaseUnits.Undefined, "RadiationEquivalentDose"), - new UnitInfo(RadiationEquivalentDoseUnit.Millisievert, "Millisieverts", BaseUnits.Undefined, "RadiationEquivalentDose"), - new UnitInfo(RadiationEquivalentDoseUnit.Nanosievert, "Nanosieverts", BaseUnits.Undefined, "RadiationEquivalentDose"), - new UnitInfo(RadiationEquivalentDoseUnit.RoentgenEquivalentMan, "RoentgensEquivalentMan", BaseUnits.Undefined, "RadiationEquivalentDose"), - new UnitInfo(RadiationEquivalentDoseUnit.Sievert, "Sieverts", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second), "RadiationEquivalentDose"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public RadiationEquivalentDoseInfo(string name, RadiationEquivalentDoseUnit baseUnit, IEnumerable> unitMappings, RadiationEquivalentDose zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public RadiationEquivalentDoseInfo(string name, RadiationEquivalentDoseUnit baseUnit, IEnumerable> unitMappings, RadiationEquivalentDose zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, RadiationEquivalentDose.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.RadiationEquivalentDose", typeof(RadiationEquivalentDose).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the RadiationEquivalentDose quantity. + /// + /// A new instance of the class with the default settings. + public static RadiationEquivalentDoseInfo CreateDefault() + { + return new RadiationEquivalentDoseInfo(nameof(RadiationEquivalentDose), DefaultBaseUnit, GetDefaultMappings(), new RadiationEquivalentDose(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the RadiationEquivalentDose quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static RadiationEquivalentDoseInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new RadiationEquivalentDoseInfo(nameof(RadiationEquivalentDose), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new RadiationEquivalentDose(0, DefaultBaseUnit), DefaultBaseDimensions); + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// The for is T^-2L^2. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 0, -2, 0, 0, 0, 0); + + /// + /// The default base unit of RadiationEquivalentDose is Sievert. All conversions, as defined in the , go via this value. + /// + public static RadiationEquivalentDoseUnit DefaultBaseUnit { get; } = RadiationEquivalentDoseUnit.Sievert; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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 = UnitsNetSetup.CreateQuantityInfo(RadiationEquivalentDoseInfo.CreateDefault); } /// @@ -95,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; @@ -109,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); @@ -120,124 +173,109 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of RadiationEquivalentDose, which is Sievert. All conversions go via this value. /// - public static RadiationEquivalentDoseUnit BaseUnit { get; } + public static RadiationEquivalentDoseUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the RadiationEquivalentDose quantity. /// - public static RadiationEquivalentDoseUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Sievert. /// - public static RadiationEquivalentDose Zero { get; } - - /// - public static RadiationEquivalentDose AdditiveIdentity => Zero; + public static RadiationEquivalentDose Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public RadiationEquivalentDoseUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => RadiationEquivalentDose.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -266,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); } @@ -274,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); } @@ -282,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); } @@ -290,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); } @@ -298,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); } @@ -306,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); } @@ -317,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); } @@ -378,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); } /// @@ -409,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); } /// @@ -434,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")); /// @@ -442,10 +473,10 @@ public static RadiationEquivalentDoseUnit ParseUnit(string str) /// Error parsing string. public static RadiationEquivalentDoseUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -460,10 +491,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -479,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; } @@ -535,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current RadiationEquivalentDose. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(RadiationEquivalentDose), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -628,232 +653,24 @@ public int CompareTo(object? obj) /// public int CompareTo(RadiationEquivalentDose other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another RadiationEquivalentDose within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(RadiationEquivalentDose other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is RadiationEquivalentDose otherTyped - && (tolerance is RadiationEquivalentDose toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'RadiationEquivalentDose'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(RadiationEquivalentDose other, RadiationEquivalentDose tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current RadiationEquivalentDose. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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)); + #region Conversion Methods (explicit implementations for netstandard2.0) - 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 RadiationEquivalentDoseUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RadiationEquivalentDoseUnit)} 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(RadiationEquivalentDoseUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(RadiationEquivalentDoseUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -868,137 +685,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(RadiationEquivalentDose)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(RadiationEquivalentDose)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(RadiationEquivalentDose)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(RadiationEquivalentDose)) - return this; - else if (conversionType == typeof(RadiationEquivalentDoseUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return RadiationEquivalentDose.Info; - else if (conversionType == typeof(BaseDimensions)) - return RadiationEquivalentDose.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(RadiationEquivalentDose)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/RadiationEquivalentDoseRate.g.cs b/UnitsNet/GeneratedCode/Quantities/RadiationEquivalentDoseRate.g.cs index 5cd347b7d5..0125db6cff 100644 --- a/UnitsNet/GeneratedCode/Quantities/RadiationEquivalentDoseRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RadiationEquivalentDoseRate.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -51,46 +46,112 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class RadiationEquivalentDoseRateInfo: QuantityInfo + { + /// + public RadiationEquivalentDoseRateInfo(string name, RadiationEquivalentDoseRateUnit baseUnit, IEnumerable> unitMappings, RadiationEquivalentDoseRate zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public RadiationEquivalentDoseRateInfo(string name, RadiationEquivalentDoseRateUnit baseUnit, IEnumerable> unitMappings, RadiationEquivalentDoseRate zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, RadiationEquivalentDoseRate.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.RadiationEquivalentDoseRate", typeof(RadiationEquivalentDoseRate).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the RadiationEquivalentDoseRate quantity. + /// + /// A new instance of the class with the default settings. + public static RadiationEquivalentDoseRateInfo CreateDefault() + { + return new RadiationEquivalentDoseRateInfo(nameof(RadiationEquivalentDoseRate), DefaultBaseUnit, GetDefaultMappings(), new RadiationEquivalentDoseRate(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the RadiationEquivalentDoseRate quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static RadiationEquivalentDoseRateInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new RadiationEquivalentDoseRateInfo(nameof(RadiationEquivalentDoseRate), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new RadiationEquivalentDoseRate(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-3L^2. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 0, -3, 0, 0, 0, 0); + + /// + /// The default base unit of RadiationEquivalentDoseRate is SievertPerSecond. All conversions, as defined in the , go via this value. + /// + public static RadiationEquivalentDoseRateUnit DefaultBaseUnit { get; } = RadiationEquivalentDoseRateUnit.SievertPerSecond; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for RadiationEquivalentDoseRate. + public static IEnumerable> GetDefaultMappings() + { + 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() { - BaseDimensions = new BaseDimensions(2, 0, -3, 0, 0, 0, 0); - BaseUnit = RadiationEquivalentDoseRateUnit.SievertPerSecond; - Units = Enum.GetValues(typeof(RadiationEquivalentDoseRateUnit)).Cast().ToArray(); - Zero = new RadiationEquivalentDoseRate(0, BaseUnit); - Info = new QuantityInfo("RadiationEquivalentDoseRate", - new UnitInfo[] - { - new UnitInfo(RadiationEquivalentDoseRateUnit.MicrosievertPerHour, "MicrosievertsPerHour", BaseUnits.Undefined, "RadiationEquivalentDoseRate"), - new UnitInfo(RadiationEquivalentDoseRateUnit.MicrosievertPerSecond, "MicrosievertsPerSecond", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Second), "RadiationEquivalentDoseRate"), - new UnitInfo(RadiationEquivalentDoseRateUnit.MilliroentgenEquivalentManPerHour, "MilliroentgensEquivalentManPerHour", BaseUnits.Undefined, "RadiationEquivalentDoseRate"), - new UnitInfo(RadiationEquivalentDoseRateUnit.MillisievertPerHour, "MillisievertsPerHour", BaseUnits.Undefined, "RadiationEquivalentDoseRate"), - new UnitInfo(RadiationEquivalentDoseRateUnit.MillisievertPerSecond, "MillisievertsPerSecond", BaseUnits.Undefined, "RadiationEquivalentDoseRate"), - new UnitInfo(RadiationEquivalentDoseRateUnit.NanosievertPerHour, "NanosievertsPerHour", BaseUnits.Undefined, "RadiationEquivalentDoseRate"), - new UnitInfo(RadiationEquivalentDoseRateUnit.NanosievertPerSecond, "NanosievertsPerSecond", BaseUnits.Undefined, "RadiationEquivalentDoseRate"), - new UnitInfo(RadiationEquivalentDoseRateUnit.RoentgenEquivalentManPerHour, "RoentgensEquivalentManPerHour", BaseUnits.Undefined, "RadiationEquivalentDoseRate"), - new UnitInfo(RadiationEquivalentDoseRateUnit.SievertPerHour, "SievertsPerHour", BaseUnits.Undefined, "RadiationEquivalentDoseRate"), - new UnitInfo(RadiationEquivalentDoseRateUnit.SievertPerSecond, "SievertsPerSecond", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second), "RadiationEquivalentDoseRate"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(RadiationEquivalentDoseRateInfo.CreateDefault); } /// @@ -98,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; @@ -112,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); @@ -123,152 +184,129 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of RadiationEquivalentDoseRate, which is SievertPerSecond. All conversions go via this value. /// - public static RadiationEquivalentDoseRateUnit BaseUnit { get; } + public static RadiationEquivalentDoseRateUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the RadiationEquivalentDoseRate quantity. /// - public static RadiationEquivalentDoseRateUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit SievertPerSecond. /// - public static RadiationEquivalentDoseRate Zero { get; } - - /// - public static RadiationEquivalentDoseRate AdditiveIdentity => Zero; + public static RadiationEquivalentDoseRate Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public RadiationEquivalentDoseRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => RadiationEquivalentDoseRate.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -297,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); } @@ -305,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); } @@ -313,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); } @@ -321,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); } @@ -329,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); } @@ -337,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); } @@ -345,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); } @@ -353,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); } @@ -361,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); } @@ -369,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); } @@ -380,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); } @@ -441,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); } /// @@ -472,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); } /// @@ -497,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")); /// @@ -505,10 +536,10 @@ public static RadiationEquivalentDoseRateUnit ParseUnit(string str) /// Error parsing string. public static RadiationEquivalentDoseRateUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -523,10 +554,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -542,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; } @@ -592,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current RadiationEquivalentDoseRate. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(RadiationEquivalentDoseRate), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -685,240 +710,24 @@ public int CompareTo(object? obj) /// public int CompareTo(RadiationEquivalentDoseRate other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another RadiationEquivalentDoseRate within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(RadiationEquivalentDoseRate other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is RadiationEquivalentDoseRate otherTyped - && (tolerance is RadiationEquivalentDoseRate toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'RadiationEquivalentDoseRate'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(RadiationEquivalentDoseRate other, RadiationEquivalentDoseRate tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current RadiationEquivalentDoseRate. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(RadiationEquivalentDoseRateUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(RadiationEquivalentDoseRateUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -933,137 +742,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(RadiationEquivalentDoseRate)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(RadiationEquivalentDoseRate)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(RadiationEquivalentDoseRate)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(RadiationEquivalentDoseRate)) - return this; - else if (conversionType == typeof(RadiationEquivalentDoseRateUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return RadiationEquivalentDoseRate.Info; - else if (conversionType == typeof(BaseDimensions)) - return RadiationEquivalentDoseRate.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(RadiationEquivalentDoseRate)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/RadiationExposure.g.cs b/UnitsNet/GeneratedCode/Quantities/RadiationExposure.g.cs index 8298931338..905c48a23d 100644 --- a/UnitsNet/GeneratedCode/Quantities/RadiationExposure.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RadiationExposure.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -48,44 +43,106 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class RadiationExposureInfo: QuantityInfo + { + /// + public RadiationExposureInfo(string name, RadiationExposureUnit baseUnit, IEnumerable> unitMappings, RadiationExposure zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public RadiationExposureInfo(string name, RadiationExposureUnit baseUnit, IEnumerable> unitMappings, RadiationExposure zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, RadiationExposure.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.RadiationExposure", typeof(RadiationExposure).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the RadiationExposure quantity. + /// + /// A new instance of the class with the default settings. + public static RadiationExposureInfo CreateDefault() + { + return new RadiationExposureInfo(nameof(RadiationExposure), DefaultBaseUnit, GetDefaultMappings(), new RadiationExposure(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the RadiationExposure quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static RadiationExposureInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new RadiationExposureInfo(nameof(RadiationExposure), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new RadiationExposure(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is TM^-1I. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, -1, 1, 1, 0, 0, 0); + + /// + /// The default base unit of RadiationExposure is CoulombPerKilogram. All conversions, as defined in the , go via this value. + /// + public static RadiationExposureUnit DefaultBaseUnit { get; } = RadiationExposureUnit.CoulombPerKilogram; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for RadiationExposure. + public static IEnumerable> 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), + 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() { - BaseDimensions = new BaseDimensions(0, -1, 1, 1, 0, 0, 0); - BaseUnit = RadiationExposureUnit.CoulombPerKilogram; - Units = Enum.GetValues(typeof(RadiationExposureUnit)).Cast().ToArray(); - Zero = new RadiationExposure(0, BaseUnit); - Info = new QuantityInfo("RadiationExposure", - new UnitInfo[] - { - new UnitInfo(RadiationExposureUnit.CoulombPerKilogram, "CoulombsPerKilogram", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "RadiationExposure"), - new UnitInfo(RadiationExposureUnit.MicrocoulombPerKilogram, "MicrocoulombsPerKilogram", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Microampere), "RadiationExposure"), - new UnitInfo(RadiationExposureUnit.Microroentgen, "Microroentgens", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Microampere), "RadiationExposure"), - new UnitInfo(RadiationExposureUnit.MillicoulombPerKilogram, "MillicoulombsPerKilogram", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere), "RadiationExposure"), - new UnitInfo(RadiationExposureUnit.Milliroentgen, "Milliroentgens", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere), "RadiationExposure"), - new UnitInfo(RadiationExposureUnit.NanocoulombPerKilogram, "NanocoulombsPerKilogram", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Nanoampere), "RadiationExposure"), - new UnitInfo(RadiationExposureUnit.PicocoulombPerKilogram, "PicocoulombsPerKilogram", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Picoampere), "RadiationExposure"), - new UnitInfo(RadiationExposureUnit.Roentgen, "Roentgens", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), "RadiationExposure"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(RadiationExposureInfo.CreateDefault); } /// @@ -93,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; @@ -107,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); @@ -118,138 +175,119 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of RadiationExposure, which is CoulombPerKilogram. All conversions go via this value. /// - public static RadiationExposureUnit BaseUnit { get; } + public static RadiationExposureUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the RadiationExposure quantity. /// - public static RadiationExposureUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit CoulombPerKilogram. /// - public static RadiationExposure Zero { get; } - - /// - public static RadiationExposure AdditiveIdentity => Zero; + public static RadiationExposure Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public RadiationExposureUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => RadiationExposure.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -278,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); } @@ -286,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); } @@ -294,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); } @@ -302,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); } @@ -310,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); } @@ -318,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); } @@ -326,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); } @@ -334,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); } @@ -345,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); } @@ -406,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); } /// @@ -437,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); } /// @@ -462,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")); /// @@ -470,10 +501,10 @@ public static RadiationExposureUnit ParseUnit(string str) /// Error parsing string. public static RadiationExposureUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -488,10 +519,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -507,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; } @@ -547,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current RadiationExposure. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(RadiationExposure), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -640,236 +665,24 @@ public int CompareTo(object? obj) /// public int CompareTo(RadiationExposure other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another RadiationExposure within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(RadiationExposure other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is RadiationExposure otherTyped - && (tolerance is RadiationExposure toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'RadiationExposure'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(RadiationExposure other, RadiationExposure tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current RadiationExposure. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(RadiationExposureUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - /// 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); - } + IQuantity IQuantity.ToUnit(RadiationExposureUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(RadiationExposureUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -884,137 +697,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(RadiationExposure)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(RadiationExposure)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(RadiationExposure)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(RadiationExposure)) - return this; - else if (conversionType == typeof(RadiationExposureUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return RadiationExposure.Info; - else if (conversionType == typeof(BaseDimensions)) - return RadiationExposure.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(RadiationExposure)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Radioactivity.g.cs b/UnitsNet/GeneratedCode/Quantities/Radioactivity.g.cs index 0793e6cae3..a3bd431e0e 100644 --- a/UnitsNet/GeneratedCode/Quantities/Radioactivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Radioactivity.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -48,65 +43,169 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class RadioactivityInfo: QuantityInfo + { + /// + public RadioactivityInfo(string name, RadioactivityUnit baseUnit, IEnumerable> unitMappings, Radioactivity zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public RadioactivityInfo(string name, RadioactivityUnit baseUnit, IEnumerable> unitMappings, Radioactivity zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Radioactivity.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Radioactivity", typeof(Radioactivity).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Radioactivity quantity. + /// + /// A new instance of the class with the default settings. + public static RadioactivityInfo CreateDefault() + { + return new RadioactivityInfo(nameof(Radioactivity), DefaultBaseUnit, GetDefaultMappings(), new Radioactivity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Radioactivity quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static RadioactivityInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new RadioactivityInfo(nameof(Radioactivity), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Radioactivity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-1. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); + + /// + /// The default base unit of Radioactivity is Becquerel. All conversions, as defined in the , go via this value. + /// + public static RadioactivityUnit DefaultBaseUnit { get; } = RadioactivityUnit.Becquerel; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Radioactivity. + public static IEnumerable> 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), + 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", BaseUnits.Undefined, + new QuantityValue(1, 1000000000000) + ); + yield return new (RadioactivityUnit.Teracurie, "Teracurie", "Teracuries", BaseUnits.Undefined, + new QuantityValue(1, new BigInteger(37) * QuantityValue.PowerOfTen(21)) + ); + yield return new (RadioactivityUnit.Terarutherford, "Terarutherford", "Terarutherfords", BaseUnits.Undefined, + new QuantityValue(1, 1000000000000000000) + ); + } + } + static Radioactivity() { - BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); - BaseUnit = RadioactivityUnit.Becquerel; - Units = Enum.GetValues(typeof(RadioactivityUnit)).Cast().ToArray(); - Zero = new Radioactivity(0, BaseUnit); - Info = new QuantityInfo("Radioactivity", - new UnitInfo[] - { - new UnitInfo(RadioactivityUnit.Becquerel, "Becquerels", new BaseUnits(time: DurationUnit.Second), "Radioactivity"), - new UnitInfo(RadioactivityUnit.Curie, "Curies", new BaseUnits(time: DurationUnit.Second), "Radioactivity"), - new UnitInfo(RadioactivityUnit.Exabecquerel, "Exabecquerels", BaseUnits.Undefined, "Radioactivity"), - new UnitInfo(RadioactivityUnit.Gigabecquerel, "Gigabecquerels", new BaseUnits(time: DurationUnit.Nanosecond), "Radioactivity"), - new UnitInfo(RadioactivityUnit.Gigacurie, "Gigacuries", new BaseUnits(time: DurationUnit.Nanosecond), "Radioactivity"), - new UnitInfo(RadioactivityUnit.Gigarutherford, "Gigarutherfords", new BaseUnits(time: DurationUnit.Nanosecond), "Radioactivity"), - new UnitInfo(RadioactivityUnit.Kilobecquerel, "Kilobecquerels", new BaseUnits(time: DurationUnit.Millisecond), "Radioactivity"), - new UnitInfo(RadioactivityUnit.Kilocurie, "Kilocuries", new BaseUnits(time: DurationUnit.Millisecond), "Radioactivity"), - new UnitInfo(RadioactivityUnit.Kilorutherford, "Kilorutherfords", new BaseUnits(time: DurationUnit.Millisecond), "Radioactivity"), - new UnitInfo(RadioactivityUnit.Megabecquerel, "Megabecquerels", new BaseUnits(time: DurationUnit.Microsecond), "Radioactivity"), - new UnitInfo(RadioactivityUnit.Megacurie, "Megacuries", new BaseUnits(time: DurationUnit.Microsecond), "Radioactivity"), - new UnitInfo(RadioactivityUnit.Megarutherford, "Megarutherfords", new BaseUnits(time: DurationUnit.Microsecond), "Radioactivity"), - new UnitInfo(RadioactivityUnit.Microbecquerel, "Microbecquerels", BaseUnits.Undefined, "Radioactivity"), - new UnitInfo(RadioactivityUnit.Microcurie, "Microcuries", BaseUnits.Undefined, "Radioactivity"), - new UnitInfo(RadioactivityUnit.Microrutherford, "Microrutherfords", BaseUnits.Undefined, "Radioactivity"), - new UnitInfo(RadioactivityUnit.Millibecquerel, "Millibecquerels", BaseUnits.Undefined, "Radioactivity"), - new UnitInfo(RadioactivityUnit.Millicurie, "Millicuries", BaseUnits.Undefined, "Radioactivity"), - new UnitInfo(RadioactivityUnit.Millirutherford, "Millirutherfords", BaseUnits.Undefined, "Radioactivity"), - new UnitInfo(RadioactivityUnit.Nanobecquerel, "Nanobecquerels", BaseUnits.Undefined, "Radioactivity"), - new UnitInfo(RadioactivityUnit.Nanocurie, "Nanocuries", BaseUnits.Undefined, "Radioactivity"), - new UnitInfo(RadioactivityUnit.Nanorutherford, "Nanorutherfords", BaseUnits.Undefined, "Radioactivity"), - new UnitInfo(RadioactivityUnit.Petabecquerel, "Petabecquerels", BaseUnits.Undefined, "Radioactivity"), - new UnitInfo(RadioactivityUnit.Picobecquerel, "Picobecquerels", BaseUnits.Undefined, "Radioactivity"), - new UnitInfo(RadioactivityUnit.Picocurie, "Picocuries", BaseUnits.Undefined, "Radioactivity"), - new UnitInfo(RadioactivityUnit.Picorutherford, "Picorutherfords", BaseUnits.Undefined, "Radioactivity"), - new UnitInfo(RadioactivityUnit.Rutherford, "Rutherfords", new BaseUnits(time: DurationUnit.Second), "Radioactivity"), - new UnitInfo(RadioactivityUnit.Terabecquerel, "Terabecquerels", BaseUnits.Undefined, "Radioactivity"), - new UnitInfo(RadioactivityUnit.Teracurie, "Teracuries", BaseUnits.Undefined, "Radioactivity"), - new UnitInfo(RadioactivityUnit.Terarutherford, "Terarutherfords", BaseUnits.Undefined, "Radioactivity"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(RadioactivityInfo.CreateDefault); } /// @@ -114,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; @@ -128,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); @@ -139,285 +238,224 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Radioactivity, which is Becquerel. All conversions go via this value. /// - public static RadioactivityUnit BaseUnit { get; } + public static RadioactivityUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Radioactivity quantity. /// - public static RadioactivityUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Becquerel. /// - public static Radioactivity Zero { get; } - - /// - public static Radioactivity AdditiveIdentity => Zero; + public static Radioactivity Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public RadioactivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Radioactivity.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -446,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); } @@ -454,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); } @@ -462,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); } @@ -470,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); } @@ -478,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); } @@ -486,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); } @@ -494,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); } @@ -502,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); } @@ -510,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); } @@ -518,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); } @@ -526,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); } @@ -534,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); } @@ -542,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); } @@ -550,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); } @@ -558,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); } @@ -566,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); } @@ -574,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); } @@ -582,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); } @@ -590,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); } @@ -598,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); } @@ -606,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); } @@ -614,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); } @@ -622,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); } @@ -630,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); } @@ -638,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); } @@ -646,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); } @@ -654,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); } @@ -662,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); } @@ -670,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); } @@ -681,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); } @@ -742,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); } /// @@ -773,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); } /// @@ -798,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")); /// @@ -806,10 +837,10 @@ public static RadioactivityUnit ParseUnit(string str) /// Error parsing string. public static RadioactivityUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -824,10 +855,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -843,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; } @@ -883,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Radioactivity. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Radioactivity), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -976,278 +1001,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Radioactivity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Radioactivity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Radioactivity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Radioactivity otherTyped - && (tolerance is Radioactivity toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Radioactivity'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Radioactivity other, Radioactivity tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Radioactivity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(RadioactivityUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - /// 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 NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } + IQuantity IQuantity.ToUnit(RadioactivityUnit unit) => this.ToUnit(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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(RadioactivityUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1262,137 +1033,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Radioactivity)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Radioactivity)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Radioactivity)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Radioactivity)) - return this; - else if (conversionType == typeof(RadioactivityUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Radioactivity.Info; - else if (conversionType == typeof(BaseDimensions)) - return Radioactivity.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Radioactivity)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs b/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs index 61d01c71be..e23d3e7239 100644 --- a/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -48,42 +43,100 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static Ratio() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class RatioInfo: QuantityInfo { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = RatioUnit.DecimalFraction; - Units = Enum.GetValues(typeof(RatioUnit)).Cast().ToArray(); - Zero = new Ratio(0, BaseUnit); - Info = new QuantityInfo("Ratio", - new UnitInfo[] - { - new UnitInfo(RatioUnit.DecimalFraction, "DecimalFractions", BaseUnits.Undefined, "Ratio"), - new UnitInfo(RatioUnit.PartPerBillion, "PartsPerBillion", BaseUnits.Undefined, "Ratio"), - new UnitInfo(RatioUnit.PartPerMillion, "PartsPerMillion", BaseUnits.Undefined, "Ratio"), - new UnitInfo(RatioUnit.PartPerThousand, "PartsPerThousand", BaseUnits.Undefined, "Ratio"), - new UnitInfo(RatioUnit.PartPerTrillion, "PartsPerTrillion", BaseUnits.Undefined, "Ratio"), - new UnitInfo(RatioUnit.Percent, "Percent", BaseUnits.Undefined, "Ratio"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public RatioInfo(string name, RatioUnit baseUnit, IEnumerable> unitMappings, Ratio zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public RatioInfo(string name, RatioUnit baseUnit, IEnumerable> unitMappings, Ratio zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Ratio.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Ratio", typeof(Ratio).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Ratio quantity. + /// + /// A new instance of the class with the default settings. + public static RatioInfo CreateDefault() + { + return new RatioInfo(nameof(Ratio), DefaultBaseUnit, GetDefaultMappings(), new Ratio(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Ratio quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static RatioInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new RatioInfo(nameof(Ratio), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Ratio(0, DefaultBaseUnit), DefaultBaseDimensions); + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// The for is . + /// + public static BaseDimensions DefaultBaseDimensions { get; } = BaseDimensions.Dimensionless; + + /// + /// The default base unit of Ratio is DecimalFraction. All conversions, as defined in the , go via this value. + /// + public static RatioUnit DefaultBaseUnit { get; } = RatioUnit.DecimalFraction; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Ratio. + public static IEnumerable> GetDefaultMappings() + { + yield return new (RatioUnit.DecimalFraction, "DecimalFraction", "DecimalFractions", 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 = UnitsNetSetup.CreateQuantityInfo(RatioInfo.CreateDefault); } /// @@ -91,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; @@ -102,124 +155,109 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Ratio, which is DecimalFraction. All conversions go via this value. /// - public static RatioUnit BaseUnit { get; } + public static RatioUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Ratio quantity. /// - public static RatioUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit DecimalFraction. /// - public static Ratio Zero { get; } - - /// - public static Ratio AdditiveIdentity => Zero; + public static Ratio Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public RatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Ratio.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -248,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); } @@ -256,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); } @@ -264,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); } @@ -272,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); } @@ -280,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); } @@ -288,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); } @@ -299,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); } @@ -360,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); } /// @@ -391,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); } /// @@ -416,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")); /// @@ -424,10 +455,10 @@ public static RatioUnit ParseUnit(string str) /// Error parsing string. public static RatioUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -442,10 +473,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -461,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; } @@ -501,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Ratio. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Ratio), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -594,232 +619,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Ratio other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Ratio within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Ratio other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Ratio otherTyped - && (tolerance is Ratio toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Ratio'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Ratio other, Ratio tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Ratio. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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)); + #region Conversion Methods (explicit implementations for netstandard2.0) - 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 RatioUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RatioUnit)} 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(RatioUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(RatioUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -834,137 +651,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Ratio)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Ratio)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Ratio)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Ratio)) - return this; - else if (conversionType == typeof(RatioUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Ratio.Info; - else if (conversionType == typeof(BaseDimensions)) - return Ratio.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Ratio)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/RatioChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/RatioChangeRate.g.cs index 28035c2af5..92102720f9 100644 --- a/UnitsNet/GeneratedCode/Quantities/RatioChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RatioChangeRate.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -48,38 +43,88 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static RatioChangeRate() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class RatioChangeRateInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); - BaseUnit = RatioChangeRateUnit.DecimalFractionPerSecond; - Units = Enum.GetValues(typeof(RatioChangeRateUnit)).Cast().ToArray(); - Zero = new RatioChangeRate(0, BaseUnit); - Info = new QuantityInfo("RatioChangeRate", - new UnitInfo[] - { - new UnitInfo(RatioChangeRateUnit.DecimalFractionPerSecond, "DecimalFractionsPerSecond", new BaseUnits(time: DurationUnit.Second), "RatioChangeRate"), - new UnitInfo(RatioChangeRateUnit.PercentPerSecond, "PercentsPerSecond", BaseUnits.Undefined, "RatioChangeRate"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public RatioChangeRateInfo(string name, RatioChangeRateUnit baseUnit, IEnumerable> unitMappings, RatioChangeRate zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public RatioChangeRateInfo(string name, RatioChangeRateUnit baseUnit, IEnumerable> unitMappings, RatioChangeRate zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, RatioChangeRate.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.RatioChangeRate", typeof(RatioChangeRate).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the RatioChangeRate quantity. + /// + /// A new instance of the class with the default settings. + public static RatioChangeRateInfo CreateDefault() + { + return new RatioChangeRateInfo(nameof(RatioChangeRate), DefaultBaseUnit, GetDefaultMappings(), new RatioChangeRate(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the RatioChangeRate quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static RatioChangeRateInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new RatioChangeRateInfo(nameof(RatioChangeRate), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new RatioChangeRate(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-1. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); + + /// + /// The default base unit of RatioChangeRate is DecimalFractionPerSecond. All conversions, as defined in the , go via this value. + /// + public static RatioChangeRateUnit DefaultBaseUnit { get; } = RatioChangeRateUnit.DecimalFractionPerSecond; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for RatioChangeRate. + public static IEnumerable> GetDefaultMappings() + { + yield return new (RatioChangeRateUnit.DecimalFractionPerSecond, "DecimalFractionPerSecond", "DecimalFractionsPerSecond", new BaseUnits(time: DurationUnit.Second)); + yield return new (RatioChangeRateUnit.PercentPerSecond, "PercentPerSecond", "PercentsPerSecond", BaseUnits.Undefined, + 100 + ); + } + } + + static RatioChangeRate() + { + Info = UnitsNetSetup.CreateQuantityInfo(RatioChangeRateInfo.CreateDefault); } /// @@ -87,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; @@ -101,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); @@ -112,96 +157,89 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of RatioChangeRate, which is DecimalFractionPerSecond. All conversions go via this value. /// - public static RatioChangeRateUnit BaseUnit { get; } + public static RatioChangeRateUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the RatioChangeRate quantity. /// - public static RatioChangeRateUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit DecimalFractionPerSecond. /// - public static RatioChangeRate Zero { get; } - - /// - public static RatioChangeRate AdditiveIdentity => Zero; + public static RatioChangeRate Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public RatioChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => RatioChangeRate.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -230,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); } @@ -238,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); } @@ -249,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); } @@ -310,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); } /// @@ -341,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); } /// @@ -366,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")); /// @@ -374,10 +405,10 @@ public static RatioChangeRateUnit ParseUnit(string str) /// Error parsing string. public static RatioChangeRateUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -392,10 +423,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -411,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; } @@ -451,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current RatioChangeRate. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(RatioChangeRate), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -544,224 +569,24 @@ public int CompareTo(object? obj) /// public int CompareTo(RatioChangeRate other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another RatioChangeRate within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(RatioChangeRate other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is RatioChangeRate otherTyped - && (tolerance is RatioChangeRate toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'RatioChangeRate'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(RatioChangeRate other, RatioChangeRate tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current RatioChangeRate. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(RatioChangeRateUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(RatioChangeRateUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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), - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -776,137 +601,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(RatioChangeRate)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(RatioChangeRate)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(RatioChangeRate)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(RatioChangeRate)) - return this; - else if (conversionType == typeof(RatioChangeRateUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return RatioChangeRate.Info; - else if (conversionType == typeof(BaseDimensions)) - return RatioChangeRate.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(RatioChangeRate)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ReciprocalArea.g.cs b/UnitsNet/GeneratedCode/Quantities/ReciprocalArea.g.cs index 5a40259f87..c54cc1a664 100644 --- a/UnitsNet/GeneratedCode/Quantities/ReciprocalArea.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ReciprocalArea.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -58,47 +53,115 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ReciprocalAreaInfo: QuantityInfo + { + /// + public ReciprocalAreaInfo(string name, ReciprocalAreaUnit baseUnit, IEnumerable> unitMappings, ReciprocalArea zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ReciprocalAreaInfo(string name, ReciprocalAreaUnit baseUnit, IEnumerable> unitMappings, ReciprocalArea zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ReciprocalArea.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ReciprocalArea", typeof(ReciprocalArea).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the ReciprocalArea quantity. + /// + /// A new instance of the class with the default settings. + public static ReciprocalAreaInfo CreateDefault() + { + return new ReciprocalAreaInfo(nameof(ReciprocalArea), DefaultBaseUnit, GetDefaultMappings(), new ReciprocalArea(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ReciprocalArea quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ReciprocalAreaInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ReciprocalAreaInfo(nameof(ReciprocalArea), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ReciprocalArea(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is L^-2. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, 0, 0, 0, 0, 0, 0); + + /// + /// The default base unit of ReciprocalArea is InverseSquareMeter. All conversions, as defined in the , go via this value. + /// + public static ReciprocalAreaUnit DefaultBaseUnit { get; } = ReciprocalAreaUnit.InverseSquareMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for ReciprocalArea. + public static IEnumerable> GetDefaultMappings() + { + 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), + 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() { - BaseDimensions = new BaseDimensions(-2, 0, 0, 0, 0, 0, 0); - BaseUnit = ReciprocalAreaUnit.InverseSquareMeter; - Units = Enum.GetValues(typeof(ReciprocalAreaUnit)).Cast().ToArray(); - Zero = new ReciprocalArea(0, BaseUnit); - Info = new QuantityInfo("ReciprocalArea", - new UnitInfo[] - { - new UnitInfo(ReciprocalAreaUnit.InverseSquareCentimeter, "InverseSquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter), "ReciprocalArea"), - new UnitInfo(ReciprocalAreaUnit.InverseSquareDecimeter, "InverseSquareDecimeters", new BaseUnits(length: LengthUnit.Decimeter), "ReciprocalArea"), - new UnitInfo(ReciprocalAreaUnit.InverseSquareFoot, "InverseSquareFeet", new BaseUnits(length: LengthUnit.Foot), "ReciprocalArea"), - new UnitInfo(ReciprocalAreaUnit.InverseSquareInch, "InverseSquareInches", new BaseUnits(length: LengthUnit.Inch), "ReciprocalArea"), - new UnitInfo(ReciprocalAreaUnit.InverseSquareKilometer, "InverseSquareKilometers", new BaseUnits(length: LengthUnit.Kilometer), "ReciprocalArea"), - new UnitInfo(ReciprocalAreaUnit.InverseSquareMeter, "InverseSquareMeters", new BaseUnits(length: LengthUnit.Meter), "ReciprocalArea"), - new UnitInfo(ReciprocalAreaUnit.InverseSquareMicrometer, "InverseSquareMicrometers", new BaseUnits(length: LengthUnit.Micrometer), "ReciprocalArea"), - new UnitInfo(ReciprocalAreaUnit.InverseSquareMile, "InverseSquareMiles", new BaseUnits(length: LengthUnit.Mile), "ReciprocalArea"), - new UnitInfo(ReciprocalAreaUnit.InverseSquareMillimeter, "InverseSquareMillimeters", new BaseUnits(length: LengthUnit.Millimeter), "ReciprocalArea"), - new UnitInfo(ReciprocalAreaUnit.InverseSquareYard, "InverseSquareYards", new BaseUnits(length: LengthUnit.Yard), "ReciprocalArea"), - new UnitInfo(ReciprocalAreaUnit.InverseUsSurveySquareFoot, "InverseUsSurveySquareFeet", new BaseUnits(length: LengthUnit.UsSurveyFoot), "ReciprocalArea"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ReciprocalAreaInfo.CreateDefault); } /// @@ -106,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; @@ -120,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); @@ -131,159 +194,134 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ReciprocalArea, which is InverseSquareMeter. All conversions go via this value. /// - public static ReciprocalAreaUnit BaseUnit { get; } + public static ReciprocalAreaUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ReciprocalArea quantity. /// - public static ReciprocalAreaUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit InverseSquareMeter. /// - public static ReciprocalArea Zero { get; } - - /// - public static ReciprocalArea AdditiveIdentity => Zero; + public static ReciprocalArea Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ReciprocalAreaUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ReciprocalArea.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -312,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); } @@ -320,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); } @@ -328,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); } @@ -336,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); } @@ -344,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); } @@ -352,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); } @@ -360,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); } @@ -368,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); } @@ -376,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); } @@ -384,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); } @@ -392,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); } @@ -403,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); } @@ -464,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); } /// @@ -495,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); } /// @@ -520,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")); /// @@ -528,10 +559,10 @@ public static ReciprocalAreaUnit ParseUnit(string str) /// Error parsing string. public static ReciprocalAreaUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -546,10 +577,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -565,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; } @@ -606,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 * . @@ -646,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ReciprocalArea. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ReciprocalArea), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -739,242 +764,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ReciprocalArea other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ReciprocalArea within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ReciprocalArea other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ReciprocalArea otherTyped - && (tolerance is ReciprocalArea toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ReciprocalArea'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ReciprocalArea other, ReciprocalArea tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ReciprocalArea. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(ReciprocalAreaUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(ReciprocalAreaUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -989,137 +796,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ReciprocalArea)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ReciprocalArea)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ReciprocalArea)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ReciprocalArea)) - return this; - else if (conversionType == typeof(ReciprocalAreaUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ReciprocalArea.Info; - else if (conversionType == typeof(BaseDimensions)) - return ReciprocalArea.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ReciprocalArea)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ReciprocalLength.g.cs b/UnitsNet/GeneratedCode/Quantities/ReciprocalLength.g.cs index 4f611a43ee..a3946b9331 100644 --- a/UnitsNet/GeneratedCode/Quantities/ReciprocalLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ReciprocalLength.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -60,46 +55,112 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ReciprocalLengthInfo: QuantityInfo + { + /// + public ReciprocalLengthInfo(string name, ReciprocalLengthUnit baseUnit, IEnumerable> unitMappings, ReciprocalLength zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ReciprocalLengthInfo(string name, ReciprocalLengthUnit baseUnit, IEnumerable> unitMappings, ReciprocalLength zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ReciprocalLength.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ReciprocalLength", typeof(ReciprocalLength).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the ReciprocalLength quantity. + /// + /// A new instance of the class with the default settings. + public static ReciprocalLengthInfo CreateDefault() + { + return new ReciprocalLengthInfo(nameof(ReciprocalLength), DefaultBaseUnit, GetDefaultMappings(), new ReciprocalLength(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ReciprocalLength quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ReciprocalLengthInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ReciprocalLengthInfo(nameof(ReciprocalLength), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ReciprocalLength(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is L^-1. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-1, 0, 0, 0, 0, 0, 0); + + /// + /// The default base unit of ReciprocalLength is InverseMeter. All conversions, as defined in the , go via this value. + /// + public static ReciprocalLengthUnit DefaultBaseUnit { get; } = ReciprocalLengthUnit.InverseMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for ReciprocalLength. + public static IEnumerable> GetDefaultMappings() + { + 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), + 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() { - BaseDimensions = new BaseDimensions(-1, 0, 0, 0, 0, 0, 0); - BaseUnit = ReciprocalLengthUnit.InverseMeter; - Units = Enum.GetValues(typeof(ReciprocalLengthUnit)).Cast().ToArray(); - Zero = new ReciprocalLength(0, BaseUnit); - Info = new QuantityInfo("ReciprocalLength", - new UnitInfo[] - { - new UnitInfo(ReciprocalLengthUnit.InverseCentimeter, "InverseCentimeters", new BaseUnits(length: LengthUnit.Centimeter), "ReciprocalLength"), - new UnitInfo(ReciprocalLengthUnit.InverseFoot, "InverseFeet", new BaseUnits(length: LengthUnit.Foot), "ReciprocalLength"), - new UnitInfo(ReciprocalLengthUnit.InverseInch, "InverseInches", new BaseUnits(length: LengthUnit.Inch), "ReciprocalLength"), - new UnitInfo(ReciprocalLengthUnit.InverseMeter, "InverseMeters", new BaseUnits(length: LengthUnit.Meter), "ReciprocalLength"), - new UnitInfo(ReciprocalLengthUnit.InverseMicroinch, "InverseMicroinches", new BaseUnits(length: LengthUnit.Microinch), "ReciprocalLength"), - new UnitInfo(ReciprocalLengthUnit.InverseMil, "InverseMils", new BaseUnits(length: LengthUnit.Mil), "ReciprocalLength"), - new UnitInfo(ReciprocalLengthUnit.InverseMile, "InverseMiles", new BaseUnits(length: LengthUnit.Mile), "ReciprocalLength"), - new UnitInfo(ReciprocalLengthUnit.InverseMillimeter, "InverseMillimeters", new BaseUnits(length: LengthUnit.Millimeter), "ReciprocalLength"), - new UnitInfo(ReciprocalLengthUnit.InverseUsSurveyFoot, "InverseUsSurveyFeet", new BaseUnits(length: LengthUnit.UsSurveyFoot), "ReciprocalLength"), - new UnitInfo(ReciprocalLengthUnit.InverseYard, "InverseYards", new BaseUnits(length: LengthUnit.Yard), "ReciprocalLength"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ReciprocalLengthInfo.CreateDefault); } /// @@ -107,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; @@ -121,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); @@ -132,152 +193,129 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ReciprocalLength, which is InverseMeter. All conversions go via this value. /// - public static ReciprocalLengthUnit BaseUnit { get; } + public static ReciprocalLengthUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ReciprocalLength quantity. /// - public static ReciprocalLengthUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit InverseMeter. /// - public static ReciprocalLength Zero { get; } - - /// - public static ReciprocalLength AdditiveIdentity => Zero; + public static ReciprocalLength Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ReciprocalLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ReciprocalLength.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -306,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); } @@ -314,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); } @@ -322,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); } @@ -330,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); } @@ -338,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); } @@ -346,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); } @@ -354,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); } @@ -362,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); } @@ -370,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); } @@ -378,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); } @@ -389,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); } @@ -450,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); } /// @@ -481,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); } /// @@ -506,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")); /// @@ -514,10 +545,10 @@ public static ReciprocalLengthUnit ParseUnit(string str) /// Error parsing string. public static ReciprocalLengthUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -532,10 +563,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -551,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; } @@ -592,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 * . @@ -644,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ReciprocalLength. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ReciprocalLength), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -737,240 +762,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ReciprocalLength other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ReciprocalLength within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ReciprocalLength other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ReciprocalLength otherTyped - && (tolerance is ReciprocalLength toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ReciprocalLength'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ReciprocalLength other, ReciprocalLength tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ReciprocalLength. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(ReciprocalLengthUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(ReciprocalLengthUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -985,137 +794,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ReciprocalLength)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ReciprocalLength)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ReciprocalLength)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ReciprocalLength)) - return this; - else if (conversionType == typeof(ReciprocalLengthUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ReciprocalLength.Info; - else if (conversionType == typeof(BaseDimensions)) - return ReciprocalLength.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ReciprocalLength)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/RelativeHumidity.g.cs b/UnitsNet/GeneratedCode/Quantities/RelativeHumidity.g.cs index b14795608b..ec03591136 100644 --- a/UnitsNet/GeneratedCode/Quantities/RelativeHumidity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RelativeHumidity.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -48,37 +43,85 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static RelativeHumidity() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class RelativeHumidityInfo: QuantityInfo { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = RelativeHumidityUnit.Percent; - Units = Enum.GetValues(typeof(RelativeHumidityUnit)).Cast().ToArray(); - Zero = new RelativeHumidity(0, BaseUnit); - Info = new QuantityInfo("RelativeHumidity", - new UnitInfo[] - { - new UnitInfo(RelativeHumidityUnit.Percent, "Percent", BaseUnits.Undefined, "RelativeHumidity"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public RelativeHumidityInfo(string name, RelativeHumidityUnit baseUnit, IEnumerable> unitMappings, RelativeHumidity zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public RelativeHumidityInfo(string name, RelativeHumidityUnit baseUnit, IEnumerable> unitMappings, RelativeHumidity zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, RelativeHumidity.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.RelativeHumidity", typeof(RelativeHumidity).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the RelativeHumidity quantity. + /// + /// A new instance of the class with the default settings. + public static RelativeHumidityInfo CreateDefault() + { + return new RelativeHumidityInfo(nameof(RelativeHumidity), DefaultBaseUnit, GetDefaultMappings(), new RelativeHumidity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the RelativeHumidity quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static RelativeHumidityInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new RelativeHumidityInfo(nameof(RelativeHumidity), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new RelativeHumidity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is . + /// + public static BaseDimensions DefaultBaseDimensions { get; } = BaseDimensions.Dimensionless; + + /// + /// The default base unit of RelativeHumidity is Percent. All conversions, as defined in the , go via this value. + /// + public static RelativeHumidityUnit DefaultBaseUnit { get; } = RelativeHumidityUnit.Percent; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for RelativeHumidity. + public static IEnumerable> GetDefaultMappings() + { + yield return new (RelativeHumidityUnit.Percent, "Percent", "Percent", BaseUnits.Undefined); + } + } + + static RelativeHumidity() + { + Info = UnitsNetSetup.CreateQuantityInfo(RelativeHumidityInfo.CreateDefault); } /// @@ -86,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; @@ -97,88 +140,83 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of RelativeHumidity, which is Percent. All conversions go via this value. /// - public static RelativeHumidityUnit BaseUnit { get; } + public static RelativeHumidityUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the RelativeHumidity quantity. /// - public static RelativeHumidityUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Percent. /// - public static RelativeHumidity Zero { get; } - - /// - public static RelativeHumidity AdditiveIdentity => Zero; + public static RelativeHumidity Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public RelativeHumidityUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => RelativeHumidity.BaseDimensions; - #endregion + #region Explicit implementations - #region Conversion Properties + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); - /// - /// Gets a value of this quantity converted into - /// - public double Percent => As(RelativeHumidityUnit.Percent); + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif #endregion - #region Static Methods + #endregion + + #region Conversion Properties /// - /// Registers the default conversion functions in the given instance. + /// Gets a value of this quantity converted into /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: RelativeHumidityUnit -> BaseUnit + public QuantityValue Percent => this.As(RelativeHumidityUnit.Percent); - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(RelativeHumidityUnit.Percent, RelativeHumidityUnit.Percent, quantity => quantity); + #endregion - // Register in unit converter: BaseUnit -> RelativeHumidityUnit - } + #region Static Methods /// /// Get unit abbreviation string. @@ -208,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); } @@ -219,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); } @@ -280,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); } /// @@ -311,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); } /// @@ -336,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")); /// @@ -344,10 +375,10 @@ public static RelativeHumidityUnit ParseUnit(string str) /// Error parsing string. public static RelativeHumidityUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -362,10 +393,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -381,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; } @@ -421,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current RelativeHumidity. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(RelativeHumidity), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -514,222 +539,24 @@ public int CompareTo(object? obj) /// public int CompareTo(RelativeHumidity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another RelativeHumidity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(RelativeHumidity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is RelativeHumidity otherTyped - && (tolerance is RelativeHumidity toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'RelativeHumidity'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(RelativeHumidity other, RelativeHumidity tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current RelativeHumidity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(RelativeHumidityUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(RelativeHumidityUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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 - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -744,137 +571,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(RelativeHumidity)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(RelativeHumidity)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(RelativeHumidity)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(RelativeHumidity)) - return this; - else if (conversionType == typeof(RelativeHumidityUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return RelativeHumidity.Info; - else if (conversionType == typeof(BaseDimensions)) - return RelativeHumidity.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(RelativeHumidity)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs index fd96df6886..0a6631df75 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -48,40 +43,94 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static RotationalAcceleration() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class RotationalAccelerationInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(0, 0, -2, 0, 0, 0, 0); - BaseUnit = RotationalAccelerationUnit.RadianPerSecondSquared; - Units = Enum.GetValues(typeof(RotationalAccelerationUnit)).Cast().ToArray(); - Zero = new RotationalAcceleration(0, BaseUnit); - Info = new QuantityInfo("RotationalAcceleration", - new UnitInfo[] - { - new UnitInfo(RotationalAccelerationUnit.DegreePerSecondSquared, "DegreesPerSecondSquared", BaseUnits.Undefined, "RotationalAcceleration"), - new UnitInfo(RotationalAccelerationUnit.RadianPerSecondSquared, "RadiansPerSecondSquared", new BaseUnits(time: DurationUnit.Second), "RotationalAcceleration"), - new UnitInfo(RotationalAccelerationUnit.RevolutionPerMinutePerSecond, "RevolutionsPerMinutePerSecond", BaseUnits.Undefined, "RotationalAcceleration"), - new UnitInfo(RotationalAccelerationUnit.RevolutionPerSecondSquared, "RevolutionsPerSecondSquared", BaseUnits.Undefined, "RotationalAcceleration"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public RotationalAccelerationInfo(string name, RotationalAccelerationUnit baseUnit, IEnumerable> unitMappings, RotationalAcceleration zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public RotationalAccelerationInfo(string name, RotationalAccelerationUnit baseUnit, IEnumerable> unitMappings, RotationalAcceleration zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, RotationalAcceleration.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.RotationalAcceleration", typeof(RotationalAcceleration).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the RotationalAcceleration quantity. + /// + /// A new instance of the class with the default settings. + public static RotationalAccelerationInfo CreateDefault() + { + return new RotationalAccelerationInfo(nameof(RotationalAcceleration), DefaultBaseUnit, GetDefaultMappings(), new RotationalAcceleration(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the RotationalAcceleration quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static RotationalAccelerationInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new RotationalAccelerationInfo(nameof(RotationalAcceleration), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new RotationalAcceleration(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-2. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, -2, 0, 0, 0, 0); + + /// + /// The default base unit of RotationalAcceleration is RadianPerSecondSquared. All conversions, as defined in the , go via this value. + /// + public static RotationalAccelerationUnit DefaultBaseUnit { get; } = RotationalAccelerationUnit.RadianPerSecondSquared; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for RotationalAcceleration. + public static IEnumerable> GetDefaultMappings() + { + 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, + new QuantityValue(30000000000000000, 3141592653589793) + ); + yield return new (RotationalAccelerationUnit.RevolutionPerSecondSquared, "RevolutionPerSecondSquared", "RevolutionsPerSecondSquared", BaseUnits.Undefined, + new QuantityValue(500000000000000, 3141592653589793) + ); + } + } + + static RotationalAcceleration() + { + Info = UnitsNetSetup.CreateQuantityInfo(RotationalAccelerationInfo.CreateDefault); } /// @@ -89,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; @@ -103,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); @@ -114,110 +163,99 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of RotationalAcceleration, which is RadianPerSecondSquared. All conversions go via this value. /// - public static RotationalAccelerationUnit BaseUnit { get; } + public static RotationalAccelerationUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the RotationalAcceleration quantity. /// - public static RotationalAccelerationUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit RadianPerSecondSquared. /// - public static RotationalAcceleration Zero { get; } - - /// - public static RotationalAcceleration AdditiveIdentity => Zero; + public static RotationalAcceleration Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public RotationalAccelerationUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => RotationalAcceleration.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -246,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); } @@ -254,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); } @@ -262,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); } @@ -270,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); } @@ -281,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); } @@ -342,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); } /// @@ -373,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); } /// @@ -398,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")); /// @@ -406,10 +437,10 @@ public static RotationalAccelerationUnit ParseUnit(string str) /// Error parsing string. public static RotationalAccelerationUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -424,10 +455,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -443,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; } @@ -483,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current RotationalAcceleration. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(RotationalAcceleration), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -576,228 +601,24 @@ public int CompareTo(object? obj) /// public int CompareTo(RotationalAcceleration other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another RotationalAcceleration within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(RotationalAcceleration other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is RotationalAcceleration otherTyped - && (tolerance is RotationalAcceleration toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'RotationalAcceleration'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(RotationalAcceleration other, RotationalAcceleration tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current RotationalAcceleration. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(RotationalAccelerationUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(RotationalAccelerationUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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), - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -812,137 +633,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(RotationalAcceleration)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(RotationalAcceleration)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(RotationalAcceleration)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(RotationalAcceleration)) - return this; - else if (conversionType == typeof(RotationalAccelerationUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return RotationalAcceleration.Info; - else if (conversionType == typeof(BaseDimensions)) - return RotationalAcceleration.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(RotationalAcceleration)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs index f4f8770ec3..9000c08db2 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -52,49 +47,121 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class RotationalSpeedInfo: QuantityInfo + { + /// + public RotationalSpeedInfo(string name, RotationalSpeedUnit baseUnit, IEnumerable> unitMappings, RotationalSpeed zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public RotationalSpeedInfo(string name, RotationalSpeedUnit baseUnit, IEnumerable> unitMappings, RotationalSpeed zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, RotationalSpeed.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.RotationalSpeed", typeof(RotationalSpeed).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the RotationalSpeed quantity. + /// + /// A new instance of the class with the default settings. + public static RotationalSpeedInfo CreateDefault() + { + return new RotationalSpeedInfo(nameof(RotationalSpeed), DefaultBaseUnit, GetDefaultMappings(), new RotationalSpeed(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the RotationalSpeed quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static RotationalSpeedInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new RotationalSpeedInfo(nameof(RotationalSpeed), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new RotationalSpeed(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-1. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); + + /// + /// The default base unit of RotationalSpeed is RadianPerSecond. All conversions, as defined in the , go via this value. + /// + public static RotationalSpeedUnit DefaultBaseUnit { get; } = RotationalSpeedUnit.RadianPerSecond; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for RotationalSpeed. + public static IEnumerable> GetDefaultMappings() + { + 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, + new QuantityValue(30000000000000000, 3141592653589793) + ); + yield return new (RotationalSpeedUnit.RevolutionPerSecond, "RevolutionPerSecond", "RevolutionsPerSecond", BaseUnits.Undefined, + new QuantityValue(500000000000000, 3141592653589793) + ); + } + } + static RotationalSpeed() { - BaseDimensions = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); - BaseUnit = RotationalSpeedUnit.RadianPerSecond; - Units = Enum.GetValues(typeof(RotationalSpeedUnit)).Cast().ToArray(); - Zero = new RotationalSpeed(0, BaseUnit); - Info = new QuantityInfo("RotationalSpeed", - new UnitInfo[] - { - new UnitInfo(RotationalSpeedUnit.CentiradianPerSecond, "CentiradiansPerSecond", BaseUnits.Undefined, "RotationalSpeed"), - new UnitInfo(RotationalSpeedUnit.DeciradianPerSecond, "DeciradiansPerSecond", BaseUnits.Undefined, "RotationalSpeed"), - new UnitInfo(RotationalSpeedUnit.DegreePerMinute, "DegreesPerMinute", BaseUnits.Undefined, "RotationalSpeed"), - new UnitInfo(RotationalSpeedUnit.DegreePerSecond, "DegreesPerSecond", BaseUnits.Undefined, "RotationalSpeed"), - new UnitInfo(RotationalSpeedUnit.MicrodegreePerSecond, "MicrodegreesPerSecond", BaseUnits.Undefined, "RotationalSpeed"), - new UnitInfo(RotationalSpeedUnit.MicroradianPerSecond, "MicroradiansPerSecond", BaseUnits.Undefined, "RotationalSpeed"), - new UnitInfo(RotationalSpeedUnit.MillidegreePerSecond, "MillidegreesPerSecond", BaseUnits.Undefined, "RotationalSpeed"), - new UnitInfo(RotationalSpeedUnit.MilliradianPerSecond, "MilliradiansPerSecond", BaseUnits.Undefined, "RotationalSpeed"), - new UnitInfo(RotationalSpeedUnit.NanodegreePerSecond, "NanodegreesPerSecond", BaseUnits.Undefined, "RotationalSpeed"), - new UnitInfo(RotationalSpeedUnit.NanoradianPerSecond, "NanoradiansPerSecond", BaseUnits.Undefined, "RotationalSpeed"), - new UnitInfo(RotationalSpeedUnit.RadianPerSecond, "RadiansPerSecond", new BaseUnits(time: DurationUnit.Second), "RotationalSpeed"), - new UnitInfo(RotationalSpeedUnit.RevolutionPerMinute, "RevolutionsPerMinute", BaseUnits.Undefined, "RotationalSpeed"), - new UnitInfo(RotationalSpeedUnit.RevolutionPerSecond, "RevolutionsPerSecond", BaseUnits.Undefined, "RotationalSpeed"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(RotationalSpeedInfo.CreateDefault); } /// @@ -102,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; @@ -116,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); @@ -127,173 +194,144 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of RotationalSpeed, which is RadianPerSecond. All conversions go via this value. /// - public static RotationalSpeedUnit BaseUnit { get; } + public static RotationalSpeedUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the RotationalSpeed quantity. /// - public static RotationalSpeedUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit RadianPerSecond. /// - public static RotationalSpeed Zero { get; } - - /// - public static RotationalSpeed AdditiveIdentity => Zero; + public static RotationalSpeed Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public RotationalSpeedUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => RotationalSpeed.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -322,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); } @@ -330,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); } @@ -338,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); } @@ -346,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); } @@ -354,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); } @@ -362,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); } @@ -370,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); } @@ -378,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); } @@ -386,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); } @@ -394,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); } @@ -402,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); } @@ -410,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); } @@ -418,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); } @@ -429,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); } @@ -490,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); } /// @@ -521,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); } /// @@ -546,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")); /// @@ -554,10 +585,10 @@ public static RotationalSpeedUnit ParseUnit(string str) /// Error parsing string. public static RotationalSpeedUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -572,10 +603,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -591,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; } @@ -647,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current RotationalSpeed. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(RotationalSpeed), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -740,246 +765,24 @@ public int CompareTo(object? obj) /// public int CompareTo(RotationalSpeed other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another RotationalSpeed within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(RotationalSpeed other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is RotationalSpeed otherTyped - && (tolerance is RotationalSpeed toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'RotationalSpeed'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(RotationalSpeed other, RotationalSpeed tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current RotationalSpeed. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(RotationalSpeedUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(RotationalSpeedUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -994,137 +797,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(RotationalSpeed)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(RotationalSpeed)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(RotationalSpeed)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(RotationalSpeed)) - return this; - else if (conversionType == typeof(RotationalSpeedUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return RotationalSpeed.Info; - else if (conversionType == typeof(BaseDimensions)) - return RotationalSpeed.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(RotationalSpeed)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.g.cs index 0eae98fef1..ade0d1bdf7 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -53,69 +48,181 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class RotationalStiffnessInfo: QuantityInfo + { + /// + public RotationalStiffnessInfo(string name, RotationalStiffnessUnit baseUnit, IEnumerable> unitMappings, RotationalStiffness zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public RotationalStiffnessInfo(string name, RotationalStiffnessUnit baseUnit, IEnumerable> unitMappings, RotationalStiffness zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, RotationalStiffness.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.RotationalStiffness", typeof(RotationalStiffness).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the RotationalStiffness quantity. + /// + /// A new instance of the class with the default settings. + public static RotationalStiffnessInfo CreateDefault() + { + return new RotationalStiffnessInfo(nameof(RotationalStiffness), DefaultBaseUnit, GetDefaultMappings(), new RotationalStiffness(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the RotationalStiffness quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static RotationalStiffnessInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new RotationalStiffnessInfo(nameof(RotationalStiffness), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new RotationalStiffness(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-2L^2M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); + + /// + /// The default base unit of RotationalStiffness is NewtonMeterPerRadian. All conversions, as defined in the , go via this value. + /// + public static RotationalStiffnessUnit DefaultBaseUnit { get; } = RotationalStiffnessUnit.NewtonMeterPerRadian; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for RotationalStiffness. + public static IEnumerable> GetDefaultMappings() + { + 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, + 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() { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); - BaseUnit = RotationalStiffnessUnit.NewtonMeterPerRadian; - Units = Enum.GetValues(typeof(RotationalStiffnessUnit)).Cast().ToArray(); - Zero = new RotationalStiffness(0, BaseUnit); - Info = new QuantityInfo("RotationalStiffness", - new UnitInfo[] - { - new UnitInfo(RotationalStiffnessUnit.CentinewtonMeterPerDegree, "CentinewtonMetersPerDegree", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, "CentinewtonMillimetersPerDegree", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.CentinewtonMillimeterPerRadian, "CentinewtonMillimetersPerRadian", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.DecanewtonMeterPerDegree, "DecanewtonMetersPerDegree", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, "DecanewtonMillimetersPerDegree", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.DecanewtonMillimeterPerRadian, "DecanewtonMillimetersPerRadian", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.DecinewtonMeterPerDegree, "DecinewtonMetersPerDegree", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, "DecinewtonMillimetersPerDegree", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.DecinewtonMillimeterPerRadian, "DecinewtonMillimetersPerRadian", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.KilonewtonMeterPerDegree, "KilonewtonMetersPerDegree", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.KilonewtonMeterPerRadian, "KilonewtonMetersPerRadian", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, "KilonewtonMillimetersPerDegree", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.KilonewtonMillimeterPerRadian, "KilonewtonMillimetersPerRadian", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.KilopoundForceFootPerDegrees, "KilopoundForceFeetPerDegrees", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.MeganewtonMeterPerDegree, "MeganewtonMetersPerDegree", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.MeganewtonMeterPerRadian, "MeganewtonMetersPerRadian", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, "MeganewtonMillimetersPerDegree", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.MeganewtonMillimeterPerRadian, "MeganewtonMillimetersPerRadian", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.MicronewtonMeterPerDegree, "MicronewtonMetersPerDegree", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, "MicronewtonMillimetersPerDegree", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.MicronewtonMillimeterPerRadian, "MicronewtonMillimetersPerRadian", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.MillinewtonMeterPerDegree, "MillinewtonMetersPerDegree", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, "MillinewtonMillimetersPerDegree", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.MillinewtonMillimeterPerRadian, "MillinewtonMillimetersPerRadian", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.NanonewtonMeterPerDegree, "NanonewtonMetersPerDegree", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, "NanonewtonMillimetersPerDegree", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.NanonewtonMillimeterPerRadian, "NanonewtonMillimetersPerRadian", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.NewtonMeterPerDegree, "NewtonMetersPerDegree", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.NewtonMeterPerRadian, "NewtonMetersPerRadian", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.NewtonMillimeterPerDegree, "NewtonMillimetersPerDegree", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.NewtonMillimeterPerRadian, "NewtonMillimetersPerRadian", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.PoundForceFeetPerRadian, "PoundForceFeetPerRadian", BaseUnits.Undefined, "RotationalStiffness"), - new UnitInfo(RotationalStiffnessUnit.PoundForceFootPerDegrees, "PoundForceFeetPerDegrees", BaseUnits.Undefined, "RotationalStiffness"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(RotationalStiffnessInfo.CreateDefault); } /// @@ -123,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; @@ -137,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); @@ -148,313 +255,244 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of RotationalStiffness, which is NewtonMeterPerRadian. All conversions go via this value. /// - public static RotationalStiffnessUnit BaseUnit { get; } + public static RotationalStiffnessUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the RotationalStiffness quantity. /// - public static RotationalStiffnessUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeterPerRadian. /// - public static RotationalStiffness Zero { get; } - - /// - public static RotationalStiffness AdditiveIdentity => Zero; + public static RotationalStiffness Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public RotationalStiffnessUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => RotationalStiffness.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -483,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); } @@ -491,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); } @@ -499,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); } @@ -507,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); } @@ -515,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); } @@ -523,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); } @@ -531,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); } @@ -539,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); } @@ -547,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); } @@ -555,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); } @@ -563,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); } @@ -571,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); } @@ -579,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); } @@ -587,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); } @@ -595,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); } @@ -603,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); } @@ -611,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); } @@ -619,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); } @@ -627,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); } @@ -635,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); } @@ -643,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); } @@ -651,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); } @@ -659,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); } @@ -667,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); } @@ -675,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); } @@ -683,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); } @@ -691,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); } @@ -699,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); } @@ -707,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); } @@ -715,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); } @@ -723,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); } @@ -731,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); } @@ -739,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); } @@ -750,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); } @@ -811,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); } /// @@ -842,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); } /// @@ -867,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")); /// @@ -875,10 +906,10 @@ public static RotationalStiffnessUnit ParseUnit(string str) /// Error parsing string. public static RotationalStiffnessUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -893,10 +924,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -912,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; } @@ -974,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current RotationalStiffness. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(RotationalStiffness), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -1067,286 +1092,24 @@ public int CompareTo(object? obj) /// public int CompareTo(RotationalStiffness other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another RotationalStiffness within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(RotationalStiffness other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is RotationalStiffness otherTyped - && (tolerance is RotationalStiffness toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'RotationalStiffness'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(RotationalStiffness other, RotationalStiffness tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current RotationalStiffness. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(RotationalStiffnessUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - /// 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 NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } + IQuantity IQuantity.ToUnit(RotationalStiffnessUnit unit) => this.ToUnit(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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(RotationalStiffnessUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1361,137 +1124,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(RotationalStiffness)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(RotationalStiffness)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(RotationalStiffness)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(RotationalStiffness)) - return this; - else if (conversionType == typeof(RotationalStiffnessUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return RotationalStiffness.Info; - else if (conversionType == typeof(BaseDimensions)) - return RotationalStiffness.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(RotationalStiffness)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs index 47df1e4037..6ef5f5b80e 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -51,41 +46,97 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static RotationalStiffnessPerLength() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class RotationalStiffnessPerLengthInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(1, 1, -2, 0, 0, 0, 0); - BaseUnit = RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter; - Units = Enum.GetValues(typeof(RotationalStiffnessPerLengthUnit)).Cast().ToArray(); - Zero = new RotationalStiffnessPerLength(0, BaseUnit); - Info = new QuantityInfo("RotationalStiffnessPerLength", - new UnitInfo[] - { - new UnitInfo(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, "KilonewtonMetersPerRadianPerMeter", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "RotationalStiffnessPerLength"), - new UnitInfo(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, "KilopoundForceFeetPerDegreesPerFeet", BaseUnits.Undefined, "RotationalStiffnessPerLength"), - new UnitInfo(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, "MeganewtonMetersPerRadianPerMeter", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "RotationalStiffnessPerLength"), - new UnitInfo(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, "NewtonMetersPerRadianPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "RotationalStiffnessPerLength"), - new UnitInfo(RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot, "PoundForceFeetPerDegreesPerFeet", BaseUnits.Undefined, "RotationalStiffnessPerLength"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public RotationalStiffnessPerLengthInfo(string name, RotationalStiffnessPerLengthUnit baseUnit, IEnumerable> unitMappings, RotationalStiffnessPerLength zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public RotationalStiffnessPerLengthInfo(string name, RotationalStiffnessPerLengthUnit baseUnit, IEnumerable> unitMappings, RotationalStiffnessPerLength zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, RotationalStiffnessPerLength.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.RotationalStiffnessPerLength", typeof(RotationalStiffnessPerLength).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the RotationalStiffnessPerLength quantity. + /// + /// A new instance of the class with the default settings. + public static RotationalStiffnessPerLengthInfo CreateDefault() + { + return new RotationalStiffnessPerLengthInfo(nameof(RotationalStiffnessPerLength), DefaultBaseUnit, GetDefaultMappings(), new RotationalStiffnessPerLength(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the RotationalStiffnessPerLength quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static RotationalStiffnessPerLengthInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new RotationalStiffnessPerLengthInfo(nameof(RotationalStiffnessPerLength), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new RotationalStiffnessPerLength(0, DefaultBaseUnit), DefaultBaseDimensions); + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// The for is T^-2LM. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, 1, -2, 0, 0, 0, 0); + + /// + /// The default base unit of RotationalStiffnessPerLength is NewtonMeterPerRadianPerMeter. All conversions, as defined in the , go via this value. + /// + public static RotationalStiffnessPerLengthUnit DefaultBaseUnit { get; } = RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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, + new QuantityValue(3141592653589793, 800679890746890000) + ); + } + } + + static RotationalStiffnessPerLength() + { + Info = UnitsNetSetup.CreateQuantityInfo(RotationalStiffnessPerLengthInfo.CreateDefault); } /// @@ -93,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; @@ -107,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); @@ -118,117 +169,104 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of RotationalStiffnessPerLength, which is NewtonMeterPerRadianPerMeter. All conversions go via this value. /// - public static RotationalStiffnessPerLengthUnit BaseUnit { get; } + public static RotationalStiffnessPerLengthUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the RotationalStiffnessPerLength quantity. /// - public static RotationalStiffnessPerLengthUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeterPerRadianPerMeter. /// - public static RotationalStiffnessPerLength Zero { get; } - - /// - public static RotationalStiffnessPerLength AdditiveIdentity => Zero; + public static RotationalStiffnessPerLength Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public RotationalStiffnessPerLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => RotationalStiffnessPerLength.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -257,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); } @@ -265,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); } @@ -273,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); } @@ -281,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); } @@ -289,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); } @@ -300,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); } @@ -361,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); } /// @@ -392,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); } /// @@ -417,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")); /// @@ -425,10 +456,10 @@ public static RotationalStiffnessPerLengthUnit ParseUnit(string str) /// Error parsing string. public static RotationalStiffnessPerLengthUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -443,10 +474,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -462,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; } @@ -512,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current RotationalStiffnessPerLength. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(RotationalStiffnessPerLength), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -605,230 +630,24 @@ public int CompareTo(object? obj) /// public int CompareTo(RotationalStiffnessPerLength other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another RotationalStiffnessPerLength within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(RotationalStiffnessPerLength other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is RotationalStiffnessPerLength otherTyped - && (tolerance is RotationalStiffnessPerLength toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'RotationalStiffnessPerLength'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(RotationalStiffnessPerLength other, RotationalStiffnessPerLength tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current RotationalStiffnessPerLength. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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)); + #region Conversion Methods (explicit implementations for netstandard2.0) - 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 RotationalStiffnessPerLengthUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalStiffnessPerLengthUnit)} 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(RotationalStiffnessPerLengthUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(RotationalStiffnessPerLengthUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -843,137 +662,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(RotationalStiffnessPerLength)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(RotationalStiffnessPerLength)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(RotationalStiffnessPerLength)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(RotationalStiffnessPerLength)) - return this; - else if (conversionType == typeof(RotationalStiffnessPerLengthUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return RotationalStiffnessPerLength.Info; - else if (conversionType == typeof(BaseDimensions)) - return RotationalStiffnessPerLength.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(RotationalStiffnessPerLength)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Scalar.g.cs b/UnitsNet/GeneratedCode/Quantities/Scalar.g.cs index 3c5bdc3153..19e8114f28 100644 --- a/UnitsNet/GeneratedCode/Quantities/Scalar.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Scalar.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -48,37 +43,85 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static Scalar() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ScalarInfo: QuantityInfo { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = ScalarUnit.Amount; - Units = Enum.GetValues(typeof(ScalarUnit)).Cast().ToArray(); - Zero = new Scalar(0, BaseUnit); - Info = new QuantityInfo("Scalar", - new UnitInfo[] - { - new UnitInfo(ScalarUnit.Amount, "Amount", BaseUnits.Undefined, "Scalar"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public ScalarInfo(string name, ScalarUnit baseUnit, IEnumerable> unitMappings, Scalar zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ScalarInfo(string name, ScalarUnit baseUnit, IEnumerable> unitMappings, Scalar zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Scalar.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Scalar", typeof(Scalar).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the Scalar quantity. + /// + /// A new instance of the class with the default settings. + public static ScalarInfo CreateDefault() + { + return new ScalarInfo(nameof(Scalar), DefaultBaseUnit, GetDefaultMappings(), new Scalar(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Scalar quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ScalarInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ScalarInfo(nameof(Scalar), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Scalar(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is . + /// + public static BaseDimensions DefaultBaseDimensions { get; } = BaseDimensions.Dimensionless; + + /// + /// The default base unit of Scalar is Amount. All conversions, as defined in the , go via this value. + /// + public static ScalarUnit DefaultBaseUnit { get; } = ScalarUnit.Amount; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Scalar. + public static IEnumerable> GetDefaultMappings() + { + yield return new (ScalarUnit.Amount, "Amount", "Amount", BaseUnits.Undefined); + } + } + + static Scalar() + { + Info = UnitsNetSetup.CreateQuantityInfo(ScalarInfo.CreateDefault); } /// @@ -86,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; @@ -97,88 +140,83 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Scalar, which is Amount. All conversions go via this value. /// - public static ScalarUnit BaseUnit { get; } + public static ScalarUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Scalar quantity. /// - public static ScalarUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Amount. /// - public static Scalar Zero { get; } - - /// - public static Scalar AdditiveIdentity => Zero; + public static Scalar Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ScalarUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Scalar.BaseDimensions; - #endregion + #region Explicit implementations - #region Conversion Properties + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); - /// - /// Gets a value of this quantity converted into - /// - public double Amount => As(ScalarUnit.Amount); + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif #endregion - #region Static Methods + #endregion + + #region Conversion Properties /// - /// Registers the default conversion functions in the given instance. + /// Gets a value of this quantity converted into /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ScalarUnit -> BaseUnit + public QuantityValue Amount => this.As(ScalarUnit.Amount); - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ScalarUnit.Amount, ScalarUnit.Amount, quantity => quantity); + #endregion - // Register in unit converter: BaseUnit -> ScalarUnit - } + #region Static Methods /// /// Get unit abbreviation string. @@ -208,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); } @@ -219,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); } @@ -280,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); } /// @@ -311,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); } /// @@ -336,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")); /// @@ -344,10 +375,10 @@ public static ScalarUnit ParseUnit(string str) /// Error parsing string. public static ScalarUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -362,10 +393,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -381,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; } @@ -421,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Scalar. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Scalar), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -514,222 +539,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Scalar other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Scalar within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Scalar other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Scalar otherTyped - && (tolerance is Scalar toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Scalar'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Scalar other, Scalar tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Scalar. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(ScalarUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(ScalarUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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 - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -744,137 +571,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Scalar)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Scalar)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Scalar)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Scalar)) - return this; - else if (conversionType == typeof(ScalarUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Scalar.Info; - else if (conversionType == typeof(BaseDimensions)) - return Scalar.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Scalar)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs b/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs index d9579a9bec..754e1f26e5 100644 --- a/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,37 +46,85 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static SolidAngle() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class SolidAngleInfo: QuantityInfo { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = SolidAngleUnit.Steradian; - Units = Enum.GetValues(typeof(SolidAngleUnit)).Cast().ToArray(); - Zero = new SolidAngle(0, BaseUnit); - Info = new QuantityInfo("SolidAngle", - new UnitInfo[] - { - new UnitInfo(SolidAngleUnit.Steradian, "Steradians", BaseUnits.Undefined, "SolidAngle"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public SolidAngleInfo(string name, SolidAngleUnit baseUnit, IEnumerable> unitMappings, SolidAngle zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public SolidAngleInfo(string name, SolidAngleUnit baseUnit, IEnumerable> unitMappings, SolidAngle zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, SolidAngle.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.SolidAngle", typeof(SolidAngle).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the SolidAngle quantity. + /// + /// A new instance of the class with the default settings. + public static SolidAngleInfo CreateDefault() + { + return new SolidAngleInfo(nameof(SolidAngle), DefaultBaseUnit, GetDefaultMappings(), new SolidAngle(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the SolidAngle quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static SolidAngleInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new SolidAngleInfo(nameof(SolidAngle), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new SolidAngle(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is . + /// + public static BaseDimensions DefaultBaseDimensions { get; } = BaseDimensions.Dimensionless; + + /// + /// The default base unit of SolidAngle is Steradian. All conversions, as defined in the , go via this value. + /// + public static SolidAngleUnit DefaultBaseUnit { get; } = SolidAngleUnit.Steradian; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for SolidAngle. + public static IEnumerable> GetDefaultMappings() + { + yield return new (SolidAngleUnit.Steradian, "Steradian", "Steradians", BaseUnits.Undefined); + } + } + + static SolidAngle() + { + Info = UnitsNetSetup.CreateQuantityInfo(SolidAngleInfo.CreateDefault); } /// @@ -89,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; @@ -100,88 +143,83 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of SolidAngle, which is Steradian. All conversions go via this value. /// - public static SolidAngleUnit BaseUnit { get; } + public static SolidAngleUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the SolidAngle quantity. /// - public static SolidAngleUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Steradian. /// - public static SolidAngle Zero { get; } - - /// - public static SolidAngle AdditiveIdentity => Zero; + public static SolidAngle Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public SolidAngleUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => SolidAngle.BaseDimensions; - #endregion + #region Explicit implementations - #region Conversion Properties + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); - /// - /// Gets a value of this quantity converted into - /// - public double Steradians => As(SolidAngleUnit.Steradian); + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif #endregion - #region Static Methods + #endregion + + #region Conversion Properties /// - /// Registers the default conversion functions in the given instance. + /// Gets a value of this quantity converted into /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: SolidAngleUnit -> BaseUnit + public QuantityValue Steradians => this.As(SolidAngleUnit.Steradian); - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(SolidAngleUnit.Steradian, SolidAngleUnit.Steradian, quantity => quantity); + #endregion - // Register in unit converter: BaseUnit -> SolidAngleUnit - } + #region Static Methods /// /// Get unit abbreviation string. @@ -211,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); } @@ -222,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); } @@ -283,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); } /// @@ -314,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); } /// @@ -339,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")); /// @@ -347,10 +378,10 @@ public static SolidAngleUnit ParseUnit(string str) /// Error parsing string. public static SolidAngleUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -365,10 +396,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -384,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; } @@ -424,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current SolidAngle. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(SolidAngle), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -517,222 +542,24 @@ public int CompareTo(object? obj) /// public int CompareTo(SolidAngle other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another SolidAngle within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(SolidAngle other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is SolidAngle otherTyped - && (tolerance is SolidAngle toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'SolidAngle'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(SolidAngle other, SolidAngle tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current SolidAngle. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(SolidAngleUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(SolidAngleUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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 - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -747,137 +574,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(SolidAngle)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(SolidAngle)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(SolidAngle)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(SolidAngle)) - return this; - else if (conversionType == typeof(SolidAngleUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return SolidAngle.Info; - else if (conversionType == typeof(BaseDimensions)) - return SolidAngle.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(SolidAngle)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs index 11780f7631..0ad2a6dafa 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,7 +46,7 @@ namespace UnitsNet IDivisionOperators, IDivisionOperators, IDivisionOperators, - IMultiplyOperators, + IMultiplyOperators, #endif #if NET7_0_OR_GREATER IComparisonOperators, @@ -59,66 +54,172 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class SpecificEnergyInfo: QuantityInfo + { + /// + public SpecificEnergyInfo(string name, SpecificEnergyUnit baseUnit, IEnumerable> unitMappings, SpecificEnergy zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public SpecificEnergyInfo(string name, SpecificEnergyUnit baseUnit, IEnumerable> unitMappings, SpecificEnergy zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, SpecificEnergy.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.SpecificEnergy", typeof(SpecificEnergy).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the SpecificEnergy quantity. + /// + /// A new instance of the class with the default settings. + public static SpecificEnergyInfo CreateDefault() + { + return new SpecificEnergyInfo(nameof(SpecificEnergy), DefaultBaseUnit, GetDefaultMappings(), new SpecificEnergy(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the SpecificEnergy quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static SpecificEnergyInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new SpecificEnergyInfo(nameof(SpecificEnergy), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new SpecificEnergy(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-2L^2. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 0, -2, 0, 0, 0, 0); + + /// + /// The default base unit of SpecificEnergy is JoulePerKilogram. All conversions, as defined in the , go via this value. + /// + public static SpecificEnergyUnit DefaultBaseUnit { get; } = SpecificEnergyUnit.JoulePerKilogram; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for SpecificEnergy. + public static IEnumerable> GetDefaultMappings() + { + 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, + 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() { - BaseDimensions = new BaseDimensions(2, 0, -2, 0, 0, 0, 0); - BaseUnit = SpecificEnergyUnit.JoulePerKilogram; - Units = Enum.GetValues(typeof(SpecificEnergyUnit)).Cast().ToArray(); - Zero = new SpecificEnergy(0, BaseUnit); - Info = new QuantityInfo("SpecificEnergy", - new UnitInfo[] - { - new UnitInfo(SpecificEnergyUnit.BtuPerPound, "BtuPerPound", BaseUnits.Undefined, "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.CaloriePerGram, "CaloriesPerGram", BaseUnits.Undefined, "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.GigawattDayPerKilogram, "GigawattDaysPerKilogram", BaseUnits.Undefined, "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.GigawattDayPerShortTon, "GigawattDaysPerShortTon", BaseUnits.Undefined, "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.GigawattDayPerTonne, "GigawattDaysPerTonne", BaseUnits.Undefined, "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.GigawattHourPerKilogram, "GigawattHoursPerKilogram", BaseUnits.Undefined, "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.GigawattHourPerPound, "GigawattHoursPerPound", BaseUnits.Undefined, "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.JoulePerKilogram, "JoulesPerKilogram", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second), "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.KilocaloriePerGram, "KilocaloriesPerGram", BaseUnits.Undefined, "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.KilojoulePerKilogram, "KilojoulesPerKilogram", BaseUnits.Undefined, "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.KilowattDayPerKilogram, "KilowattDaysPerKilogram", BaseUnits.Undefined, "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.KilowattDayPerShortTon, "KilowattDaysPerShortTon", BaseUnits.Undefined, "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.KilowattDayPerTonne, "KilowattDaysPerTonne", BaseUnits.Undefined, "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.KilowattHourPerKilogram, "KilowattHoursPerKilogram", BaseUnits.Undefined, "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.KilowattHourPerPound, "KilowattHoursPerPound", BaseUnits.Undefined, "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.MegajoulePerKilogram, "MegajoulesPerKilogram", new BaseUnits(length: LengthUnit.Kilometer, time: DurationUnit.Second), "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.MegaJoulePerTonne, "MegaJoulesPerTonne", BaseUnits.Undefined, "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.MegawattDayPerKilogram, "MegawattDaysPerKilogram", BaseUnits.Undefined, "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.MegawattDayPerShortTon, "MegawattDaysPerShortTon", BaseUnits.Undefined, "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.MegawattDayPerTonne, "MegawattDaysPerTonne", BaseUnits.Undefined, "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.MegawattHourPerKilogram, "MegawattHoursPerKilogram", BaseUnits.Undefined, "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.MegawattHourPerPound, "MegawattHoursPerPound", BaseUnits.Undefined, "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.TerawattDayPerKilogram, "TerawattDaysPerKilogram", BaseUnits.Undefined, "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.TerawattDayPerShortTon, "TerawattDaysPerShortTon", BaseUnits.Undefined, "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.TerawattDayPerTonne, "TerawattDaysPerTonne", BaseUnits.Undefined, "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.WattDayPerKilogram, "WattDaysPerKilogram", BaseUnits.Undefined, "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.WattDayPerShortTon, "WattDaysPerShortTon", BaseUnits.Undefined, "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.WattDayPerTonne, "WattDaysPerTonne", BaseUnits.Undefined, "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.WattHourPerKilogram, "WattHoursPerKilogram", BaseUnits.Undefined, "SpecificEnergy"), - new UnitInfo(SpecificEnergyUnit.WattHourPerPound, "WattHoursPerPound", BaseUnits.Undefined, "SpecificEnergy"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(SpecificEnergyInfo.CreateDefault); } /// @@ -126,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; @@ -140,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); @@ -151,292 +252,229 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of SpecificEnergy, which is JoulePerKilogram. All conversions go via this value. /// - public static SpecificEnergyUnit BaseUnit { get; } + public static SpecificEnergyUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the SpecificEnergy quantity. /// - public static SpecificEnergyUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerKilogram. /// - public static SpecificEnergy Zero { get; } - - /// - public static SpecificEnergy AdditiveIdentity => Zero; + public static SpecificEnergy Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public SpecificEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => SpecificEnergy.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -465,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); } @@ -473,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); } @@ -481,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); } @@ -489,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); } @@ -497,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); } @@ -505,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); } @@ -513,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); } @@ -521,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); } @@ -529,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); } @@ -537,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); } @@ -545,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); } @@ -553,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); } @@ -561,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); } @@ -569,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); } @@ -577,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); } @@ -585,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); } @@ -593,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); } @@ -601,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); } @@ -609,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); } @@ -617,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); } @@ -625,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); } @@ -633,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); } @@ -641,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); } @@ -649,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); } @@ -657,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); } @@ -665,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); } @@ -673,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); } @@ -681,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); } @@ -689,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); } @@ -697,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); } @@ -708,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); } @@ -769,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); } /// @@ -800,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); } /// @@ -825,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")); /// @@ -833,10 +864,10 @@ public static SpecificEnergyUnit ParseUnit(string str) /// Error parsing string. public static SpecificEnergyUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -851,10 +882,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -870,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; } @@ -907,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); } @@ -943,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; } @@ -956,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current SpecificEnergy. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(SpecificEnergy), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -1049,280 +1074,24 @@ public int CompareTo(object? obj) /// public int CompareTo(SpecificEnergy other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another SpecificEnergy within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(SpecificEnergy other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is SpecificEnergy otherTyped - && (tolerance is SpecificEnergy toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'SpecificEnergy'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(SpecificEnergy other, SpecificEnergy tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current SpecificEnergy. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(SpecificEnergyUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - /// 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 NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } + IQuantity IQuantity.ToUnit(SpecificEnergyUnit unit) => this.ToUnit(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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(SpecificEnergyUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1337,137 +1106,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(SpecificEnergy)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(SpecificEnergy)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(SpecificEnergy)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(SpecificEnergy)) - return this; - else if (conversionType == typeof(SpecificEnergyUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return SpecificEnergy.Info; - else if (conversionType == typeof(BaseDimensions)) - return SpecificEnergy.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(SpecificEnergy)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs index 803bb51c14..0f15e79dd6 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -52,45 +47,109 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class SpecificEntropyInfo: QuantityInfo + { + /// + public SpecificEntropyInfo(string name, SpecificEntropyUnit baseUnit, IEnumerable> unitMappings, SpecificEntropy zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public SpecificEntropyInfo(string name, SpecificEntropyUnit baseUnit, IEnumerable> unitMappings, SpecificEntropy zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, SpecificEntropy.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.SpecificEntropy", typeof(SpecificEntropy).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the SpecificEntropy quantity. + /// + /// A new instance of the class with the default settings. + public static SpecificEntropyInfo CreateDefault() + { + return new SpecificEntropyInfo(nameof(SpecificEntropy), DefaultBaseUnit, GetDefaultMappings(), new SpecificEntropy(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the SpecificEntropy quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static SpecificEntropyInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new SpecificEntropyInfo(nameof(SpecificEntropy), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new SpecificEntropy(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-2L^2Θ^-1. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 0, -2, 0, -1, 0, 0); + + /// + /// The default base unit of SpecificEntropy is JoulePerKilogramKelvin. All conversions, as defined in the , go via this value. + /// + public static SpecificEntropyUnit DefaultBaseUnit { get; } = SpecificEntropyUnit.JoulePerKilogramKelvin; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for SpecificEntropy. + public static IEnumerable> GetDefaultMappings() + { + 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, + 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() { - BaseDimensions = new BaseDimensions(2, 0, -2, 0, -1, 0, 0); - BaseUnit = SpecificEntropyUnit.JoulePerKilogramKelvin; - Units = Enum.GetValues(typeof(SpecificEntropyUnit)).Cast().ToArray(); - Zero = new SpecificEntropy(0, BaseUnit); - Info = new QuantityInfo("SpecificEntropy", - new UnitInfo[] - { - new UnitInfo(SpecificEntropyUnit.BtuPerPoundFahrenheit, "BtusPerPoundFahrenheit", BaseUnits.Undefined, "SpecificEntropy"), - new UnitInfo(SpecificEntropyUnit.CaloriePerGramKelvin, "CaloriesPerGramKelvin", BaseUnits.Undefined, "SpecificEntropy"), - new UnitInfo(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius, "JoulesPerKilogramDegreeCelsius", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius), "SpecificEntropy"), - new UnitInfo(SpecificEntropyUnit.JoulePerKilogramKelvin, "JoulesPerKilogramKelvin", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin), "SpecificEntropy"), - new UnitInfo(SpecificEntropyUnit.KilocaloriePerGramKelvin, "KilocaloriesPerGramKelvin", BaseUnits.Undefined, "SpecificEntropy"), - new UnitInfo(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius, "KilojoulesPerKilogramDegreeCelsius", BaseUnits.Undefined, "SpecificEntropy"), - new UnitInfo(SpecificEntropyUnit.KilojoulePerKilogramKelvin, "KilojoulesPerKilogramKelvin", BaseUnits.Undefined, "SpecificEntropy"), - new UnitInfo(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius, "MegajoulesPerKilogramDegreeCelsius", new BaseUnits(length: LengthUnit.Kilometer, time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius), "SpecificEntropy"), - new UnitInfo(SpecificEntropyUnit.MegajoulePerKilogramKelvin, "MegajoulesPerKilogramKelvin", new BaseUnits(length: LengthUnit.Kilometer, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin), "SpecificEntropy"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(SpecificEntropyInfo.CreateDefault); } /// @@ -98,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; @@ -112,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); @@ -123,145 +182,124 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of SpecificEntropy, which is JoulePerKilogramKelvin. All conversions go via this value. /// - public static SpecificEntropyUnit BaseUnit { get; } + public static SpecificEntropyUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the SpecificEntropy quantity. /// - public static SpecificEntropyUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerKilogramKelvin. /// - public static SpecificEntropy Zero { get; } - - /// - public static SpecificEntropy AdditiveIdentity => Zero; + public static SpecificEntropy Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public SpecificEntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => SpecificEntropy.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -290,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); } @@ -298,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); } @@ -306,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); } @@ -314,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); } @@ -322,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); } @@ -330,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); } @@ -338,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); } @@ -346,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); } @@ -354,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); } @@ -365,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); } @@ -426,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); } /// @@ -457,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); } /// @@ -482,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")); /// @@ -490,10 +521,10 @@ public static SpecificEntropyUnit ParseUnit(string str) /// Error parsing string. public static SpecificEntropyUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -508,10 +539,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -527,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; } @@ -583,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current SpecificEntropy. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(SpecificEntropy), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -676,238 +701,24 @@ public int CompareTo(object? obj) /// public int CompareTo(SpecificEntropy other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another SpecificEntropy within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(SpecificEntropy other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is SpecificEntropy otherTyped - && (tolerance is SpecificEntropy toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'SpecificEntropy'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(SpecificEntropy other, SpecificEntropy tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current SpecificEntropy. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(SpecificEntropyUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(SpecificEntropyUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -922,137 +733,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(SpecificEntropy)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(SpecificEntropy)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(SpecificEntropy)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(SpecificEntropy)) - return this; - else if (conversionType == typeof(SpecificEntropyUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return SpecificEntropy.Info; - else if (conversionType == typeof(BaseDimensions)) - return SpecificEntropy.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(SpecificEntropy)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs index 276f6e83e5..709e159ae2 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,40 +46,94 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static SpecificFuelConsumption() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class SpecificFuelConsumptionInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(-1, 0, 1, 0, 0, 0, 0); - BaseUnit = SpecificFuelConsumptionUnit.GramPerKilonewtonSecond; - Units = Enum.GetValues(typeof(SpecificFuelConsumptionUnit)).Cast().ToArray(); - Zero = new SpecificFuelConsumption(0, BaseUnit); - Info = new QuantityInfo("SpecificFuelConsumption", - new UnitInfo[] - { - new UnitInfo(SpecificFuelConsumptionUnit.GramPerKilonewtonSecond, "GramsPerKilonewtonSecond", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second), "SpecificFuelConsumption"), - new UnitInfo(SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, "KilogramsPerKilogramForceHour", BaseUnits.Undefined, "SpecificFuelConsumption"), - new UnitInfo(SpecificFuelConsumptionUnit.KilogramPerKilonewtonSecond, "KilogramsPerKilonewtonSecond", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Second), "SpecificFuelConsumption"), - new UnitInfo(SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour, "PoundsMassPerPoundForceHour", BaseUnits.Undefined, "SpecificFuelConsumption"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public SpecificFuelConsumptionInfo(string name, SpecificFuelConsumptionUnit baseUnit, IEnumerable> unitMappings, SpecificFuelConsumption zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public SpecificFuelConsumptionInfo(string name, SpecificFuelConsumptionUnit baseUnit, IEnumerable> unitMappings, SpecificFuelConsumption zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, SpecificFuelConsumption.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.SpecificFuelConsumption", typeof(SpecificFuelConsumption).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the SpecificFuelConsumption quantity. + /// + /// A new instance of the class with the default settings. + public static SpecificFuelConsumptionInfo CreateDefault() + { + return new SpecificFuelConsumptionInfo(nameof(SpecificFuelConsumption), DefaultBaseUnit, GetDefaultMappings(), new SpecificFuelConsumption(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the SpecificFuelConsumption quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static SpecificFuelConsumptionInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new SpecificFuelConsumptionInfo(nameof(SpecificFuelConsumption), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new SpecificFuelConsumption(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is TL^-1. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-1, 0, 1, 0, 0, 0, 0); + + /// + /// The default base unit of SpecificFuelConsumption is GramPerKilonewtonSecond. All conversions, as defined in the , go via this value. + /// + public static SpecificFuelConsumptionUnit DefaultBaseUnit { get; } = SpecificFuelConsumptionUnit.GramPerKilonewtonSecond; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for SpecificFuelConsumption. + public static IEnumerable> 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, + 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 = UnitsNetSetup.CreateQuantityInfo(SpecificFuelConsumptionInfo.CreateDefault); } /// @@ -92,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; @@ -106,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); @@ -117,110 +166,99 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of SpecificFuelConsumption, which is GramPerKilonewtonSecond. All conversions go via this value. /// - public static SpecificFuelConsumptionUnit BaseUnit { get; } + public static SpecificFuelConsumptionUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the SpecificFuelConsumption quantity. /// - public static SpecificFuelConsumptionUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit GramPerKilonewtonSecond. /// - public static SpecificFuelConsumption Zero { get; } - - /// - public static SpecificFuelConsumption AdditiveIdentity => Zero; + public static SpecificFuelConsumption Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public SpecificFuelConsumptionUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => SpecificFuelConsumption.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -249,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); } @@ -257,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); } @@ -265,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); } @@ -273,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); } @@ -284,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); } @@ -345,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); } /// @@ -376,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); } /// @@ -401,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")); /// @@ -409,10 +440,10 @@ public static SpecificFuelConsumptionUnit ParseUnit(string str) /// Error parsing string. public static SpecificFuelConsumptionUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -427,10 +458,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -446,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; } @@ -486,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current SpecificFuelConsumption. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(SpecificFuelConsumption), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -579,228 +604,24 @@ public int CompareTo(object? obj) /// public int CompareTo(SpecificFuelConsumption other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another SpecificFuelConsumption within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(SpecificFuelConsumption other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is SpecificFuelConsumption otherTyped - && (tolerance is SpecificFuelConsumption toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'SpecificFuelConsumption'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(SpecificFuelConsumption other, SpecificFuelConsumption tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current SpecificFuelConsumption. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(SpecificFuelConsumptionUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(SpecificFuelConsumptionUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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), - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -815,137 +636,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(SpecificFuelConsumption)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(SpecificFuelConsumption)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(SpecificFuelConsumption)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(SpecificFuelConsumption)) - return this; - else if (conversionType == typeof(SpecificFuelConsumptionUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return SpecificFuelConsumption.Info; - else if (conversionType == typeof(BaseDimensions)) - return SpecificFuelConsumption.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(SpecificFuelConsumption)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs index b65942490f..5e048206c3 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -51,39 +46,91 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static SpecificVolume() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class SpecificVolumeInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(3, -1, 0, 0, 0, 0, 0); - BaseUnit = SpecificVolumeUnit.CubicMeterPerKilogram; - Units = Enum.GetValues(typeof(SpecificVolumeUnit)).Cast().ToArray(); - Zero = new SpecificVolume(0, BaseUnit); - Info = new QuantityInfo("SpecificVolume", - new UnitInfo[] - { - new UnitInfo(SpecificVolumeUnit.CubicFootPerPound, "CubicFeetPerPound", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Pound), "SpecificVolume"), - new UnitInfo(SpecificVolumeUnit.CubicMeterPerKilogram, "CubicMetersPerKilogram", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram), "SpecificVolume"), - new UnitInfo(SpecificVolumeUnit.MillicubicMeterPerKilogram, "MillicubicMetersPerKilogram", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilogram), "SpecificVolume"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public SpecificVolumeInfo(string name, SpecificVolumeUnit baseUnit, IEnumerable> unitMappings, SpecificVolume zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public SpecificVolumeInfo(string name, SpecificVolumeUnit baseUnit, IEnumerable> unitMappings, SpecificVolume zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, SpecificVolume.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.SpecificVolume", typeof(SpecificVolume).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the SpecificVolume quantity. + /// + /// A new instance of the class with the default settings. + public static SpecificVolumeInfo CreateDefault() + { + return new SpecificVolumeInfo(nameof(SpecificVolume), DefaultBaseUnit, GetDefaultMappings(), new SpecificVolume(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the SpecificVolume quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static SpecificVolumeInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new SpecificVolumeInfo(nameof(SpecificVolume), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new SpecificVolume(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is L^3M^-1. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(3, -1, 0, 0, 0, 0, 0); + + /// + /// The default base unit of SpecificVolume is CubicMeterPerKilogram. All conversions, as defined in the , go via this value. + /// + public static SpecificVolumeUnit DefaultBaseUnit { get; } = SpecificVolumeUnit.CubicMeterPerKilogram; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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), + 1000 + ); + } + } + + static SpecificVolume() + { + Info = UnitsNetSetup.CreateQuantityInfo(SpecificVolumeInfo.CreateDefault); } /// @@ -91,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; @@ -105,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); @@ -116,103 +163,94 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of SpecificVolume, which is CubicMeterPerKilogram. All conversions go via this value. /// - public static SpecificVolumeUnit BaseUnit { get; } + public static SpecificVolumeUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the SpecificVolume quantity. /// - public static SpecificVolumeUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeterPerKilogram. /// - public static SpecificVolume Zero { get; } - - /// - public static SpecificVolume AdditiveIdentity => Zero; + public static SpecificVolume Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public SpecificVolumeUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => SpecificVolume.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -241,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); } @@ -249,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); } @@ -257,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); } @@ -268,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); } @@ -329,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); } /// @@ -360,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); } /// @@ -385,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")); /// @@ -393,10 +424,10 @@ public static SpecificVolumeUnit ParseUnit(string str) /// Error parsing string. public static SpecificVolumeUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -411,10 +442,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -430,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; } @@ -471,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 * . @@ -487,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current SpecificVolume. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(SpecificVolume), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -580,226 +605,24 @@ public int CompareTo(object? obj) /// public int CompareTo(SpecificVolume other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another SpecificVolume within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(SpecificVolume other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is SpecificVolume otherTyped - && (tolerance is SpecificVolume toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'SpecificVolume'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(SpecificVolume other, SpecificVolume tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current SpecificVolume. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(SpecificVolumeUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(SpecificVolumeUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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), - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -814,137 +637,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(SpecificVolume)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(SpecificVolume)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(SpecificVolume)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(SpecificVolume)) - return this; - else if (conversionType == typeof(SpecificVolumeUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return SpecificVolume.Info; - else if (conversionType == typeof(BaseDimensions)) - return SpecificVolume.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(SpecificVolume)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs index ad707ea084..3df1654766 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,7 +36,8 @@ namespace UnitsNet /// http://en.wikipedia.org/wiki/Specificweight /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct SpecificWeight : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -57,53 +52,133 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class SpecificWeightInfo: QuantityInfo + { + /// + public SpecificWeightInfo(string name, SpecificWeightUnit baseUnit, IEnumerable> unitMappings, SpecificWeight zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public SpecificWeightInfo(string name, SpecificWeightUnit baseUnit, IEnumerable> unitMappings, SpecificWeight zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, SpecificWeight.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.SpecificWeight", typeof(SpecificWeight).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the SpecificWeight quantity. + /// + /// A new instance of the class with the default settings. + public static SpecificWeightInfo CreateDefault() + { + return new SpecificWeightInfo(nameof(SpecificWeight), DefaultBaseUnit, GetDefaultMappings(), new SpecificWeight(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the SpecificWeight quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static SpecificWeightInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new SpecificWeightInfo(nameof(SpecificWeight), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new SpecificWeight(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-2L^-2M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, 1, -2, 0, 0, 0, 0); + + /// + /// The default base unit of SpecificWeight is NewtonPerCubicMeter. All conversions, as defined in the , go via this value. + /// + public static SpecificWeightUnit DefaultBaseUnit { get; } = SpecificWeightUnit.NewtonPerCubicMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for SpecificWeight. + public static IEnumerable> GetDefaultMappings() + { + 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, + 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() { - BaseDimensions = new BaseDimensions(-2, 1, -2, 0, 0, 0, 0); - BaseUnit = SpecificWeightUnit.NewtonPerCubicMeter; - Units = Enum.GetValues(typeof(SpecificWeightUnit)).Cast().ToArray(); - Zero = new SpecificWeight(0, BaseUnit); - Info = new QuantityInfo("SpecificWeight", - new UnitInfo[] - { - new UnitInfo(SpecificWeightUnit.KilogramForcePerCubicCentimeter, "KilogramsForcePerCubicCentimeter", BaseUnits.Undefined, "SpecificWeight"), - new UnitInfo(SpecificWeightUnit.KilogramForcePerCubicMeter, "KilogramsForcePerCubicMeter", BaseUnits.Undefined, "SpecificWeight"), - new UnitInfo(SpecificWeightUnit.KilogramForcePerCubicMillimeter, "KilogramsForcePerCubicMillimeter", BaseUnits.Undefined, "SpecificWeight"), - new UnitInfo(SpecificWeightUnit.KilonewtonPerCubicCentimeter, "KilonewtonsPerCubicCentimeter", BaseUnits.Undefined, "SpecificWeight"), - new UnitInfo(SpecificWeightUnit.KilonewtonPerCubicMeter, "KilonewtonsPerCubicMeter", BaseUnits.Undefined, "SpecificWeight"), - new UnitInfo(SpecificWeightUnit.KilonewtonPerCubicMillimeter, "KilonewtonsPerCubicMillimeter", BaseUnits.Undefined, "SpecificWeight"), - new UnitInfo(SpecificWeightUnit.KilopoundForcePerCubicFoot, "KilopoundsForcePerCubicFoot", BaseUnits.Undefined, "SpecificWeight"), - new UnitInfo(SpecificWeightUnit.KilopoundForcePerCubicInch, "KilopoundsForcePerCubicInch", BaseUnits.Undefined, "SpecificWeight"), - new UnitInfo(SpecificWeightUnit.MeganewtonPerCubicMeter, "MeganewtonsPerCubicMeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "SpecificWeight"), - new UnitInfo(SpecificWeightUnit.NewtonPerCubicCentimeter, "NewtonsPerCubicCentimeter", BaseUnits.Undefined, "SpecificWeight"), - new UnitInfo(SpecificWeightUnit.NewtonPerCubicMeter, "NewtonsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "SpecificWeight"), - new UnitInfo(SpecificWeightUnit.NewtonPerCubicMillimeter, "NewtonsPerCubicMillimeter", BaseUnits.Undefined, "SpecificWeight"), - new UnitInfo(SpecificWeightUnit.PoundForcePerCubicFoot, "PoundsForcePerCubicFoot", BaseUnits.Undefined, "SpecificWeight"), - new UnitInfo(SpecificWeightUnit.PoundForcePerCubicInch, "PoundsForcePerCubicInch", BaseUnits.Undefined, "SpecificWeight"), - new UnitInfo(SpecificWeightUnit.TonneForcePerCubicCentimeter, "TonnesForcePerCubicCentimeter", BaseUnits.Undefined, "SpecificWeight"), - new UnitInfo(SpecificWeightUnit.TonneForcePerCubicMeter, "TonnesForcePerCubicMeter", BaseUnits.Undefined, "SpecificWeight"), - new UnitInfo(SpecificWeightUnit.TonneForcePerCubicMillimeter, "TonnesForcePerCubicMillimeter", BaseUnits.Undefined, "SpecificWeight"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(SpecificWeightInfo.CreateDefault); } /// @@ -111,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; @@ -125,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); @@ -136,201 +211,164 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of SpecificWeight, which is NewtonPerCubicMeter. All conversions go via this value. /// - public static SpecificWeightUnit BaseUnit { get; } + public static SpecificWeightUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the SpecificWeight quantity. /// - public static SpecificWeightUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit NewtonPerCubicMeter. /// - public static SpecificWeight Zero { get; } - - /// - public static SpecificWeight AdditiveIdentity => Zero; + public static SpecificWeight Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public SpecificWeightUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => SpecificWeight.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -359,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); } @@ -367,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); } @@ -375,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); } @@ -383,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); } @@ -391,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); } @@ -399,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); } @@ -407,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); } @@ -415,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); } @@ -423,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); } @@ -431,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); } @@ -439,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); } @@ -447,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); } @@ -455,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); } @@ -463,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); } @@ -471,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); } @@ -479,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); } @@ -487,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); } @@ -498,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); } @@ -559,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); } /// @@ -590,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); } /// @@ -615,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")); /// @@ -623,10 +654,10 @@ public static SpecificWeightUnit ParseUnit(string str) /// Error parsing string. public static SpecificWeightUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -641,10 +672,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -660,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; } @@ -728,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current SpecificWeight. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(SpecificWeight), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -821,254 +846,24 @@ public int CompareTo(object? obj) /// public int CompareTo(SpecificWeight other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another SpecificWeight within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(SpecificWeight other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is SpecificWeight otherTyped - && (tolerance is SpecificWeight toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'SpecificWeight'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(SpecificWeight other, SpecificWeight tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current SpecificWeight. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(SpecificWeightUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(SpecificWeightUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(SpecificWeightUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1083,137 +878,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(SpecificWeight)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(SpecificWeight)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(SpecificWeight)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(SpecificWeight)) - return this; - else if (conversionType == typeof(SpecificWeightUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return SpecificWeight.Info; - else if (conversionType == typeof(BaseDimensions)) - return SpecificWeight.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(SpecificWeight)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Speed.g.cs b/UnitsNet/GeneratedCode/Quantities/Speed.g.cs index db7c424f76..0f8f92c5bf 100644 --- a/UnitsNet/GeneratedCode/Quantities/Speed.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Speed.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -58,69 +53,181 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class SpeedInfo: QuantityInfo + { + /// + public SpeedInfo(string name, SpeedUnit baseUnit, IEnumerable> unitMappings, Speed zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public SpeedInfo(string name, SpeedUnit baseUnit, IEnumerable> unitMappings, Speed zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Speed.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Speed", typeof(Speed).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Speed quantity. + /// + /// A new instance of the class with the default settings. + public static SpeedInfo CreateDefault() + { + return new SpeedInfo(nameof(Speed), DefaultBaseUnit, GetDefaultMappings(), new Speed(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Speed quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static SpeedInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new SpeedInfo(nameof(Speed), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Speed(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-1L. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, 0, -1, 0, 0, 0, 0); + + /// + /// The default base unit of Speed is MeterPerSecond. All conversions, as defined in the , go via this value. + /// + public static SpeedUnit DefaultBaseUnit { get; } = SpeedUnit.MeterPerSecond; + + /// + /// Retrieves the default mappings for . + /// + /// 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), + 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), + 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() { - BaseDimensions = new BaseDimensions(1, 0, -1, 0, 0, 0, 0); - BaseUnit = SpeedUnit.MeterPerSecond; - Units = Enum.GetValues(typeof(SpeedUnit)).Cast().ToArray(); - Zero = new Speed(0, BaseUnit); - Info = new QuantityInfo("Speed", - new UnitInfo[] - { - new UnitInfo(SpeedUnit.CentimeterPerHour, "CentimetersPerHour", new BaseUnits(length: LengthUnit.Centimeter, time: DurationUnit.Hour), "Speed"), - new UnitInfo(SpeedUnit.CentimeterPerMinute, "CentimetersPerMinute", new BaseUnits(length: LengthUnit.Centimeter, time: DurationUnit.Minute), "Speed"), - new UnitInfo(SpeedUnit.CentimeterPerSecond, "CentimetersPerSecond", new BaseUnits(length: LengthUnit.Centimeter, time: DurationUnit.Second), "Speed"), - new UnitInfo(SpeedUnit.DecimeterPerMinute, "DecimetersPerMinute", new BaseUnits(length: LengthUnit.Decimeter, time: DurationUnit.Minute), "Speed"), - new UnitInfo(SpeedUnit.DecimeterPerSecond, "DecimetersPerSecond", new BaseUnits(length: LengthUnit.Decimeter, time: DurationUnit.Second), "Speed"), - new UnitInfo(SpeedUnit.FootPerHour, "FeetPerHour", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Hour), "Speed"), - new UnitInfo(SpeedUnit.FootPerMinute, "FeetPerMinute", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Minute), "Speed"), - new UnitInfo(SpeedUnit.FootPerSecond, "FeetPerSecond", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Second), "Speed"), - new UnitInfo(SpeedUnit.InchPerHour, "InchesPerHour", new BaseUnits(length: LengthUnit.Inch, time: DurationUnit.Hour), "Speed"), - new UnitInfo(SpeedUnit.InchPerMinute, "InchesPerMinute", new BaseUnits(length: LengthUnit.Inch, time: DurationUnit.Minute), "Speed"), - new UnitInfo(SpeedUnit.InchPerSecond, "InchesPerSecond", new BaseUnits(length: LengthUnit.Inch, time: DurationUnit.Second), "Speed"), - new UnitInfo(SpeedUnit.KilometerPerHour, "KilometersPerHour", new BaseUnits(length: LengthUnit.Kilometer, time: DurationUnit.Hour), "Speed"), - new UnitInfo(SpeedUnit.KilometerPerMinute, "KilometersPerMinute", new BaseUnits(length: LengthUnit.Kilometer, time: DurationUnit.Minute), "Speed"), - new UnitInfo(SpeedUnit.KilometerPerSecond, "KilometersPerSecond", new BaseUnits(length: LengthUnit.Kilometer, time: DurationUnit.Second), "Speed"), - new UnitInfo(SpeedUnit.Knot, "Knots", new BaseUnits(length: LengthUnit.NauticalMile, time: DurationUnit.Hour), "Speed"), - new UnitInfo(SpeedUnit.Mach, "Mach", BaseUnits.Undefined, "Speed"), - new UnitInfo(SpeedUnit.MeterPerHour, "MetersPerHour", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Hour), "Speed"), - new UnitInfo(SpeedUnit.MeterPerMinute, "MetersPerMinute", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Minute), "Speed"), - new UnitInfo(SpeedUnit.MeterPerSecond, "MetersPerSecond", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second), "Speed"), - new UnitInfo(SpeedUnit.MicrometerPerMinute, "MicrometersPerMinute", new BaseUnits(length: LengthUnit.Micrometer, time: DurationUnit.Minute), "Speed"), - new UnitInfo(SpeedUnit.MicrometerPerSecond, "MicrometersPerSecond", new BaseUnits(length: LengthUnit.Micrometer, time: DurationUnit.Second), "Speed"), - new UnitInfo(SpeedUnit.MilePerHour, "MilesPerHour", new BaseUnits(length: LengthUnit.Mile, time: DurationUnit.Hour), "Speed"), - new UnitInfo(SpeedUnit.MillimeterPerHour, "MillimetersPerHour", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Hour), "Speed"), - new UnitInfo(SpeedUnit.MillimeterPerMinute, "MillimetersPerMinute", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Minute), "Speed"), - new UnitInfo(SpeedUnit.MillimeterPerSecond, "MillimetersPerSecond", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Second), "Speed"), - new UnitInfo(SpeedUnit.NanometerPerMinute, "NanometersPerMinute", new BaseUnits(length: LengthUnit.Nanometer, time: DurationUnit.Minute), "Speed"), - new UnitInfo(SpeedUnit.NanometerPerSecond, "NanometersPerSecond", new BaseUnits(length: LengthUnit.Nanometer, time: DurationUnit.Second), "Speed"), - new UnitInfo(SpeedUnit.UsSurveyFootPerHour, "UsSurveyFeetPerHour", new BaseUnits(length: LengthUnit.UsSurveyFoot, time: DurationUnit.Hour), "Speed"), - new UnitInfo(SpeedUnit.UsSurveyFootPerMinute, "UsSurveyFeetPerMinute", new BaseUnits(length: LengthUnit.UsSurveyFoot, time: DurationUnit.Minute), "Speed"), - new UnitInfo(SpeedUnit.UsSurveyFootPerSecond, "UsSurveyFeetPerSecond", new BaseUnits(length: LengthUnit.UsSurveyFoot, time: DurationUnit.Second), "Speed"), - new UnitInfo(SpeedUnit.YardPerHour, "YardsPerHour", new BaseUnits(length: LengthUnit.Yard, time: DurationUnit.Hour), "Speed"), - new UnitInfo(SpeedUnit.YardPerMinute, "YardsPerMinute", new BaseUnits(length: LengthUnit.Yard, time: DurationUnit.Minute), "Speed"), - new UnitInfo(SpeedUnit.YardPerSecond, "YardsPerSecond", new BaseUnits(length: LengthUnit.Yard, time: DurationUnit.Second), "Speed"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(SpeedInfo.CreateDefault); } /// @@ -128,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; @@ -142,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); @@ -153,313 +260,244 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Speed, which is MeterPerSecond. All conversions go via this value. /// - public static SpeedUnit BaseUnit { get; } + public static SpeedUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Speed quantity. /// - public static SpeedUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit MeterPerSecond. /// - public static Speed Zero { get; } - - /// - public static Speed AdditiveIdentity => Zero; + public static Speed Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public SpeedUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Speed.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -488,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); } @@ -496,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); } @@ -504,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); } @@ -512,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); } @@ -520,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); } @@ -528,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); } @@ -536,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); } @@ -544,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); } @@ -552,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); } @@ -560,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); } @@ -568,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); } @@ -576,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); } @@ -584,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); } @@ -592,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); } @@ -600,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); } @@ -608,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); } @@ -616,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); } @@ -624,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); } @@ -632,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); } @@ -640,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); } @@ -648,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); } @@ -656,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); } @@ -664,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); } @@ -672,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); } @@ -680,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); } @@ -688,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); } @@ -696,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); } @@ -704,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); } @@ -712,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); } @@ -720,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); } @@ -728,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); } @@ -736,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); } @@ -744,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); } @@ -755,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); } @@ -816,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); } /// @@ -847,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); } /// @@ -872,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")); /// @@ -880,10 +911,10 @@ public static SpeedUnit ParseUnit(string str) /// Error parsing string. public static SpeedUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -898,10 +929,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -917,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; } @@ -1009,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Speed. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Speed), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -1102,286 +1127,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Speed other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Speed within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Speed other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Speed otherTyped - && (tolerance is Speed toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Speed'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Speed other, Speed tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Speed. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(SpeedUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - /// 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 NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } + IQuantity IQuantity.ToUnit(SpeedUnit unit) => this.ToUnit(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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(SpeedUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1396,137 +1159,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Speed)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Speed)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Speed)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Speed)) - return this; - else if (conversionType == typeof(SpeedUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Speed.Info; - else if (conversionType == typeof(BaseDimensions)) - return Speed.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Speed)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/StandardVolumeFlow.g.cs b/UnitsNet/GeneratedCode/Quantities/StandardVolumeFlow.g.cs index 82a30f53e4..69382cc626 100644 --- a/UnitsNet/GeneratedCode/Quantities/StandardVolumeFlow.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/StandardVolumeFlow.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -48,45 +43,109 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class StandardVolumeFlowInfo: QuantityInfo + { + /// + public StandardVolumeFlowInfo(string name, StandardVolumeFlowUnit baseUnit, IEnumerable> unitMappings, StandardVolumeFlow zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public StandardVolumeFlowInfo(string name, StandardVolumeFlowUnit baseUnit, IEnumerable> unitMappings, StandardVolumeFlow zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, StandardVolumeFlow.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.StandardVolumeFlow", typeof(StandardVolumeFlow).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the StandardVolumeFlow quantity. + /// + /// A new instance of the class with the default settings. + public static StandardVolumeFlowInfo CreateDefault() + { + return new StandardVolumeFlowInfo(nameof(StandardVolumeFlow), DefaultBaseUnit, GetDefaultMappings(), new StandardVolumeFlow(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the StandardVolumeFlow quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static StandardVolumeFlowInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new StandardVolumeFlowInfo(nameof(StandardVolumeFlow), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new StandardVolumeFlow(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-1M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 1, -1, 0, 0, 0, 0); + + /// + /// The default base unit of StandardVolumeFlow is StandardCubicMeterPerSecond. All conversions, as defined in the , go via this value. + /// + public static StandardVolumeFlowUnit DefaultBaseUnit { get; } = StandardVolumeFlowUnit.StandardCubicMeterPerSecond; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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), + 60000 + ); + } + } + static StandardVolumeFlow() { - BaseDimensions = new BaseDimensions(0, 1, -1, 0, 0, 0, 0); - BaseUnit = StandardVolumeFlowUnit.StandardCubicMeterPerSecond; - Units = Enum.GetValues(typeof(StandardVolumeFlowUnit)).Cast().ToArray(); - Zero = new StandardVolumeFlow(0, BaseUnit); - Info = new QuantityInfo("StandardVolumeFlow", - new UnitInfo[] - { - new UnitInfo(StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute, "StandardCubicCentimetersPerMinute", new BaseUnits(length: LengthUnit.Centimeter, time: DurationUnit.Minute), "StandardVolumeFlow"), - new UnitInfo(StandardVolumeFlowUnit.StandardCubicFootPerHour, "StandardCubicFeetPerHour", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Hour), "StandardVolumeFlow"), - new UnitInfo(StandardVolumeFlowUnit.StandardCubicFootPerMinute, "StandardCubicFeetPerMinute", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Minute), "StandardVolumeFlow"), - new UnitInfo(StandardVolumeFlowUnit.StandardCubicFootPerSecond, "StandardCubicFeetPerSecond", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Second), "StandardVolumeFlow"), - new UnitInfo(StandardVolumeFlowUnit.StandardCubicMeterPerDay, "StandardCubicMetersPerDay", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Day), "StandardVolumeFlow"), - new UnitInfo(StandardVolumeFlowUnit.StandardCubicMeterPerHour, "StandardCubicMetersPerHour", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Hour), "StandardVolumeFlow"), - new UnitInfo(StandardVolumeFlowUnit.StandardCubicMeterPerMinute, "StandardCubicMetersPerMinute", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Minute), "StandardVolumeFlow"), - new UnitInfo(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, "StandardCubicMetersPerSecond", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second), "StandardVolumeFlow"), - new UnitInfo(StandardVolumeFlowUnit.StandardLiterPerMinute, "StandardLitersPerMinute", new BaseUnits(length: LengthUnit.Decimeter, time: DurationUnit.Minute), "StandardVolumeFlow"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(StandardVolumeFlowInfo.CreateDefault); } /// @@ -94,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; @@ -108,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); @@ -119,145 +178,124 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of StandardVolumeFlow, which is StandardCubicMeterPerSecond. All conversions go via this value. /// - public static StandardVolumeFlowUnit BaseUnit { get; } + public static StandardVolumeFlowUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the StandardVolumeFlow quantity. /// - public static StandardVolumeFlowUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit StandardCubicMeterPerSecond. /// - public static StandardVolumeFlow Zero { get; } - - /// - public static StandardVolumeFlow AdditiveIdentity => Zero; + public static StandardVolumeFlow Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public StandardVolumeFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => StandardVolumeFlow.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -286,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); } @@ -294,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); } @@ -302,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); } @@ -310,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); } @@ -318,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); } @@ -326,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); } @@ -334,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); } @@ -342,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); } @@ -350,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); } @@ -361,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); } @@ -422,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); } /// @@ -453,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); } /// @@ -478,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")); /// @@ -486,10 +517,10 @@ public static StandardVolumeFlowUnit ParseUnit(string str) /// Error parsing string. public static StandardVolumeFlowUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -504,10 +535,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -523,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; } @@ -563,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current StandardVolumeFlow. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(StandardVolumeFlow), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -656,238 +681,24 @@ public int CompareTo(object? obj) /// public int CompareTo(StandardVolumeFlow other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another StandardVolumeFlow within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(StandardVolumeFlow other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is StandardVolumeFlow otherTyped - && (tolerance is StandardVolumeFlow toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'StandardVolumeFlow'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(StandardVolumeFlow other, StandardVolumeFlow tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current StandardVolumeFlow. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(StandardVolumeFlowUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(StandardVolumeFlowUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -902,137 +713,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(StandardVolumeFlow)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(StandardVolumeFlow)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(StandardVolumeFlow)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(StandardVolumeFlow)) - return this; - else if (conversionType == typeof(StandardVolumeFlowUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return StandardVolumeFlow.Info; - else if (conversionType == typeof(BaseDimensions)) - return StandardVolumeFlow.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(StandardVolumeFlow)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs b/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs index a98def59ea..f9592de401 100644 --- a/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,55 +33,129 @@ 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 : - IQuantity, + IAffineQuantity, #if NET7_0_OR_GREATER IComparisonOperators, IParsable, #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class TemperatureInfo: QuantityInfo + { + /// + public TemperatureInfo(string name, TemperatureUnit baseUnit, IEnumerable> unitMappings, Temperature zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public TemperatureInfo(string name, TemperatureUnit baseUnit, IEnumerable> unitMappings, Temperature zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Temperature.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Temperature", typeof(Temperature).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Temperature quantity. + /// + /// A new instance of the class with the default settings. + public static TemperatureInfo CreateDefault() + { + return new TemperatureInfo(nameof(Temperature), DefaultBaseUnit, GetDefaultMappings(), new Temperature(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Temperature quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static TemperatureInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new TemperatureInfo(nameof(Temperature), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Temperature(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is Θ. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, 0, 0, 1, 0, 0); + + /// + /// The default base unit of Temperature is Kelvin. All conversions, as defined in the , go via this value. + /// + public static TemperatureUnit DefaultBaseUnit { get; } = TemperatureUnit.Kelvin; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Temperature. + public static IEnumerable> GetDefaultMappings() + { + 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), + 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() { - BaseDimensions = new BaseDimensions(0, 0, 0, 0, 1, 0, 0); - BaseUnit = TemperatureUnit.Kelvin; - Units = Enum.GetValues(typeof(TemperatureUnit)).Cast().ToArray(); - Zero = new Temperature(0, BaseUnit); - Info = new QuantityInfo("Temperature", - new UnitInfo[] - { - new UnitInfo(TemperatureUnit.DegreeCelsius, "DegreesCelsius", new BaseUnits(temperature: TemperatureUnit.DegreeCelsius), "Temperature"), - new UnitInfo(TemperatureUnit.DegreeDelisle, "DegreesDelisle", new BaseUnits(temperature: TemperatureUnit.DegreeDelisle), "Temperature"), - new UnitInfo(TemperatureUnit.DegreeFahrenheit, "DegreesFahrenheit", new BaseUnits(temperature: TemperatureUnit.DegreeFahrenheit), "Temperature"), - new UnitInfo(TemperatureUnit.DegreeNewton, "DegreesNewton", new BaseUnits(temperature: TemperatureUnit.DegreeNewton), "Temperature"), - new UnitInfo(TemperatureUnit.DegreeRankine, "DegreesRankine", new BaseUnits(temperature: TemperatureUnit.DegreeRankine), "Temperature"), - new UnitInfo(TemperatureUnit.DegreeReaumur, "DegreesReaumur", new BaseUnits(temperature: TemperatureUnit.DegreeReaumur), "Temperature"), - new UnitInfo(TemperatureUnit.DegreeRoemer, "DegreesRoemer", new BaseUnits(temperature: TemperatureUnit.DegreeRoemer), "Temperature"), - new UnitInfo(TemperatureUnit.Kelvin, "Kelvins", new BaseUnits(temperature: TemperatureUnit.Kelvin), "Temperature"), - new UnitInfo(TemperatureUnit.MillidegreeCelsius, "MillidegreesCelsius", new BaseUnits(temperature: TemperatureUnit.MillidegreeCelsius), "Temperature"), - new UnitInfo(TemperatureUnit.SolarTemperature, "SolarTemperatures", new BaseUnits(temperature: TemperatureUnit.SolarTemperature), "Temperature"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(TemperatureInfo.CreateDefault); } /// @@ -95,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; @@ -109,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); @@ -120,149 +188,129 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Temperature, which is Kelvin. All conversions go via this value. /// - public static TemperatureUnit BaseUnit { get; } + public static TemperatureUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Temperature quantity. /// - public static TemperatureUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Kelvin. /// - public static Temperature Zero { get; } + public static Temperature Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public TemperatureUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Temperature.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -291,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); } @@ -299,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); } @@ -307,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); } @@ -315,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); } @@ -323,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); } @@ -331,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); } @@ -339,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); } @@ -347,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); } @@ -355,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); } @@ -363,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); } @@ -374,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); } @@ -435,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); } /// @@ -466,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); } /// @@ -491,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")); /// @@ -499,10 +540,10 @@ public static TemperatureUnit ParseUnit(string str) /// Error parsing string. public static TemperatureUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -517,10 +558,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -530,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Temperature. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Temperature), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -623,240 +658,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Temperature other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Temperature within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Temperature other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Temperature otherTyped - && (tolerance is Temperature toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Temperature'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Temperature other, Temperature tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Temperature. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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; - } + #region Conversion Methods (explicit implementations for netstandard2.0) - converted = convertedOrNull.Value; - return true; - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - public Temperature ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(TemperatureUnit unit) => this.ToUnit(unit); - /// - 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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(TemperatureUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -871,137 +690,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Temperature)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Temperature)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Temperature)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Temperature)) - return this; - else if (conversionType == typeof(TemperatureUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Temperature.Info; - else if (conversionType == typeof(BaseDimensions)) - return Temperature.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Temperature)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs index d386589bc4..6043dd3784 100644 --- a/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -51,53 +46,133 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class TemperatureChangeRateInfo: QuantityInfo + { + /// + public TemperatureChangeRateInfo(string name, TemperatureChangeRateUnit baseUnit, IEnumerable> unitMappings, TemperatureChangeRate zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public TemperatureChangeRateInfo(string name, TemperatureChangeRateUnit baseUnit, IEnumerable> unitMappings, TemperatureChangeRate zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, TemperatureChangeRate.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.TemperatureChangeRate", typeof(TemperatureChangeRate).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the TemperatureChangeRate quantity. + /// + /// A new instance of the class with the default settings. + public static TemperatureChangeRateInfo CreateDefault() + { + return new TemperatureChangeRateInfo(nameof(TemperatureChangeRate), DefaultBaseUnit, GetDefaultMappings(), new TemperatureChangeRate(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the TemperatureChangeRate quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static TemperatureChangeRateInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new TemperatureChangeRateInfo(nameof(TemperatureChangeRate), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new TemperatureChangeRate(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-1Θ. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, -1, 0, 1, 0, 0); + + /// + /// The default base unit of TemperatureChangeRate is DegreeCelsiusPerSecond. All conversions, as defined in the , go via this value. + /// + public static TemperatureChangeRateUnit DefaultBaseUnit { get; } = TemperatureChangeRateUnit.DegreeCelsiusPerSecond; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for TemperatureChangeRate. + public static IEnumerable> GetDefaultMappings() + { + 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), + 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() { - BaseDimensions = new BaseDimensions(0, 0, -1, 0, 1, 0, 0); - BaseUnit = TemperatureChangeRateUnit.DegreeCelsiusPerSecond; - Units = Enum.GetValues(typeof(TemperatureChangeRateUnit)).Cast().ToArray(); - Zero = new TemperatureChangeRate(0, BaseUnit); - Info = new QuantityInfo("TemperatureChangeRate", - new UnitInfo[] - { - new UnitInfo(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond, "CentidegreesCelsiusPerSecond", BaseUnits.Undefined, "TemperatureChangeRate"), - new UnitInfo(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond, "DecadegreesCelsiusPerSecond", BaseUnits.Undefined, "TemperatureChangeRate"), - new UnitInfo(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond, "DecidegreesCelsiusPerSecond", BaseUnits.Undefined, "TemperatureChangeRate"), - new UnitInfo(TemperatureChangeRateUnit.DegreeCelsiusPerHour, "DegreesCelsiusPerHour", new BaseUnits(time: DurationUnit.Hour, temperature: TemperatureUnit.DegreeCelsius), "TemperatureChangeRate"), - new UnitInfo(TemperatureChangeRateUnit.DegreeCelsiusPerMinute, "DegreesCelsiusPerMinute", new BaseUnits(time: DurationUnit.Minute, temperature: TemperatureUnit.DegreeCelsius), "TemperatureChangeRate"), - new UnitInfo(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, "DegreesCelsiusPerSecond", new BaseUnits(time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius), "TemperatureChangeRate"), - new UnitInfo(TemperatureChangeRateUnit.DegreeFahrenheitPerHour, "DegreesFahrenheitPerHour", new BaseUnits(time: DurationUnit.Hour, temperature: TemperatureUnit.DegreeFahrenheit), "TemperatureChangeRate"), - new UnitInfo(TemperatureChangeRateUnit.DegreeFahrenheitPerMinute, "DegreesFahrenheitPerMinute", new BaseUnits(time: DurationUnit.Minute, temperature: TemperatureUnit.DegreeFahrenheit), "TemperatureChangeRate"), - new UnitInfo(TemperatureChangeRateUnit.DegreeFahrenheitPerSecond, "DegreesFahrenheitPerSecond", new BaseUnits(time: DurationUnit.Second, temperature: TemperatureUnit.DegreeFahrenheit), "TemperatureChangeRate"), - new UnitInfo(TemperatureChangeRateUnit.DegreeKelvinPerHour, "DegreesKelvinPerHour", new BaseUnits(time: DurationUnit.Hour, temperature: TemperatureUnit.Kelvin), "TemperatureChangeRate"), - new UnitInfo(TemperatureChangeRateUnit.DegreeKelvinPerMinute, "DegreesKelvinPerMinute", new BaseUnits(time: DurationUnit.Minute, temperature: TemperatureUnit.Kelvin), "TemperatureChangeRate"), - new UnitInfo(TemperatureChangeRateUnit.DegreeKelvinPerSecond, "DegreesKelvinPerSecond", new BaseUnits(time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin), "TemperatureChangeRate"), - new UnitInfo(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond, "HectodegreesCelsiusPerSecond", BaseUnits.Undefined, "TemperatureChangeRate"), - new UnitInfo(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond, "KilodegreesCelsiusPerSecond", new BaseUnits(time: DurationUnit.Millisecond, temperature: TemperatureUnit.DegreeCelsius), "TemperatureChangeRate"), - new UnitInfo(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond, "MicrodegreesCelsiusPerSecond", BaseUnits.Undefined, "TemperatureChangeRate"), - new UnitInfo(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond, "MillidegreesCelsiusPerSecond", BaseUnits.Undefined, "TemperatureChangeRate"), - new UnitInfo(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, "NanodegreesCelsiusPerSecond", BaseUnits.Undefined, "TemperatureChangeRate"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(TemperatureChangeRateInfo.CreateDefault); } /// @@ -105,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; @@ -119,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); @@ -130,201 +205,164 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of TemperatureChangeRate, which is DegreeCelsiusPerSecond. All conversions go via this value. /// - public static TemperatureChangeRateUnit BaseUnit { get; } + public static TemperatureChangeRateUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the TemperatureChangeRate quantity. /// - public static TemperatureChangeRateUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit DegreeCelsiusPerSecond. /// - public static TemperatureChangeRate Zero { get; } - - /// - public static TemperatureChangeRate AdditiveIdentity => Zero; + public static TemperatureChangeRate Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public TemperatureChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => TemperatureChangeRate.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -353,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); } @@ -361,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); } @@ -369,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); } @@ -377,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); } @@ -385,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); } @@ -393,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); } @@ -401,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); } @@ -409,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); } @@ -417,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); } @@ -425,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); } @@ -433,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); } @@ -441,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); } @@ -449,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); } @@ -457,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); } @@ -465,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); } @@ -473,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); } @@ -481,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); } @@ -492,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); } @@ -553,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); } /// @@ -584,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); } /// @@ -609,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")); /// @@ -617,10 +648,10 @@ public static TemperatureChangeRateUnit ParseUnit(string str) /// Error parsing string. public static TemperatureChangeRateUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -635,10 +666,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -654,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; } @@ -704,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current TemperatureChangeRate. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(TemperatureChangeRate), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -797,254 +822,24 @@ public int CompareTo(object? obj) /// public int CompareTo(TemperatureChangeRate other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another TemperatureChangeRate within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(TemperatureChangeRate other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is TemperatureChangeRate otherTyped - && (tolerance is TemperatureChangeRate toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'TemperatureChangeRate'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(TemperatureChangeRate other, TemperatureChangeRate tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current TemperatureChangeRate. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(TemperatureChangeRateUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(TemperatureChangeRateUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(TemperatureChangeRateUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1059,137 +854,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(TemperatureChangeRate)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(TemperatureChangeRate)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(TemperatureChangeRate)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(TemperatureChangeRate)) - return this; - else if (conversionType == typeof(TemperatureChangeRateUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return TemperatureChangeRate.Info; - else if (conversionType == typeof(BaseDimensions)) - return TemperatureChangeRate.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(TemperatureChangeRate)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs b/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs index 0a02aca388..a2bd1f79f1 100644 --- a/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -57,45 +52,109 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class TemperatureDeltaInfo: QuantityInfo + { + /// + public TemperatureDeltaInfo(string name, TemperatureDeltaUnit baseUnit, IEnumerable> unitMappings, TemperatureDelta zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public TemperatureDeltaInfo(string name, TemperatureDeltaUnit baseUnit, IEnumerable> unitMappings, TemperatureDelta zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, TemperatureDelta.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.TemperatureDelta", typeof(TemperatureDelta).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the TemperatureDelta quantity. + /// + /// A new instance of the class with the default settings. + public static TemperatureDeltaInfo CreateDefault() + { + return new TemperatureDeltaInfo(nameof(TemperatureDelta), DefaultBaseUnit, GetDefaultMappings(), new TemperatureDelta(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the TemperatureDelta quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static TemperatureDeltaInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new TemperatureDeltaInfo(nameof(TemperatureDelta), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new TemperatureDelta(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is Θ. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, 0, 0, 1, 0, 0); + + /// + /// The default base unit of TemperatureDelta is Kelvin. All conversions, as defined in the , go via this value. + /// + public static TemperatureDeltaUnit DefaultBaseUnit { get; } = TemperatureDeltaUnit.Kelvin; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for TemperatureDelta. + public static IEnumerable> GetDefaultMappings() + { + 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, + 1000 + ); + } + } + static TemperatureDelta() { - BaseDimensions = new BaseDimensions(0, 0, 0, 0, 1, 0, 0); - BaseUnit = TemperatureDeltaUnit.Kelvin; - Units = Enum.GetValues(typeof(TemperatureDeltaUnit)).Cast().ToArray(); - Zero = new TemperatureDelta(0, BaseUnit); - Info = new QuantityInfo("TemperatureDelta", - new UnitInfo[] - { - new UnitInfo(TemperatureDeltaUnit.DegreeCelsius, "DegreesCelsius", new BaseUnits(temperature: TemperatureUnit.DegreeCelsius), "TemperatureDelta"), - new UnitInfo(TemperatureDeltaUnit.DegreeDelisle, "DegreesDelisle", new BaseUnits(temperature: TemperatureUnit.DegreeDelisle), "TemperatureDelta"), - new UnitInfo(TemperatureDeltaUnit.DegreeFahrenheit, "DegreesFahrenheit", new BaseUnits(temperature: TemperatureUnit.DegreeFahrenheit), "TemperatureDelta"), - new UnitInfo(TemperatureDeltaUnit.DegreeNewton, "DegreesNewton", new BaseUnits(temperature: TemperatureUnit.DegreeNewton), "TemperatureDelta"), - new UnitInfo(TemperatureDeltaUnit.DegreeRankine, "DegreesRankine", new BaseUnits(temperature: TemperatureUnit.DegreeRankine), "TemperatureDelta"), - new UnitInfo(TemperatureDeltaUnit.DegreeReaumur, "DegreesReaumur", new BaseUnits(temperature: TemperatureUnit.DegreeReaumur), "TemperatureDelta"), - new UnitInfo(TemperatureDeltaUnit.DegreeRoemer, "DegreesRoemer", new BaseUnits(temperature: TemperatureUnit.DegreeRoemer), "TemperatureDelta"), - new UnitInfo(TemperatureDeltaUnit.Kelvin, "Kelvins", new BaseUnits(temperature: TemperatureUnit.Kelvin), "TemperatureDelta"), - new UnitInfo(TemperatureDeltaUnit.MillidegreeCelsius, "MillidegreesCelsius", BaseUnits.Undefined, "TemperatureDelta"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(TemperatureDeltaInfo.CreateDefault); } /// @@ -103,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; @@ -117,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); @@ -128,145 +187,124 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of TemperatureDelta, which is Kelvin. All conversions go via this value. /// - public static TemperatureDeltaUnit BaseUnit { get; } + public static TemperatureDeltaUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the TemperatureDelta quantity. /// - public static TemperatureDeltaUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit Kelvin. /// - public static TemperatureDelta Zero { get; } - - /// - public static TemperatureDelta AdditiveIdentity => Zero; + public static TemperatureDelta Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public TemperatureDeltaUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => TemperatureDelta.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -295,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); } @@ -303,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); } @@ -311,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); } @@ -319,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); } @@ -327,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); } @@ -335,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); } @@ -343,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); } @@ -351,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); } @@ -359,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); } @@ -370,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); } @@ -431,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); } /// @@ -462,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); } /// @@ -487,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")); /// @@ -495,10 +526,10 @@ public static TemperatureDeltaUnit ParseUnit(string str) /// Error parsing string. public static TemperatureDeltaUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -513,10 +544,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -532,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; } @@ -618,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current TemperatureDelta. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(TemperatureDelta), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -711,238 +736,24 @@ public int CompareTo(object? obj) /// public int CompareTo(TemperatureDelta other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another TemperatureDelta within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(TemperatureDelta other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is TemperatureDelta otherTyped - && (tolerance is TemperatureDelta toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'TemperatureDelta'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(TemperatureDelta other, TemperatureDelta tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current TemperatureDelta. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(TemperatureDeltaUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(TemperatureDeltaUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -957,137 +768,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(TemperatureDelta)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(TemperatureDelta)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(TemperatureDelta)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(TemperatureDelta)) - return this; - else if (conversionType == typeof(TemperatureDeltaUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return TemperatureDelta.Info; - else if (conversionType == typeof(BaseDimensions)) - return TemperatureDelta.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(TemperatureDelta)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/TemperatureGradient.g.cs b/UnitsNet/GeneratedCode/Quantities/TemperatureGradient.g.cs index 02afa3cd6f..73854f2e59 100644 --- a/UnitsNet/GeneratedCode/Quantities/TemperatureGradient.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/TemperatureGradient.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -51,40 +46,94 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static TemperatureGradient() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class TemperatureGradientInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(-1, 0, 0, 0, 1, 0, 0); - BaseUnit = TemperatureGradientUnit.KelvinPerMeter; - Units = Enum.GetValues(typeof(TemperatureGradientUnit)).Cast().ToArray(); - Zero = new TemperatureGradient(0, BaseUnit); - Info = new QuantityInfo("TemperatureGradient", - new UnitInfo[] - { - new UnitInfo(TemperatureGradientUnit.DegreeCelsiusPerKilometer, "DegreesCelsiusPerKilometer", new BaseUnits(length: LengthUnit.Kilometer, temperature: TemperatureUnit.DegreeCelsius), "TemperatureGradient"), - new UnitInfo(TemperatureGradientUnit.DegreeCelsiusPerMeter, "DegreesCelsiusPerMeter", new BaseUnits(length: LengthUnit.Meter, temperature: TemperatureUnit.DegreeCelsius), "TemperatureGradient"), - new UnitInfo(TemperatureGradientUnit.DegreeFahrenheitPerFoot, "DegreesFahrenheitPerFoot", new BaseUnits(length: LengthUnit.Foot, temperature: TemperatureUnit.DegreeFahrenheit), "TemperatureGradient"), - new UnitInfo(TemperatureGradientUnit.KelvinPerMeter, "KelvinsPerMeter", new BaseUnits(length: LengthUnit.Meter, temperature: TemperatureUnit.Kelvin), "TemperatureGradient"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public TemperatureGradientInfo(string name, TemperatureGradientUnit baseUnit, IEnumerable> unitMappings, TemperatureGradient zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public TemperatureGradientInfo(string name, TemperatureGradientUnit baseUnit, IEnumerable> unitMappings, TemperatureGradient zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, TemperatureGradient.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.TemperatureGradient", typeof(TemperatureGradient).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the TemperatureGradient quantity. + /// + /// A new instance of the class with the default settings. + public static TemperatureGradientInfo CreateDefault() + { + return new TemperatureGradientInfo(nameof(TemperatureGradient), DefaultBaseUnit, GetDefaultMappings(), new TemperatureGradient(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the TemperatureGradient quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static TemperatureGradientInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new TemperatureGradientInfo(nameof(TemperatureGradient), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new TemperatureGradient(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is L^-1Θ. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-1, 0, 0, 0, 1, 0, 0); + + /// + /// The default base unit of TemperatureGradient is KelvinPerMeter. All conversions, as defined in the , go via this value. + /// + public static TemperatureGradientUnit DefaultBaseUnit { get; } = TemperatureGradientUnit.KelvinPerMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + 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 = UnitsNetSetup.CreateQuantityInfo(TemperatureGradientInfo.CreateDefault); } /// @@ -92,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; @@ -106,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); @@ -117,110 +166,99 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of TemperatureGradient, which is KelvinPerMeter. All conversions go via this value. /// - public static TemperatureGradientUnit BaseUnit { get; } + public static TemperatureGradientUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the TemperatureGradient quantity. /// - public static TemperatureGradientUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit KelvinPerMeter. /// - public static TemperatureGradient Zero { get; } - - /// - public static TemperatureGradient AdditiveIdentity => Zero; + public static TemperatureGradient Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public TemperatureGradientUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => TemperatureGradient.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -249,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); } @@ -257,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); } @@ -265,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); } @@ -273,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); } @@ -284,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); } @@ -345,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); } /// @@ -376,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); } /// @@ -401,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")); /// @@ -409,10 +440,10 @@ public static TemperatureGradientUnit ParseUnit(string str) /// Error parsing string. public static TemperatureGradientUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -427,10 +458,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -446,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; } @@ -496,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current TemperatureGradient. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(TemperatureGradient), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -589,228 +614,24 @@ public int CompareTo(object? obj) /// public int CompareTo(TemperatureGradient other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another TemperatureGradient within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(TemperatureGradient other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is TemperatureGradient otherTyped - && (tolerance is TemperatureGradient toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'TemperatureGradient'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(TemperatureGradient other, TemperatureGradient tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current TemperatureGradient. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(TemperatureGradientUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(TemperatureGradientUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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), - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -825,137 +646,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(TemperatureGradient)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(TemperatureGradient)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(TemperatureGradient)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(TemperatureGradient)) - return this; - else if (conversionType == typeof(TemperatureGradientUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return TemperatureGradient.Info; - else if (conversionType == typeof(BaseDimensions)) - return TemperatureGradient.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(TemperatureGradient)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs b/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs index 5011bf152e..4f5fa257e8 100644 --- a/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,38 +46,88 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static ThermalConductivity() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ThermalConductivityInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(1, 1, -3, 0, -1, 0, 0); - BaseUnit = ThermalConductivityUnit.WattPerMeterKelvin; - Units = Enum.GetValues(typeof(ThermalConductivityUnit)).Cast().ToArray(); - Zero = new ThermalConductivity(0, BaseUnit); - Info = new QuantityInfo("ThermalConductivity", - new UnitInfo[] - { - new UnitInfo(ThermalConductivityUnit.BtuPerHourFootFahrenheit, "BtusPerHourFootFahrenheit", BaseUnits.Undefined, "ThermalConductivity"), - new UnitInfo(ThermalConductivityUnit.WattPerMeterKelvin, "WattsPerMeterKelvin", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin), "ThermalConductivity"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public ThermalConductivityInfo(string name, ThermalConductivityUnit baseUnit, IEnumerable> unitMappings, ThermalConductivity zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ThermalConductivityInfo(string name, ThermalConductivityUnit baseUnit, IEnumerable> unitMappings, ThermalConductivity zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ThermalConductivity.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ThermalConductivity", typeof(ThermalConductivity).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the ThermalConductivity quantity. + /// + /// A new instance of the class with the default settings. + public static ThermalConductivityInfo CreateDefault() + { + return new ThermalConductivityInfo(nameof(ThermalConductivity), DefaultBaseUnit, GetDefaultMappings(), new ThermalConductivity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ThermalConductivity quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ThermalConductivityInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ThermalConductivityInfo(nameof(ThermalConductivity), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ThermalConductivity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-3LMΘ^-1. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, 1, -3, 0, -1, 0, 0); + + /// + /// The default base unit of ThermalConductivity is WattPerMeterKelvin. All conversions, as defined in the , go via this value. + /// + public static ThermalConductivityUnit DefaultBaseUnit { get; } = ThermalConductivityUnit.WattPerMeterKelvin; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for ThermalConductivity. + public static IEnumerable> GetDefaultMappings() + { + 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 = UnitsNetSetup.CreateQuantityInfo(ThermalConductivityInfo.CreateDefault); } /// @@ -90,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; @@ -104,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); @@ -115,96 +160,89 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ThermalConductivity, which is WattPerMeterKelvin. All conversions go via this value. /// - public static ThermalConductivityUnit BaseUnit { get; } + public static ThermalConductivityUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ThermalConductivity quantity. /// - public static ThermalConductivityUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit WattPerMeterKelvin. /// - public static ThermalConductivity Zero { get; } - - /// - public static ThermalConductivity AdditiveIdentity => Zero; + public static ThermalConductivity Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ThermalConductivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ThermalConductivity.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -233,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); } @@ -241,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); } @@ -252,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); } @@ -313,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); } /// @@ -344,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); } /// @@ -369,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")); /// @@ -377,10 +408,10 @@ public static ThermalConductivityUnit ParseUnit(string str) /// Error parsing string. public static ThermalConductivityUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -395,10 +426,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -414,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; } @@ -454,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ThermalConductivity. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ThermalConductivity), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -547,224 +572,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ThermalConductivity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ThermalConductivity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ThermalConductivity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ThermalConductivity otherTyped - && (tolerance is ThermalConductivity toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ThermalConductivity'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ThermalConductivity other, ThermalConductivity tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ThermalConductivity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(ThermalConductivityUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(ThermalConductivityUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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), - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -779,137 +604,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ThermalConductivity)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ThermalConductivity)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ThermalConductivity)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ThermalConductivity)) - return this; - else if (conversionType == typeof(ThermalConductivityUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ThermalConductivity.Info; - else if (conversionType == typeof(BaseDimensions)) - return ThermalConductivity.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ThermalConductivity)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/ThermalInsulance.g.cs b/UnitsNet/GeneratedCode/Quantities/ThermalInsulance.g.cs index 98cb82a981..ef733d0566 100644 --- a/UnitsNet/GeneratedCode/Quantities/ThermalInsulance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ThermalInsulance.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -48,42 +43,100 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static ThermalInsulance() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class ThermalInsulanceInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(0, -1, 3, 0, 1, 0, 0); - BaseUnit = ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt; - Units = Enum.GetValues(typeof(ThermalInsulanceUnit)).Cast().ToArray(); - Zero = new ThermalInsulance(0, BaseUnit); - Info = new QuantityInfo("ThermalInsulance", - new UnitInfo[] - { - new UnitInfo(ThermalInsulanceUnit.HourSquareFeetDegreeFahrenheitPerBtu, "HourSquareFeetDegreesFahrenheitPerBtu", BaseUnits.Undefined, "ThermalInsulance"), - new UnitInfo(ThermalInsulanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie, "SquareCentimeterHourDegreesCelsiusPerKilocalorie", BaseUnits.Undefined, "ThermalInsulance"), - new UnitInfo(ThermalInsulanceUnit.SquareCentimeterKelvinPerWatt, "SquareCentimeterKelvinsPerWatt", BaseUnits.Undefined, "ThermalInsulance"), - new UnitInfo(ThermalInsulanceUnit.SquareMeterDegreeCelsiusPerWatt, "SquareMeterDegreesCelsiusPerWatt", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius), "ThermalInsulance"), - new UnitInfo(ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, "SquareMeterKelvinsPerKilowatt", BaseUnits.Undefined, "ThermalInsulance"), - new UnitInfo(ThermalInsulanceUnit.SquareMeterKelvinPerWatt, "SquareMeterKelvinsPerWatt", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin), "ThermalInsulance"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public ThermalInsulanceInfo(string name, ThermalInsulanceUnit baseUnit, IEnumerable> unitMappings, ThermalInsulance zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public ThermalInsulanceInfo(string name, ThermalInsulanceUnit baseUnit, IEnumerable> unitMappings, ThermalInsulance zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, ThermalInsulance.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.ThermalInsulance", typeof(ThermalInsulance).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the ThermalInsulance quantity. + /// + /// A new instance of the class with the default settings. + public static ThermalInsulanceInfo CreateDefault() + { + return new ThermalInsulanceInfo(nameof(ThermalInsulance), DefaultBaseUnit, GetDefaultMappings(), new ThermalInsulance(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the ThermalInsulance quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static ThermalInsulanceInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new ThermalInsulanceInfo(nameof(ThermalInsulance), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new ThermalInsulance(0, DefaultBaseUnit), DefaultBaseDimensions); + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// The for is T^3M^-1Θ. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, -1, 3, 0, 1, 0, 0); + + /// + /// The default base unit of ThermalInsulance is SquareMeterKelvinPerKilowatt. All conversions, as defined in the , go via this value. + /// + public static ThermalInsulanceUnit DefaultBaseUnit { get; } = ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for ThermalInsulance. + public static IEnumerable> GetDefaultMappings() + { + 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), + new QuantityValue(1, 1000) + ); + } + } + + static ThermalInsulance() + { + Info = UnitsNetSetup.CreateQuantityInfo(ThermalInsulanceInfo.CreateDefault); } /// @@ -91,7 +144,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; @@ -105,7 +158,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); @@ -116,124 +169,109 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of ThermalInsulance, which is SquareMeterKelvinPerKilowatt. All conversions go via this value. /// - public static ThermalInsulanceUnit BaseUnit { get; } + public static ThermalInsulanceUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the ThermalInsulance quantity. /// - public static ThermalInsulanceUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit SquareMeterKelvinPerKilowatt. /// - public static ThermalInsulance Zero { get; } - - /// - public static ThermalInsulance AdditiveIdentity => Zero; + public static ThermalInsulance Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public ThermalInsulanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => ThermalInsulance.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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); #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)); - - // 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)); - } - /// /// Get unit abbreviation string. /// @@ -262,7 +300,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); } @@ -270,7 +308,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); } @@ -278,7 +316,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); } @@ -286,7 +324,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); } @@ -294,7 +332,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); } @@ -302,7 +340,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); } @@ -313,7 +351,7 @@ public static ThermalInsulance FromSquareMeterKelvinsPerWatt(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); } @@ -374,10 +412,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); } /// @@ -405,11 +440,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); } /// @@ -430,7 +461,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")); /// @@ -438,10 +469,10 @@ public static ThermalInsulanceUnit ParseUnit(string str) /// Error parsing string. public static ThermalInsulanceUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -456,10 +487,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -475,35 +506,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; } @@ -515,88 +546,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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current ThermalInsulance. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(ThermalInsulance), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -608,232 +633,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ThermalInsulance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another ThermalInsulance within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(ThermalInsulance other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is ThermalInsulance otherTyped - && (tolerance is ThermalInsulance toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'ThermalInsulance'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(ThermalInsulance other, ThermalInsulance tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current ThermalInsulance. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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), - - // 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), - - _ => 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)); + #region Conversion Methods (explicit implementations for netstandard2.0) - 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 ThermalInsulanceUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ThermalInsulanceUnit)} 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(ThermalInsulanceUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(ThermalInsulanceUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -848,137 +665,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ThermalInsulance)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ThermalInsulance)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(ThermalInsulance)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(ThermalInsulance)) - return this; - else if (conversionType == typeof(ThermalInsulanceUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return ThermalInsulance.Info; - else if (conversionType == typeof(BaseDimensions)) - return ThermalInsulance.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(ThermalInsulance)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Torque.g.cs b/UnitsNet/GeneratedCode/Quantities/Torque.g.cs index 3af689138c..0f85a75fe6 100644 --- a/UnitsNet/GeneratedCode/Quantities/Torque.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Torque.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -57,61 +52,157 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class TorqueInfo: QuantityInfo + { + /// + public TorqueInfo(string name, TorqueUnit baseUnit, IEnumerable> unitMappings, Torque zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public TorqueInfo(string name, TorqueUnit baseUnit, IEnumerable> unitMappings, Torque zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Torque.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Torque", typeof(Torque).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Torque quantity. + /// + /// A new instance of the class with the default settings. + public static TorqueInfo CreateDefault() + { + return new TorqueInfo(nameof(Torque), DefaultBaseUnit, GetDefaultMappings(), new Torque(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Torque quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static TorqueInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new TorqueInfo(nameof(Torque), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Torque(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-2L^2M. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); + + /// + /// The default base unit of Torque is NewtonMeter. All conversions, as defined in the , go via this value. + /// + public static TorqueUnit DefaultBaseUnit { get; } = TorqueUnit.NewtonMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Torque. + public static IEnumerable> GetDefaultMappings() + { + 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, + 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() { - BaseDimensions = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); - BaseUnit = TorqueUnit.NewtonMeter; - Units = Enum.GetValues(typeof(TorqueUnit)).Cast().ToArray(); - Zero = new Torque(0, BaseUnit); - Info = new QuantityInfo("Torque", - new UnitInfo[] - { - new UnitInfo(TorqueUnit.GramForceCentimeter, "GramForceCentimeters", BaseUnits.Undefined, "Torque"), - new UnitInfo(TorqueUnit.GramForceMeter, "GramForceMeters", BaseUnits.Undefined, "Torque"), - new UnitInfo(TorqueUnit.GramForceMillimeter, "GramForceMillimeters", BaseUnits.Undefined, "Torque"), - new UnitInfo(TorqueUnit.KilogramForceCentimeter, "KilogramForceCentimeters", BaseUnits.Undefined, "Torque"), - new UnitInfo(TorqueUnit.KilogramForceMeter, "KilogramForceMeters", BaseUnits.Undefined, "Torque"), - new UnitInfo(TorqueUnit.KilogramForceMillimeter, "KilogramForceMillimeters", BaseUnits.Undefined, "Torque"), - new UnitInfo(TorqueUnit.KilonewtonCentimeter, "KilonewtonCentimeters", BaseUnits.Undefined, "Torque"), - new UnitInfo(TorqueUnit.KilonewtonMeter, "KilonewtonMeters", BaseUnits.Undefined, "Torque"), - new UnitInfo(TorqueUnit.KilonewtonMillimeter, "KilonewtonMillimeters", BaseUnits.Undefined, "Torque"), - new UnitInfo(TorqueUnit.KilopoundForceFoot, "KilopoundForceFeet", BaseUnits.Undefined, "Torque"), - new UnitInfo(TorqueUnit.KilopoundForceInch, "KilopoundForceInches", BaseUnits.Undefined, "Torque"), - new UnitInfo(TorqueUnit.MeganewtonCentimeter, "MeganewtonCentimeters", BaseUnits.Undefined, "Torque"), - new UnitInfo(TorqueUnit.MeganewtonMeter, "MeganewtonMeters", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Torque"), - new UnitInfo(TorqueUnit.MeganewtonMillimeter, "MeganewtonMillimeters", BaseUnits.Undefined, "Torque"), - new UnitInfo(TorqueUnit.MegapoundForceFoot, "MegapoundForceFeet", BaseUnits.Undefined, "Torque"), - new UnitInfo(TorqueUnit.MegapoundForceInch, "MegapoundForceInches", BaseUnits.Undefined, "Torque"), - new UnitInfo(TorqueUnit.NewtonCentimeter, "NewtonCentimeters", BaseUnits.Undefined, "Torque"), - new UnitInfo(TorqueUnit.NewtonMeter, "NewtonMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second), "Torque"), - new UnitInfo(TorqueUnit.NewtonMillimeter, "NewtonMillimeters", BaseUnits.Undefined, "Torque"), - new UnitInfo(TorqueUnit.PoundalFoot, "PoundalFeet", BaseUnits.Undefined, "Torque"), - new UnitInfo(TorqueUnit.PoundForceFoot, "PoundForceFeet", BaseUnits.Undefined, "Torque"), - new UnitInfo(TorqueUnit.PoundForceInch, "PoundForceInches", BaseUnits.Undefined, "Torque"), - new UnitInfo(TorqueUnit.TonneForceCentimeter, "TonneForceCentimeters", BaseUnits.Undefined, "Torque"), - new UnitInfo(TorqueUnit.TonneForceMeter, "TonneForceMeters", BaseUnits.Undefined, "Torque"), - new UnitInfo(TorqueUnit.TonneForceMillimeter, "TonneForceMillimeters", BaseUnits.Undefined, "Torque"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(TorqueInfo.CreateDefault); } /// @@ -119,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; @@ -133,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); @@ -144,257 +235,204 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Torque, which is NewtonMeter. All conversions go via this value. /// - public static TorqueUnit BaseUnit { get; } + public static TorqueUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Torque quantity. /// - public static TorqueUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit NewtonMeter. /// - public static Torque Zero { get; } - - /// - public static Torque AdditiveIdentity => Zero; + public static Torque Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public TorqueUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Torque.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -423,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); } @@ -431,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); } @@ -439,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); } @@ -447,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); } @@ -455,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); } @@ -463,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); } @@ -471,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); } @@ -479,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); } @@ -487,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); } @@ -495,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); } @@ -503,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); } @@ -511,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); } @@ -519,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); } @@ -527,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); } @@ -535,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); } @@ -543,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); } @@ -551,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); } @@ -559,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); } @@ -567,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); } @@ -575,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); } @@ -583,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); } @@ -591,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); } @@ -599,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); } @@ -607,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); } @@ -615,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); } @@ -626,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); } @@ -687,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); } /// @@ -718,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); } /// @@ -743,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")); /// @@ -751,10 +782,10 @@ public static TorqueUnit ParseUnit(string str) /// Error parsing string. public static TorqueUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -769,10 +800,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -788,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; } @@ -874,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Torque. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Torque), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -967,270 +992,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Torque other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Torque within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Torque other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Torque otherTyped - && (tolerance is Torque toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Torque'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Torque other, Torque tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Torque. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(TorqueUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - /// 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 NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } + IQuantity IQuantity.ToUnit(TorqueUnit unit) => this.ToUnit(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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(TorqueUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1245,137 +1024,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Torque)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Torque)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Torque)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Torque)) - return this; - else if (conversionType == typeof(TorqueUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Torque.Info; - else if (conversionType == typeof(BaseDimensions)) - return Torque.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Torque)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Turbidity.g.cs b/UnitsNet/GeneratedCode/Quantities/Turbidity.g.cs index e10d096fad..d2e1c9332f 100644 --- a/UnitsNet/GeneratedCode/Quantities/Turbidity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Turbidity.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,37 +46,85 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static Turbidity() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class TurbidityInfo: QuantityInfo { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = TurbidityUnit.NTU; - Units = Enum.GetValues(typeof(TurbidityUnit)).Cast().ToArray(); - Zero = new Turbidity(0, BaseUnit); - Info = new QuantityInfo("Turbidity", - new UnitInfo[] - { - new UnitInfo(TurbidityUnit.NTU, "NTU", BaseUnits.Undefined, "Turbidity"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public TurbidityInfo(string name, TurbidityUnit baseUnit, IEnumerable> unitMappings, Turbidity zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public TurbidityInfo(string name, TurbidityUnit baseUnit, IEnumerable> unitMappings, Turbidity zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Turbidity.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Turbidity", typeof(Turbidity).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the Turbidity quantity. + /// + /// A new instance of the class with the default settings. + public static TurbidityInfo CreateDefault() + { + return new TurbidityInfo(nameof(Turbidity), DefaultBaseUnit, GetDefaultMappings(), new Turbidity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Turbidity quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static TurbidityInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new TurbidityInfo(nameof(Turbidity), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Turbidity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is . + /// + public static BaseDimensions DefaultBaseDimensions { get; } = BaseDimensions.Dimensionless; + + /// + /// The default base unit of Turbidity is NTU. All conversions, as defined in the , go via this value. + /// + public static TurbidityUnit DefaultBaseUnit { get; } = TurbidityUnit.NTU; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Turbidity. + public static IEnumerable> GetDefaultMappings() + { + yield return new (TurbidityUnit.NTU, "NTU", "NTU", BaseUnits.Undefined); + } + } + + static Turbidity() + { + Info = UnitsNetSetup.CreateQuantityInfo(TurbidityInfo.CreateDefault); } /// @@ -89,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; @@ -100,88 +143,83 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Turbidity, which is NTU. All conversions go via this value. /// - public static TurbidityUnit BaseUnit { get; } + public static TurbidityUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Turbidity quantity. /// - public static TurbidityUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit NTU. /// - public static Turbidity Zero { get; } - - /// - public static Turbidity AdditiveIdentity => Zero; + public static Turbidity Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public TurbidityUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Turbidity.BaseDimensions; - #endregion + #region Explicit implementations - #region Conversion Properties + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); - /// - /// Gets a value of this quantity converted into - /// - public double NTU => As(TurbidityUnit.NTU); + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif #endregion - #region Static Methods + #endregion + + #region Conversion Properties /// - /// Registers the default conversion functions in the given instance. + /// Gets a value of this quantity converted into /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: TurbidityUnit -> BaseUnit + public QuantityValue NTU => this.As(TurbidityUnit.NTU); - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(TurbidityUnit.NTU, TurbidityUnit.NTU, quantity => quantity); + #endregion - // Register in unit converter: BaseUnit -> TurbidityUnit - } + #region Static Methods /// /// Get unit abbreviation string. @@ -211,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); } @@ -222,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); } @@ -283,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); } /// @@ -314,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); } /// @@ -339,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")); /// @@ -347,10 +378,10 @@ public static TurbidityUnit ParseUnit(string str) /// Error parsing string. public static TurbidityUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -365,10 +396,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -384,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; } @@ -424,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Turbidity. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Turbidity), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -517,222 +542,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Turbidity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Turbidity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Turbidity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Turbidity otherTyped - && (tolerance is Turbidity toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Turbidity'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Turbidity other, Turbidity tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Turbidity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(TurbidityUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(TurbidityUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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 - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -747,137 +574,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Turbidity)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Turbidity)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Turbidity)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Turbidity)) - return this; - else if (conversionType == typeof(TurbidityUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Turbidity.Info; - else if (conversionType == typeof(BaseDimensions)) - return Turbidity.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Turbidity)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs b/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs index ef2c7139da..11b8ceadb7 100644 --- a/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -48,37 +43,85 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static VitaminA() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class VitaminAInfo: QuantityInfo { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = VitaminAUnit.InternationalUnit; - Units = Enum.GetValues(typeof(VitaminAUnit)).Cast().ToArray(); - Zero = new VitaminA(0, BaseUnit); - Info = new QuantityInfo("VitaminA", - new UnitInfo[] - { - new UnitInfo(VitaminAUnit.InternationalUnit, "InternationalUnits", BaseUnits.Undefined, "VitaminA"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public VitaminAInfo(string name, VitaminAUnit baseUnit, IEnumerable> unitMappings, VitaminA zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public VitaminAInfo(string name, VitaminAUnit baseUnit, IEnumerable> unitMappings, VitaminA zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, VitaminA.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.VitaminA", typeof(VitaminA).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the VitaminA quantity. + /// + /// A new instance of the class with the default settings. + public static VitaminAInfo CreateDefault() + { + return new VitaminAInfo(nameof(VitaminA), DefaultBaseUnit, GetDefaultMappings(), new VitaminA(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the VitaminA quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static VitaminAInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new VitaminAInfo(nameof(VitaminA), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new VitaminA(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is . + /// + public static BaseDimensions DefaultBaseDimensions { get; } = BaseDimensions.Dimensionless; + + /// + /// The default base unit of VitaminA is InternationalUnit. All conversions, as defined in the , go via this value. + /// + public static VitaminAUnit DefaultBaseUnit { get; } = VitaminAUnit.InternationalUnit; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for VitaminA. + public static IEnumerable> GetDefaultMappings() + { + yield return new (VitaminAUnit.InternationalUnit, "InternationalUnit", "InternationalUnits", BaseUnits.Undefined); + } + } + + static VitaminA() + { + Info = UnitsNetSetup.CreateQuantityInfo(VitaminAInfo.CreateDefault); } /// @@ -86,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; @@ -97,88 +140,83 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of VitaminA, which is InternationalUnit. All conversions go via this value. /// - public static VitaminAUnit BaseUnit { get; } + public static VitaminAUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the VitaminA quantity. /// - public static VitaminAUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit InternationalUnit. /// - public static VitaminA Zero { get; } - - /// - public static VitaminA AdditiveIdentity => Zero; + public static VitaminA Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public VitaminAUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => VitaminA.BaseDimensions; - #endregion + #region Explicit implementations - #region Conversion Properties + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); - /// - /// Gets a value of this quantity converted into - /// - public double InternationalUnits => As(VitaminAUnit.InternationalUnit); + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif #endregion - #region Static Methods + #endregion + + #region Conversion Properties /// - /// Registers the default conversion functions in the given instance. + /// Gets a value of this quantity converted into /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: VitaminAUnit -> BaseUnit + public QuantityValue InternationalUnits => this.As(VitaminAUnit.InternationalUnit); - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(VitaminAUnit.InternationalUnit, VitaminAUnit.InternationalUnit, quantity => quantity); + #endregion - // Register in unit converter: BaseUnit -> VitaminAUnit - } + #region Static Methods /// /// Get unit abbreviation string. @@ -208,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); } @@ -219,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); } @@ -280,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); } /// @@ -311,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); } /// @@ -336,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")); /// @@ -344,10 +375,10 @@ public static VitaminAUnit ParseUnit(string str) /// Error parsing string. public static VitaminAUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -362,10 +393,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -381,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; } @@ -421,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current VitaminA. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(VitaminA), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -514,222 +539,24 @@ public int CompareTo(object? obj) /// public int CompareTo(VitaminA other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another VitaminA within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(VitaminA other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is VitaminA otherTyped - && (tolerance is VitaminA toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'VitaminA'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(VitaminA other, VitaminA tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current VitaminA. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(VitaminAUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(VitaminAUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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 - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -744,137 +571,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(VitaminA)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(VitaminA)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(VitaminA)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(VitaminA)) - return this; - else if (conversionType == typeof(VitaminAUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return VitaminA.Info; - else if (conversionType == typeof(BaseDimensions)) - return VitaminA.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(VitaminA)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/Volume.g.cs b/UnitsNet/GeneratedCode/Quantities/Volume.g.cs index 25cb6f7120..d6bc9092df 100644 --- a/UnitsNet/GeneratedCode/Quantities/Volume.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Volume.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -63,90 +58,244 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class VolumeInfo: QuantityInfo + { + /// + public VolumeInfo(string name, VolumeUnit baseUnit, IEnumerable> unitMappings, Volume zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public VolumeInfo(string name, VolumeUnit baseUnit, IEnumerable> unitMappings, Volume zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, Volume.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.Volume", typeof(Volume).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the Volume quantity. + /// + /// A new instance of the class with the default settings. + public static VolumeInfo CreateDefault() + { + return new VolumeInfo(nameof(Volume), DefaultBaseUnit, GetDefaultMappings(), new Volume(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the Volume quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static VolumeInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new VolumeInfo(nameof(Volume), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new Volume(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is L^3. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(3, 0, 0, 0, 0, 0, 0); + + /// + /// The default base unit of Volume is CubicMeter. All conversions, as defined in the , go via this value. + /// + public static VolumeUnit DefaultBaseUnit { get; } = VolumeUnit.CubicMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for Volume. + public static IEnumerable> GetDefaultMappings() + { + 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), + 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() { - BaseDimensions = new BaseDimensions(3, 0, 0, 0, 0, 0, 0); - BaseUnit = VolumeUnit.CubicMeter; - Units = Enum.GetValues(typeof(VolumeUnit)).Cast().ToArray(); - Zero = new Volume(0, BaseUnit); - Info = new QuantityInfo("Volume", - new UnitInfo[] - { - new UnitInfo(VolumeUnit.AcreFoot, "AcreFeet", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.AuTablespoon, "AuTablespoons", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.BoardFoot, "BoardFeet", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.Centiliter, "Centiliters", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.CubicCentimeter, "CubicCentimeters", new BaseUnits(length: LengthUnit.Centimeter), "Volume"), - new UnitInfo(VolumeUnit.CubicDecimeter, "CubicDecimeters", new BaseUnits(length: LengthUnit.Decimeter), "Volume"), - new UnitInfo(VolumeUnit.CubicFoot, "CubicFeet", new BaseUnits(length: LengthUnit.Foot), "Volume"), - new UnitInfo(VolumeUnit.CubicHectometer, "CubicHectometers", new BaseUnits(length: LengthUnit.Hectometer), "Volume"), - new UnitInfo(VolumeUnit.CubicInch, "CubicInches", new BaseUnits(length: LengthUnit.Inch), "Volume"), - new UnitInfo(VolumeUnit.CubicKilometer, "CubicKilometers", new BaseUnits(length: LengthUnit.Kilometer), "Volume"), - new UnitInfo(VolumeUnit.CubicMeter, "CubicMeters", new BaseUnits(length: LengthUnit.Meter), "Volume"), - new UnitInfo(VolumeUnit.CubicMicrometer, "CubicMicrometers", new BaseUnits(length: LengthUnit.Micrometer), "Volume"), - new UnitInfo(VolumeUnit.CubicMile, "CubicMiles", new BaseUnits(length: LengthUnit.Mile), "Volume"), - new UnitInfo(VolumeUnit.CubicMillimeter, "CubicMillimeters", new BaseUnits(length: LengthUnit.Millimeter), "Volume"), - new UnitInfo(VolumeUnit.CubicYard, "CubicYards", new BaseUnits(length: LengthUnit.Yard), "Volume"), - new UnitInfo(VolumeUnit.Decaliter, "Decaliters", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.DecausGallon, "DecausGallons", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.Deciliter, "Deciliters", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.DeciusGallon, "DeciusGallons", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.HectocubicFoot, "HectocubicFeet", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.HectocubicMeter, "HectocubicMeters", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.Hectoliter, "Hectoliters", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.HectousGallon, "HectousGallons", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.ImperialBeerBarrel, "ImperialBeerBarrels", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.ImperialGallon, "ImperialGallons", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.ImperialOunce, "ImperialOunces", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.ImperialPint, "ImperialPints", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.ImperialQuart, "ImperialQuarts", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.KilocubicFoot, "KilocubicFeet", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.KilocubicMeter, "KilocubicMeters", new BaseUnits(length: LengthUnit.Decameter), "Volume"), - new UnitInfo(VolumeUnit.KiloimperialGallon, "KiloimperialGallons", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.Kiloliter, "Kiloliters", new BaseUnits(length: LengthUnit.Meter), "Volume"), - new UnitInfo(VolumeUnit.KilousGallon, "KilousGallons", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.Liter, "Liters", new BaseUnits(length: LengthUnit.Decimeter), "Volume"), - new UnitInfo(VolumeUnit.MegacubicFoot, "MegacubicFeet", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.MegaimperialGallon, "MegaimperialGallons", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.Megaliter, "Megaliters", new BaseUnits(length: LengthUnit.Decameter), "Volume"), - new UnitInfo(VolumeUnit.MegausGallon, "MegausGallons", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.MetricCup, "MetricCups", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.MetricTeaspoon, "MetricTeaspoons", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.Microliter, "Microliters", new BaseUnits(length: LengthUnit.Millimeter), "Volume"), - new UnitInfo(VolumeUnit.Milliliter, "Milliliters", new BaseUnits(length: LengthUnit.Centimeter), "Volume"), - new UnitInfo(VolumeUnit.Nanoliter, "Nanoliters", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.OilBarrel, "OilBarrels", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.UkTablespoon, "UkTablespoons", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.UsBeerBarrel, "UsBeerBarrels", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.UsCustomaryCup, "UsCustomaryCups", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.UsGallon, "UsGallons", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.UsLegalCup, "UsLegalCups", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.UsOunce, "UsOunces", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.UsPint, "UsPints", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.UsQuart, "UsQuarts", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.UsTablespoon, "UsTablespoons", BaseUnits.Undefined, "Volume"), - new UnitInfo(VolumeUnit.UsTeaspoon, "UsTeaspoons", BaseUnits.Undefined, "Volume"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(VolumeInfo.CreateDefault); } /// @@ -154,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; @@ -168,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); @@ -179,460 +328,349 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of Volume, which is CubicMeter. All conversions go via this value. /// - public static VolumeUnit BaseUnit { get; } + public static VolumeUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the Volume quantity. /// - public static VolumeUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeter. /// - public static Volume Zero { get; } - - /// - public static Volume AdditiveIdentity => Zero; + public static Volume Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public VolumeUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => Volume.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -661,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); } @@ -669,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); } @@ -677,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); } @@ -685,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); } @@ -693,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); } @@ -701,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); } @@ -709,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); } @@ -717,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); } @@ -725,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); } @@ -733,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); } @@ -741,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); } @@ -749,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); } @@ -757,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); } @@ -765,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); } @@ -773,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); } @@ -781,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); } @@ -789,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); } @@ -797,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); } @@ -805,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); } @@ -813,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); } @@ -821,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); } @@ -829,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); } @@ -837,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); } @@ -845,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); } @@ -853,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); } @@ -861,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); } @@ -869,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); } @@ -877,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); } @@ -885,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); } @@ -893,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); } @@ -901,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); } @@ -909,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); } @@ -917,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); } @@ -925,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); } @@ -933,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); } @@ -941,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); } @@ -949,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); } @@ -957,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); } @@ -965,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); } @@ -973,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); } @@ -981,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); } @@ -989,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); } @@ -997,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); } @@ -1005,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); } @@ -1013,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); } @@ -1021,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); } @@ -1029,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); } @@ -1037,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); } @@ -1045,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); } @@ -1053,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); } @@ -1061,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); } @@ -1069,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); } @@ -1077,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); } @@ -1085,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); } @@ -1096,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); } @@ -1157,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); } /// @@ -1188,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); } /// @@ -1213,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")); /// @@ -1221,10 +1252,10 @@ public static VolumeUnit ParseUnit(string str) /// Error parsing string. public static VolumeUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -1239,10 +1270,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -1258,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; } @@ -1380,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current Volume. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(Volume), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -1473,328 +1498,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Volume other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another Volume within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(Volume other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is Volume otherTyped - && (tolerance is Volume toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'Volume'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(Volume other, Volume tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current Volume. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(VolumeUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - /// 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 NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } + IQuantity IQuantity.ToUnit(VolumeUnit unit) => this.ToUnit(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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(VolumeUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1809,137 +1530,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Volume)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Volume)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(Volume)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(Volume)) - return this; - else if (conversionType == typeof(VolumeUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return Volume.Info; - else if (conversionType == typeof(BaseDimensions)) - return Volume.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(Volume)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/VolumeConcentration.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumeConcentration.g.cs index 6a598defda..c50553ef20 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumeConcentration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumeConcentration.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -55,56 +50,142 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class VolumeConcentrationInfo: QuantityInfo + { + /// + public VolumeConcentrationInfo(string name, VolumeConcentrationUnit baseUnit, IEnumerable> unitMappings, VolumeConcentration zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public VolumeConcentrationInfo(string name, VolumeConcentrationUnit baseUnit, IEnumerable> unitMappings, VolumeConcentration zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, VolumeConcentration.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.VolumeConcentration", typeof(VolumeConcentration).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the VolumeConcentration quantity. + /// + /// A new instance of the class with the default settings. + public static VolumeConcentrationInfo CreateDefault() + { + return new VolumeConcentrationInfo(nameof(VolumeConcentration), DefaultBaseUnit, GetDefaultMappings(), new VolumeConcentration(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the VolumeConcentration quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static VolumeConcentrationInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new VolumeConcentrationInfo(nameof(VolumeConcentration), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new VolumeConcentration(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is . + /// + public static BaseDimensions DefaultBaseDimensions { get; } = BaseDimensions.Dimensionless; + + /// + /// The default base unit of VolumeConcentration is DecimalFraction. All conversions, as defined in the , go via this value. + /// + public static VolumeConcentrationUnit DefaultBaseUnit { get; } = VolumeConcentrationUnit.DecimalFraction; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for VolumeConcentration. + public static IEnumerable> GetDefaultMappings() + { + 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, + 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() { - BaseDimensions = BaseDimensions.Dimensionless; - BaseUnit = VolumeConcentrationUnit.DecimalFraction; - Units = Enum.GetValues(typeof(VolumeConcentrationUnit)).Cast().ToArray(); - Zero = new VolumeConcentration(0, BaseUnit); - Info = new QuantityInfo("VolumeConcentration", - new UnitInfo[] - { - new UnitInfo(VolumeConcentrationUnit.CentiliterPerLiter, "CentilitersPerLiter", BaseUnits.Undefined, "VolumeConcentration"), - new UnitInfo(VolumeConcentrationUnit.CentiliterPerMilliliter, "CentilitersPerMilliliter", BaseUnits.Undefined, "VolumeConcentration"), - new UnitInfo(VolumeConcentrationUnit.DeciliterPerLiter, "DecilitersPerLiter", BaseUnits.Undefined, "VolumeConcentration"), - new UnitInfo(VolumeConcentrationUnit.DeciliterPerMilliliter, "DecilitersPerMilliliter", BaseUnits.Undefined, "VolumeConcentration"), - new UnitInfo(VolumeConcentrationUnit.DecimalFraction, "DecimalFractions", BaseUnits.Undefined, "VolumeConcentration"), - new UnitInfo(VolumeConcentrationUnit.LiterPerLiter, "LitersPerLiter", BaseUnits.Undefined, "VolumeConcentration"), - new UnitInfo(VolumeConcentrationUnit.LiterPerMilliliter, "LitersPerMilliliter", BaseUnits.Undefined, "VolumeConcentration"), - new UnitInfo(VolumeConcentrationUnit.MicroliterPerLiter, "MicrolitersPerLiter", BaseUnits.Undefined, "VolumeConcentration"), - new UnitInfo(VolumeConcentrationUnit.MicroliterPerMilliliter, "MicrolitersPerMilliliter", BaseUnits.Undefined, "VolumeConcentration"), - new UnitInfo(VolumeConcentrationUnit.MilliliterPerLiter, "MillilitersPerLiter", BaseUnits.Undefined, "VolumeConcentration"), - new UnitInfo(VolumeConcentrationUnit.MilliliterPerMilliliter, "MillilitersPerMilliliter", BaseUnits.Undefined, "VolumeConcentration"), - new UnitInfo(VolumeConcentrationUnit.NanoliterPerLiter, "NanolitersPerLiter", BaseUnits.Undefined, "VolumeConcentration"), - new UnitInfo(VolumeConcentrationUnit.NanoliterPerMilliliter, "NanolitersPerMilliliter", BaseUnits.Undefined, "VolumeConcentration"), - new UnitInfo(VolumeConcentrationUnit.PartPerBillion, "PartsPerBillion", BaseUnits.Undefined, "VolumeConcentration"), - new UnitInfo(VolumeConcentrationUnit.PartPerMillion, "PartsPerMillion", BaseUnits.Undefined, "VolumeConcentration"), - new UnitInfo(VolumeConcentrationUnit.PartPerThousand, "PartsPerThousand", BaseUnits.Undefined, "VolumeConcentration"), - new UnitInfo(VolumeConcentrationUnit.PartPerTrillion, "PartsPerTrillion", BaseUnits.Undefined, "VolumeConcentration"), - new UnitInfo(VolumeConcentrationUnit.Percent, "Percent", BaseUnits.Undefined, "VolumeConcentration"), - new UnitInfo(VolumeConcentrationUnit.PicoliterPerLiter, "PicolitersPerLiter", BaseUnits.Undefined, "VolumeConcentration"), - new UnitInfo(VolumeConcentrationUnit.PicoliterPerMilliliter, "PicolitersPerMilliliter", BaseUnits.Undefined, "VolumeConcentration"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(VolumeConcentrationInfo.CreateDefault); } /// @@ -112,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; @@ -123,222 +204,179 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of VolumeConcentration, which is DecimalFraction. All conversions go via this value. /// - public static VolumeConcentrationUnit BaseUnit { get; } + public static VolumeConcentrationUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the VolumeConcentration quantity. /// - public static VolumeConcentrationUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit DecimalFraction. /// - public static VolumeConcentration Zero { get; } - - /// - public static VolumeConcentration AdditiveIdentity => Zero; + public static VolumeConcentration Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public VolumeConcentrationUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => VolumeConcentration.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -367,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); } @@ -375,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); } @@ -383,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); } @@ -391,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); } @@ -399,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); } @@ -407,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); } @@ -415,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); } @@ -423,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); } @@ -431,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); } @@ -439,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); } @@ -447,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); } @@ -455,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); } @@ -463,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); } @@ -471,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); } @@ -479,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); } @@ -487,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); } @@ -495,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); } @@ -503,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); } @@ -511,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); } @@ -519,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); } @@ -530,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); } @@ -591,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); } /// @@ -622,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); } /// @@ -647,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")); /// @@ -655,10 +686,10 @@ public static VolumeConcentrationUnit ParseUnit(string str) /// Error parsing string. public static VolumeConcentrationUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -673,10 +704,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -692,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; } @@ -748,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current VolumeConcentration. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(VolumeConcentration), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -841,260 +866,24 @@ public int CompareTo(object? obj) /// public int CompareTo(VolumeConcentration other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another VolumeConcentration within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(VolumeConcentration other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is VolumeConcentration otherTyped - && (tolerance is VolumeConcentration toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'VolumeConcentration'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(VolumeConcentration other, VolumeConcentration tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current VolumeConcentration. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(VolumeConcentrationUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(VolumeConcentrationUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1109,137 +898,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(VolumeConcentration)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(VolumeConcentration)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(VolumeConcentration)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(VolumeConcentration)) - return this; - else if (conversionType == typeof(VolumeConcentrationUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return VolumeConcentration.Info; - else if (conversionType == typeof(BaseDimensions)) - return VolumeConcentration.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(VolumeConcentration)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs index 24304ed034..39ce395965 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -55,111 +50,307 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class VolumeFlowInfo: QuantityInfo + { + /// + public VolumeFlowInfo(string name, VolumeFlowUnit baseUnit, IEnumerable> unitMappings, VolumeFlow zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public VolumeFlowInfo(string name, VolumeFlowUnit baseUnit, IEnumerable> unitMappings, VolumeFlow zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, VolumeFlow.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.VolumeFlow", typeof(VolumeFlow).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the VolumeFlow quantity. + /// + /// A new instance of the class with the default settings. + public static VolumeFlowInfo CreateDefault() + { + return new VolumeFlowInfo(nameof(VolumeFlow), DefaultBaseUnit, GetDefaultMappings(), new VolumeFlow(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the VolumeFlow quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static VolumeFlowInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new VolumeFlowInfo(nameof(VolumeFlow), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new VolumeFlow(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-1L^3. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(3, 0, -1, 0, 0, 0, 0); + + /// + /// The default base unit of VolumeFlow is CubicMeterPerSecond. All conversions, as defined in the , go via this value. + /// + public static VolumeFlowUnit DefaultBaseUnit { get; } = VolumeFlowUnit.CubicMeterPerSecond; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for VolumeFlow. + public static IEnumerable> GetDefaultMappings() + { + 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), + 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() { - BaseDimensions = new BaseDimensions(3, 0, -1, 0, 0, 0, 0); - BaseUnit = VolumeFlowUnit.CubicMeterPerSecond; - Units = Enum.GetValues(typeof(VolumeFlowUnit)).Cast().ToArray(); - Zero = new VolumeFlow(0, BaseUnit); - Info = new QuantityInfo("VolumeFlow", - new UnitInfo[] - { - new UnitInfo(VolumeFlowUnit.AcreFootPerDay, "AcreFeetPerDay", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.AcreFootPerHour, "AcreFeetPerHour", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.AcreFootPerMinute, "AcreFeetPerMinute", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.AcreFootPerSecond, "AcreFeetPerSecond", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.CentiliterPerDay, "CentilitersPerDay", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.CentiliterPerHour, "CentilitersPerHour", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.CentiliterPerMinute, "CentilitersPerMinute", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.CentiliterPerSecond, "CentilitersPerSecond", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.CubicCentimeterPerMinute, "CubicCentimetersPerMinute", new BaseUnits(length: LengthUnit.Centimeter, time: DurationUnit.Minute), "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.CubicDecimeterPerMinute, "CubicDecimetersPerMinute", new BaseUnits(length: LengthUnit.Decimeter, time: DurationUnit.Minute), "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.CubicFootPerHour, "CubicFeetPerHour", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Hour), "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.CubicFootPerMinute, "CubicFeetPerMinute", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Minute), "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.CubicFootPerSecond, "CubicFeetPerSecond", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Second), "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.CubicMeterPerDay, "CubicMetersPerDay", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Day), "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.CubicMeterPerHour, "CubicMetersPerHour", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Hour), "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.CubicMeterPerMinute, "CubicMetersPerMinute", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Minute), "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.CubicMeterPerSecond, "CubicMetersPerSecond", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second), "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.CubicMillimeterPerSecond, "CubicMillimetersPerSecond", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Second), "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.CubicYardPerDay, "CubicYardsPerDay", new BaseUnits(length: LengthUnit.Yard, time: DurationUnit.Day), "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.CubicYardPerHour, "CubicYardsPerHour", new BaseUnits(length: LengthUnit.Yard, time: DurationUnit.Hour), "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.CubicYardPerMinute, "CubicYardsPerMinute", new BaseUnits(length: LengthUnit.Yard, time: DurationUnit.Minute), "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.CubicYardPerSecond, "CubicYardsPerSecond", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.DecaliterPerDay, "DecalitersPerDay", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.DecaliterPerHour, "DecalitersPerHour", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.DecaliterPerMinute, "DecalitersPerMinute", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.DecaliterPerSecond, "DecalitersPerSecond", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.DeciliterPerDay, "DecilitersPerDay", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.DeciliterPerHour, "DecilitersPerHour", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.DeciliterPerMinute, "DecilitersPerMinute", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.DeciliterPerSecond, "DecilitersPerSecond", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.HectoliterPerDay, "HectolitersPerDay", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.HectoliterPerHour, "HectolitersPerHour", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.HectoliterPerMinute, "HectolitersPerMinute", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.HectoliterPerSecond, "HectolitersPerSecond", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.KiloliterPerDay, "KilolitersPerDay", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.KiloliterPerHour, "KilolitersPerHour", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.KiloliterPerMinute, "KilolitersPerMinute", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.KiloliterPerSecond, "KilolitersPerSecond", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.KilousGallonPerMinute, "KilousGallonsPerMinute", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.LiterPerDay, "LitersPerDay", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.LiterPerHour, "LitersPerHour", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.LiterPerMinute, "LitersPerMinute", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.LiterPerSecond, "LitersPerSecond", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.MegaliterPerDay, "MegalitersPerDay", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.MegaliterPerHour, "MegalitersPerHour", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.MegaliterPerMinute, "MegalitersPerMinute", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.MegaliterPerSecond, "MegalitersPerSecond", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.MegaukGallonPerDay, "MegaukGallonsPerDay", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.MegaukGallonPerSecond, "MegaukGallonsPerSecond", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.MegausGallonPerDay, "MegausGallonsPerDay", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.MicroliterPerDay, "MicrolitersPerDay", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.MicroliterPerHour, "MicrolitersPerHour", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.MicroliterPerMinute, "MicrolitersPerMinute", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.MicroliterPerSecond, "MicrolitersPerSecond", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.MilliliterPerDay, "MillilitersPerDay", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.MilliliterPerHour, "MillilitersPerHour", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.MilliliterPerMinute, "MillilitersPerMinute", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.MilliliterPerSecond, "MillilitersPerSecond", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.MillionUsGallonPerDay, "MillionUsGallonsPerDay", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.NanoliterPerDay, "NanolitersPerDay", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.NanoliterPerHour, "NanolitersPerHour", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.NanoliterPerMinute, "NanolitersPerMinute", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.NanoliterPerSecond, "NanolitersPerSecond", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.OilBarrelPerDay, "OilBarrelsPerDay", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.OilBarrelPerHour, "OilBarrelsPerHour", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.OilBarrelPerMinute, "OilBarrelsPerMinute", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.OilBarrelPerSecond, "OilBarrelsPerSecond", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.UkGallonPerDay, "UkGallonsPerDay", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.UkGallonPerHour, "UkGallonsPerHour", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.UkGallonPerMinute, "UkGallonsPerMinute", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.UkGallonPerSecond, "UkGallonsPerSecond", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.UsGallonPerDay, "UsGallonsPerDay", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.UsGallonPerHour, "UsGallonsPerHour", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.UsGallonPerMinute, "UsGallonsPerMinute", BaseUnits.Undefined, "VolumeFlow"), - new UnitInfo(VolumeFlowUnit.UsGallonPerSecond, "UsGallonsPerSecond", BaseUnits.Undefined, "VolumeFlow"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(VolumeFlowInfo.CreateDefault); } /// @@ -167,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; @@ -181,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); @@ -192,607 +383,454 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of VolumeFlow, which is CubicMeterPerSecond. All conversions go via this value. /// - public static VolumeFlowUnit BaseUnit { get; } + public static VolumeFlowUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the VolumeFlow quantity. /// - public static VolumeFlowUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeterPerSecond. /// - public static VolumeFlow Zero { get; } - - /// - public static VolumeFlow AdditiveIdentity => Zero; + public static VolumeFlow Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public VolumeFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => VolumeFlow.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -821,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); } @@ -829,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); } @@ -837,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); } @@ -845,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); } @@ -853,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); } @@ -861,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); } @@ -869,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); } @@ -877,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); } @@ -885,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); } @@ -893,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); } @@ -901,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); } @@ -909,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); } @@ -917,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); } @@ -925,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); } @@ -933,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); } @@ -941,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); } @@ -949,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); } @@ -957,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); } @@ -965,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); } @@ -973,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); } @@ -981,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); } @@ -989,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); } @@ -997,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); } @@ -1005,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); } @@ -1013,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); } @@ -1021,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); } @@ -1029,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); } @@ -1037,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); } @@ -1045,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); } @@ -1053,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); } @@ -1061,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); } @@ -1069,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); } @@ -1077,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); } @@ -1085,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); } @@ -1093,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); } @@ -1101,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); } @@ -1109,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); } @@ -1117,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); } @@ -1125,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); } @@ -1133,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); } @@ -1141,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); } @@ -1149,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); } @@ -1157,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); } @@ -1165,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); } @@ -1173,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); } @@ -1181,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); } @@ -1189,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); } @@ -1197,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); } @@ -1205,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); } @@ -1213,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); } @@ -1221,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); } @@ -1229,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); } @@ -1237,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); } @@ -1245,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); } @@ -1253,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); } @@ -1261,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); } @@ -1269,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); } @@ -1277,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); } @@ -1285,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); } @@ -1293,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); } @@ -1301,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); } @@ -1309,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); } @@ -1317,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); } @@ -1325,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); } @@ -1333,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); } @@ -1341,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); } @@ -1349,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); } @@ -1357,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); } @@ -1365,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); } @@ -1373,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); } @@ -1381,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); } @@ -1389,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); } @@ -1397,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); } @@ -1405,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); } @@ -1413,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); } @@ -1424,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); } @@ -1485,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); } /// @@ -1516,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); } /// @@ -1541,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")); /// @@ -1549,10 +1580,10 @@ public static VolumeFlowUnit ParseUnit(string str) /// Error parsing string. public static VolumeFlowUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, 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); @@ -1567,10 +1598,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -1586,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; } @@ -1660,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current VolumeFlow. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(VolumeFlow), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -1753,370 +1778,24 @@ public int CompareTo(object? obj) /// public int CompareTo(VolumeFlow other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another VolumeFlow within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(VolumeFlow other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is VolumeFlow otherTyped - && (tolerance is VolumeFlow toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'VolumeFlow'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(VolumeFlow other, VolumeFlow tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current VolumeFlow. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(VolumeFlowUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - /// 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 NotImplementedException($"Can not convert {Unit} to {unit}."); - } - } + IQuantity IQuantity.ToUnit(VolumeFlowUnit unit) => this.ToUnit(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); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(VolumeFlowUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -2131,137 +1810,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(VolumeFlow)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(VolumeFlow)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(VolumeFlow)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(VolumeFlow)) - return this; - else if (conversionType == typeof(VolumeFlowUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return VolumeFlow.Info; - else if (conversionType == typeof(BaseDimensions)) - return VolumeFlow.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(VolumeFlow)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs index 1ef2505bec..9d90812e06 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -48,38 +43,88 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static VolumeFlowPerArea() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class VolumeFlowPerAreaInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(1, 0, -1, 0, 0, 0, 0); - BaseUnit = VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter; - Units = Enum.GetValues(typeof(VolumeFlowPerAreaUnit)).Cast().ToArray(); - Zero = new VolumeFlowPerArea(0, BaseUnit); - Info = new QuantityInfo("VolumeFlowPerArea", - new UnitInfo[] - { - new UnitInfo(VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot, "CubicFeetPerMinutePerSquareFoot", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Minute), "VolumeFlowPerArea"), - new UnitInfo(VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, "CubicMetersPerSecondPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second), "VolumeFlowPerArea"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public VolumeFlowPerAreaInfo(string name, VolumeFlowPerAreaUnit baseUnit, IEnumerable> unitMappings, VolumeFlowPerArea zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public VolumeFlowPerAreaInfo(string name, VolumeFlowPerAreaUnit baseUnit, IEnumerable> unitMappings, VolumeFlowPerArea zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, VolumeFlowPerArea.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.VolumeFlowPerArea", typeof(VolumeFlowPerArea).Assembly)) + { + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// Creates a new instance of the class with the default settings for the VolumeFlowPerArea quantity. + /// + /// A new instance of the class with the default settings. + public static VolumeFlowPerAreaInfo CreateDefault() + { + return new VolumeFlowPerAreaInfo(nameof(VolumeFlowPerArea), DefaultBaseUnit, GetDefaultMappings(), new VolumeFlowPerArea(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the VolumeFlowPerArea quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static VolumeFlowPerAreaInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new VolumeFlowPerAreaInfo(nameof(VolumeFlowPerArea), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new VolumeFlowPerArea(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-1L. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, 0, -1, 0, 0, 0, 0); + + /// + /// The default base unit of VolumeFlowPerArea is CubicMeterPerSecondPerSquareMeter. All conversions, as defined in the , go via this value. + /// + public static VolumeFlowPerAreaUnit DefaultBaseUnit { get; } = VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An 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), + new QuantityValue(25000, 127) + ); + yield return new (VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, "CubicMeterPerSecondPerSquareMeter", "CubicMetersPerSecondPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second)); + } + } + + static VolumeFlowPerArea() + { + Info = UnitsNetSetup.CreateQuantityInfo(VolumeFlowPerAreaInfo.CreateDefault); } /// @@ -87,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; @@ -101,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); @@ -112,96 +157,89 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of VolumeFlowPerArea, which is CubicMeterPerSecondPerSquareMeter. All conversions go via this value. /// - public static VolumeFlowPerAreaUnit BaseUnit { get; } + public static VolumeFlowPerAreaUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the VolumeFlowPerArea quantity. /// - public static VolumeFlowPerAreaUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeterPerSecondPerSquareMeter. /// - public static VolumeFlowPerArea Zero { get; } - - /// - public static VolumeFlowPerArea AdditiveIdentity => Zero; + public static VolumeFlowPerArea Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public VolumeFlowPerAreaUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => VolumeFlowPerArea.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -230,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); } @@ -238,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); } @@ -249,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); } @@ -310,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); } /// @@ -341,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); } /// @@ -366,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")); /// @@ -374,10 +405,10 @@ public static VolumeFlowPerAreaUnit ParseUnit(string str) /// Error parsing string. public static VolumeFlowPerAreaUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -392,10 +423,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -411,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; } @@ -451,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current VolumeFlowPerArea. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(VolumeFlowPerArea), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -544,224 +569,24 @@ public int CompareTo(object? obj) /// public int CompareTo(VolumeFlowPerArea other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another VolumeFlowPerArea within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(VolumeFlowPerArea other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is VolumeFlowPerArea otherTyped - && (tolerance is VolumeFlowPerArea toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'VolumeFlowPerArea'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(VolumeFlowPerArea other, VolumeFlowPerArea tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current VolumeFlowPerArea. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(VolumeFlowPerAreaUnit unit) - { - if (Unit == unit) - return Value; +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return ToUnit(unit).Value; - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(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); - } + IQuantity IQuantity.ToUnit(VolumeFlowPerAreaUnit unit) => this.ToUnit(unit); - /// - /// 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 NotImplementedException($"Can not 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), - - // 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); - } - - /// - 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)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - 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 @@ -776,137 +601,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(VolumeFlowPerArea)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(VolumeFlowPerArea)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(VolumeFlowPerArea)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(VolumeFlowPerArea)) - return this; - else if (conversionType == typeof(VolumeFlowPerAreaUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return VolumeFlowPerArea.Info; - else if (conversionType == typeof(BaseDimensions)) - return VolumeFlowPerArea.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(VolumeFlowPerArea)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/VolumePerLength.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumePerLength.g.cs index 3b7859334d..dc39898450 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumePerLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumePerLength.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -48,45 +43,109 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class VolumePerLengthInfo: QuantityInfo + { + /// + public VolumePerLengthInfo(string name, VolumePerLengthUnit baseUnit, IEnumerable> unitMappings, VolumePerLength zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public VolumePerLengthInfo(string name, VolumePerLengthUnit baseUnit, IEnumerable> unitMappings, VolumePerLength zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, VolumePerLength.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.VolumePerLength", typeof(VolumePerLength).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the VolumePerLength quantity. + /// + /// A new instance of the class with the default settings. + public static VolumePerLengthInfo CreateDefault() + { + return new VolumePerLengthInfo(nameof(VolumePerLength), DefaultBaseUnit, GetDefaultMappings(), new VolumePerLength(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the VolumePerLength quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static VolumePerLengthInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new VolumePerLengthInfo(nameof(VolumePerLength), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new VolumePerLength(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is L^2. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); + + /// + /// The default base unit of VolumePerLength is CubicMeterPerMeter. All conversions, as defined in the , go via this value. + /// + public static VolumePerLengthUnit DefaultBaseUnit { get; } = VolumePerLengthUnit.CubicMeterPerMeter; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for VolumePerLength. + public static IEnumerable> GetDefaultMappings() + { + yield return new (VolumePerLengthUnit.CubicMeterPerMeter, "CubicMeterPerMeter", "CubicMetersPerMeter", new BaseUnits(length: LengthUnit.Meter)); + 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() { - BaseDimensions = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); - BaseUnit = VolumePerLengthUnit.CubicMeterPerMeter; - Units = Enum.GetValues(typeof(VolumePerLengthUnit)).Cast().ToArray(); - Zero = new VolumePerLength(0, BaseUnit); - Info = new QuantityInfo("VolumePerLength", - new UnitInfo[] - { - new UnitInfo(VolumePerLengthUnit.CubicMeterPerMeter, "CubicMetersPerMeter", new BaseUnits(length: LengthUnit.Meter), "VolumePerLength"), - new UnitInfo(VolumePerLengthUnit.CubicYardPerFoot, "CubicYardsPerFoot", BaseUnits.Undefined, "VolumePerLength"), - new UnitInfo(VolumePerLengthUnit.CubicYardPerUsSurveyFoot, "CubicYardsPerUsSurveyFoot", BaseUnits.Undefined, "VolumePerLength"), - new UnitInfo(VolumePerLengthUnit.ImperialGallonPerMile, "ImperialGallonsPerMile", BaseUnits.Undefined, "VolumePerLength"), - new UnitInfo(VolumePerLengthUnit.LiterPerKilometer, "LitersPerKilometer", BaseUnits.Undefined, "VolumePerLength"), - new UnitInfo(VolumePerLengthUnit.LiterPerMeter, "LitersPerMeter", new BaseUnits(length: LengthUnit.Decimeter), "VolumePerLength"), - new UnitInfo(VolumePerLengthUnit.LiterPerMillimeter, "LitersPerMillimeter", BaseUnits.Undefined, "VolumePerLength"), - new UnitInfo(VolumePerLengthUnit.OilBarrelPerFoot, "OilBarrelsPerFoot", BaseUnits.Undefined, "VolumePerLength"), - new UnitInfo(VolumePerLengthUnit.UsGallonPerMile, "UsGallonsPerMile", BaseUnits.Undefined, "VolumePerLength"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(VolumePerLengthInfo.CreateDefault); } /// @@ -94,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; @@ -108,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); @@ -119,145 +178,124 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of VolumePerLength, which is CubicMeterPerMeter. All conversions go via this value. /// - public static VolumePerLengthUnit BaseUnit { get; } + public static VolumePerLengthUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the VolumePerLength quantity. /// - public static VolumePerLengthUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit CubicMeterPerMeter. /// - public static VolumePerLength Zero { get; } - - /// - public static VolumePerLength AdditiveIdentity => Zero; + public static VolumePerLength Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public VolumePerLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => VolumePerLength.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -286,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); } @@ -294,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); } @@ -302,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); } @@ -310,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); } @@ -318,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); } @@ -326,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); } @@ -334,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); } @@ -342,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); } @@ -350,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); } @@ -361,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); } @@ -422,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); } /// @@ -453,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); } /// @@ -478,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")); /// @@ -486,10 +517,10 @@ public static VolumePerLengthUnit ParseUnit(string str) /// Error parsing string. public static VolumePerLengthUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -504,10 +535,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -523,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; } @@ -563,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current VolumePerLength. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(VolumePerLength), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -656,238 +681,24 @@ public int CompareTo(object? obj) /// public int CompareTo(VolumePerLength other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another VolumePerLength within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(VolumePerLength other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is VolumePerLength otherTyped - && (tolerance is VolumePerLength toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'VolumePerLength'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(VolumePerLength other, VolumePerLength tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current VolumePerLength. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(VolumePerLengthUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(VolumePerLengthUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -902,137 +713,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(VolumePerLength)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(VolumePerLength)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(VolumePerLength)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(VolumePerLength)) - return this; - else if (conversionType == typeof(VolumePerLengthUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return VolumePerLength.Info; - else if (conversionType == typeof(BaseDimensions)) - return VolumePerLength.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(VolumePerLength)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs index f7c82f84b4..bd9cf0f1fc 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -42,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 @@ -51,45 +46,109 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class VolumetricHeatCapacityInfo: QuantityInfo + { + /// + public VolumetricHeatCapacityInfo(string name, VolumetricHeatCapacityUnit baseUnit, IEnumerable> unitMappings, VolumetricHeatCapacity zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public VolumetricHeatCapacityInfo(string name, VolumetricHeatCapacityUnit baseUnit, IEnumerable> unitMappings, VolumetricHeatCapacity zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, VolumetricHeatCapacity.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.VolumetricHeatCapacity", typeof(VolumetricHeatCapacity).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the VolumetricHeatCapacity quantity. + /// + /// A new instance of the class with the default settings. + public static VolumetricHeatCapacityInfo CreateDefault() + { + return new VolumetricHeatCapacityInfo(nameof(VolumetricHeatCapacity), DefaultBaseUnit, GetDefaultMappings(), new VolumetricHeatCapacity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the VolumetricHeatCapacity quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static VolumetricHeatCapacityInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new VolumetricHeatCapacityInfo(nameof(VolumetricHeatCapacity), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new VolumetricHeatCapacity(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// The for is T^-2L^-1MΘ^-1. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-1, 1, -2, 0, -1, 0, 0); + + /// + /// The default base unit of VolumetricHeatCapacity is JoulePerCubicMeterKelvin. All conversions, as defined in the , go via this value. + /// + public static VolumetricHeatCapacityUnit DefaultBaseUnit { get; } = VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for VolumetricHeatCapacity. + public static IEnumerable> GetDefaultMappings() + { + 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, + 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() { - BaseDimensions = new BaseDimensions(-1, 1, -2, 0, -1, 0, 0); - BaseUnit = VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin; - Units = Enum.GetValues(typeof(VolumetricHeatCapacityUnit)).Cast().ToArray(); - Zero = new VolumetricHeatCapacity(0, BaseUnit); - Info = new QuantityInfo("VolumetricHeatCapacity", - new UnitInfo[] - { - new UnitInfo(VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit, "BtusPerCubicFootDegreeFahrenheit", BaseUnits.Undefined, "VolumetricHeatCapacity"), - new UnitInfo(VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius, "CaloriesPerCubicCentimeterDegreeCelsius", BaseUnits.Undefined, "VolumetricHeatCapacity"), - new UnitInfo(VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius, "JoulesPerCubicMeterDegreeCelsius", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius), "VolumetricHeatCapacity"), - new UnitInfo(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, "JoulesPerCubicMeterKelvin", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin), "VolumetricHeatCapacity"), - new UnitInfo(VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius, "KilocaloriesPerCubicCentimeterDegreeCelsius", BaseUnits.Undefined, "VolumetricHeatCapacity"), - new UnitInfo(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius, "KilojoulesPerCubicMeterDegreeCelsius", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius), "VolumetricHeatCapacity"), - new UnitInfo(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin, "KilojoulesPerCubicMeterKelvin", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin), "VolumetricHeatCapacity"), - new UnitInfo(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius, "MegajoulesPerCubicMeterDegreeCelsius", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius), "VolumetricHeatCapacity"), - new UnitInfo(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin, "MegajoulesPerCubicMeterKelvin", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin), "VolumetricHeatCapacity"), - }, - BaseUnit, Zero, BaseDimensions); - - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(VolumetricHeatCapacityInfo.CreateDefault); } /// @@ -97,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; @@ -111,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); @@ -122,145 +181,124 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of VolumetricHeatCapacity, which is JoulePerCubicMeterKelvin. All conversions go via this value. /// - public static VolumetricHeatCapacityUnit BaseUnit { get; } + public static VolumetricHeatCapacityUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the VolumetricHeatCapacity quantity. /// - public static VolumetricHeatCapacityUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit JoulePerCubicMeterKelvin. /// - public static VolumetricHeatCapacity Zero { get; } - - /// - public static VolumetricHeatCapacity AdditiveIdentity => Zero; + public static VolumetricHeatCapacity Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public VolumetricHeatCapacityUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => VolumetricHeatCapacity.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -289,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); } @@ -297,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); } @@ -305,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); } @@ -313,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); } @@ -321,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); } @@ -329,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); } @@ -337,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); } @@ -345,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); } @@ -353,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); } @@ -364,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); } @@ -425,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); } /// @@ -456,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); } /// @@ -481,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")); /// @@ -489,10 +520,10 @@ public static VolumetricHeatCapacityUnit ParseUnit(string str) /// Error parsing string. public static VolumetricHeatCapacityUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -507,10 +538,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -526,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; } @@ -566,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current VolumetricHeatCapacity. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(VolumetricHeatCapacity), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -659,238 +684,24 @@ public int CompareTo(object? obj) /// public int CompareTo(VolumetricHeatCapacity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another VolumetricHeatCapacity within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(VolumetricHeatCapacity other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is VolumetricHeatCapacity otherTyped - && (tolerance is VolumetricHeatCapacity toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'VolumetricHeatCapacity'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(VolumetricHeatCapacity other, VolumetricHeatCapacity tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current VolumetricHeatCapacity. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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 + #region Conversion Methods (explicit implementations for netstandard2.0) - 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)); +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - return As(typedUnit); - } + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - 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)); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(VolumetricHeatCapacityUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - /// - IQuantity IQuantity.ToUnit(VolumetricHeatCapacityUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -905,137 +716,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(VolumetricHeatCapacity)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(VolumetricHeatCapacity)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(VolumetricHeatCapacity)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(VolumetricHeatCapacity)) - return this; - else if (conversionType == typeof(VolumetricHeatCapacityUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return VolumetricHeatCapacity.Info; - else if (conversionType == typeof(BaseDimensions)) - return VolumetricHeatCapacity.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(VolumetricHeatCapacity)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs b/UnitsNet/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs index 990b5b876a..e66e3dd07f 100644 --- a/UnitsNet/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs @@ -17,16 +17,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.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Globalization; -using System.Linq; +using System.Resources; using System.Runtime.Serialization; -using UnitsNet.Units; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,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 @@ -48,42 +43,100 @@ namespace UnitsNet #endif IComparable, IComparable, - IConvertible, IEquatable, IFormattable { /// /// 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; - static WarpingMomentOfInertia() + /// + /// Provides detailed information about the quantity, including its name, base unit, unit mappings, base dimensions, and conversion functions. + /// + public sealed class WarpingMomentOfInertiaInfo: QuantityInfo { - BaseDimensions = new BaseDimensions(6, 0, 0, 0, 0, 0, 0); - BaseUnit = WarpingMomentOfInertiaUnit.MeterToTheSixth; - Units = Enum.GetValues(typeof(WarpingMomentOfInertiaUnit)).Cast().ToArray(); - Zero = new WarpingMomentOfInertia(0, BaseUnit); - Info = new QuantityInfo("WarpingMomentOfInertia", - new UnitInfo[] - { - new UnitInfo(WarpingMomentOfInertiaUnit.CentimeterToTheSixth, "CentimetersToTheSixth", new BaseUnits(length: LengthUnit.Centimeter), "WarpingMomentOfInertia"), - new UnitInfo(WarpingMomentOfInertiaUnit.DecimeterToTheSixth, "DecimetersToTheSixth", new BaseUnits(length: LengthUnit.Decimeter), "WarpingMomentOfInertia"), - new UnitInfo(WarpingMomentOfInertiaUnit.FootToTheSixth, "FeetToTheSixth", new BaseUnits(length: LengthUnit.Foot), "WarpingMomentOfInertia"), - new UnitInfo(WarpingMomentOfInertiaUnit.InchToTheSixth, "InchesToTheSixth", new BaseUnits(length: LengthUnit.Inch), "WarpingMomentOfInertia"), - new UnitInfo(WarpingMomentOfInertiaUnit.MeterToTheSixth, "MetersToTheSixth", new BaseUnits(length: LengthUnit.Meter), "WarpingMomentOfInertia"), - new UnitInfo(WarpingMomentOfInertiaUnit.MillimeterToTheSixth, "MillimetersToTheSixth", new BaseUnits(length: LengthUnit.Millimeter), "WarpingMomentOfInertia"), - }, - BaseUnit, Zero, BaseDimensions); + /// + public WarpingMomentOfInertiaInfo(string name, WarpingMomentOfInertiaUnit baseUnit, IEnumerable> unitMappings, WarpingMomentOfInertia zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations) + : base(name, baseUnit, unitMappings, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + public WarpingMomentOfInertiaInfo(string name, WarpingMomentOfInertiaUnit baseUnit, IEnumerable> unitMappings, WarpingMomentOfInertia zero, BaseDimensions baseDimensions) + : this(name, baseUnit, unitMappings, zero, baseDimensions, WarpingMomentOfInertia.From, new ResourceManager("UnitsNet.GeneratedCode.Resources.WarpingMomentOfInertia", typeof(WarpingMomentOfInertia).Assembly)) + { + } + + /// + /// Creates a new instance of the class with the default settings for the WarpingMomentOfInertia quantity. + /// + /// A new instance of the class with the default settings. + public static WarpingMomentOfInertiaInfo CreateDefault() + { + return new WarpingMomentOfInertiaInfo(nameof(WarpingMomentOfInertia), DefaultBaseUnit, GetDefaultMappings(), new WarpingMomentOfInertia(0, DefaultBaseUnit), DefaultBaseDimensions); + } + + /// + /// Creates a new instance of the class with the default settings for the WarpingMomentOfInertia quantity and a callback for customizing the default unit mappings. + /// + /// + /// A callback function for customizing the default unit mappings. + /// + /// + /// A new instance of the class with the default settings. + /// + public static WarpingMomentOfInertiaInfo CreateDefault(Func>, IEnumerable>> customizeUnits) + { + return new WarpingMomentOfInertiaInfo(nameof(WarpingMomentOfInertia), DefaultBaseUnit, customizeUnits(GetDefaultMappings()), new WarpingMomentOfInertia(0, DefaultBaseUnit), DefaultBaseDimensions); + } - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + /// + /// The for is L^6. + /// + public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(6, 0, 0, 0, 0, 0, 0); + + /// + /// The default base unit of WarpingMomentOfInertia is MeterToTheSixth. All conversions, as defined in the , go via this value. + /// + public static WarpingMomentOfInertiaUnit DefaultBaseUnit { get; } = WarpingMomentOfInertiaUnit.MeterToTheSixth; + + /// + /// Retrieves the default mappings for . + /// + /// An of representing the default unit mappings for WarpingMomentOfInertia. + public static IEnumerable> GetDefaultMappings() + { + 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), + 1000000000000000000 + ); + } + } + + static WarpingMomentOfInertia() + { + Info = UnitsNetSetup.CreateQuantityInfo(WarpingMomentOfInertiaInfo.CreateDefault); } /// @@ -91,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; @@ -105,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); @@ -116,124 +169,109 @@ 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; } + public static QuantityInfo Info { get; } /// /// The of this quantity. /// - public static BaseDimensions BaseDimensions { get; } + public static BaseDimensions BaseDimensions => Info.BaseDimensions; /// /// The base unit of WarpingMomentOfInertia, which is MeterToTheSixth. All conversions go via this value. /// - public static WarpingMomentOfInertiaUnit BaseUnit { get; } + public static WarpingMomentOfInertiaUnit BaseUnit => Info.BaseUnitInfo.Value; /// /// All units of measurement for the WarpingMomentOfInertia quantity. /// - public static WarpingMomentOfInertiaUnit[] Units { get; } + public static IReadOnlyCollection Units => Info.Units; /// /// Gets an instance of this quantity with a value of 0 in the base unit MeterToTheSixth. /// - public static WarpingMomentOfInertia Zero { get; } - - /// - public static WarpingMomentOfInertia AdditiveIdentity => Zero; + public static WarpingMomentOfInertia Zero => Info.Zero; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; - /// - double IQuantity.Value => _value; - - Enum IQuantity.Unit => Unit; + public QuantityValue Value => _value; /// public WarpingMomentOfInertiaUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// - public QuantityInfo QuantityInfo => Info; - - /// - QuantityInfo IQuantity.QuantityInfo => Info; + public QuantityInfo QuantityInfo => Info; /// /// The of this quantity. /// public BaseDimensions Dimensions => WarpingMomentOfInertia.BaseDimensions; + #region Explicit implementations + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + Enum IQuantity.Unit => Unit; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit); + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + QuantityInfo IQuantity.QuantityInfo => Info; + +#if NETSTANDARD2_0 + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + IQuantityInstanceInfo IQuantityInstance.QuantityInfo => Info; +#endif + + #endregion + #endregion #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. /// @@ -262,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); } @@ -270,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); } @@ -278,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); } @@ -286,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); } @@ -294,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); } @@ -302,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); } @@ -313,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); } @@ -374,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); } /// @@ -405,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); } /// @@ -430,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")); /// @@ -438,10 +469,10 @@ public static WarpingMomentOfInertiaUnit ParseUnit(string str) /// Error parsing string. public static WarpingMomentOfInertiaUnit ParseUnit(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.UnitParser.Parse(str, provider); + 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); @@ -456,10 +487,10 @@ 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 UnitsNetSetup.Default.UnitParser.TryParse(str, provider, out unit); + return UnitParser.Default.TryParse(str, Info, provider, out unit); } #endregion @@ -475,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; } @@ -515,88 +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 - - /// 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. + /// + /// Returns the hash code for this instance. + /// + /// A hash code for the current WarpingMomentOfInertia. + public override int GetHashCode() + { + return Comparison.GetHashCode(typeof(WarpingMomentOfInertia), this.As(BaseUnit)); + } + + /// /// 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: /// @@ -608,232 +633,24 @@ public int CompareTo(object? obj) /// public int CompareTo(WarpingMomentOfInertia other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); - } - - /// - /// - /// Compare equality to another WarpingMomentOfInertia within the given absolute or relative tolerance. - /// - /// - /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a percentage of this quantity's value. will be converted into - /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of - /// this quantity's value to be considered equal. - /// - /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). - /// - /// var a = Length.FromMeters(2.0); - /// var b = Length.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Relative); - /// - /// - /// - /// - /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and - /// as a fixed number in this quantity's unit. will be converted into - /// this quantity's unit for comparison. - /// - /// 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.FromInches(50.0); - /// a.Equals(b, 0.01, ComparisonType.Absolute); - /// - /// - /// - /// - /// Note that it is advised against specifying zero difference, due to the nature - /// of floating-point operations and using double internally. - /// - /// - /// The other quantity to compare to. - /// The absolute or relative tolerance value. Must be greater than or equal to 0. - /// The comparison type: either relative or absolute. - /// True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance. - [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.")] - public bool Equals(WarpingMomentOfInertia other, double tolerance, ComparisonType comparisonType) - { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0."); - - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance, - comparisonType: comparisonType); - } - - /// - public bool Equals(IQuantity? other, IQuantity tolerance) - { - return other is WarpingMomentOfInertia otherTyped - && (tolerance is WarpingMomentOfInertia toleranceTyped - ? true - : throw new ArgumentException($"Tolerance quantity ({tolerance.QuantityInfo.Name}) did not match the other quantities of type 'WarpingMomentOfInertia'.", nameof(tolerance))) - && Equals(otherTyped, toleranceTyped); - } - - /// - public bool Equals(WarpingMomentOfInertia other, WarpingMomentOfInertia tolerance) - { - return UnitsNet.Comparison.Equals( - referenceValue: this.Value, - otherValue: other.As(this.Unit), - tolerance: tolerance.As(this.Unit), - comparisonType: ComparisonType.Absolute); - } - - /// - /// Returns the hash code for this instance. - /// - /// A hash code for the current WarpingMomentOfInertia. - public override int GetHashCode() - { - return new { Info.Name, Value, Unit }.GetHashCode(); + 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(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// 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 NotImplementedException($"Can not 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)); + #region Conversion Methods (explicit implementations for netstandard2.0) - 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 WarpingMomentOfInertiaUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(WarpingMomentOfInertiaUnit)} 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(WarpingMomentOfInertiaUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(WarpingMomentOfInertiaUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -848,137 +665,16 @@ public override string ToString() return ToString(null, null); } - /// - /// Gets the default string representation of value and unit using the given format provider. - /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - public string ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - /// - /// - /// Gets the string representation of this instance in the specified format string using . - /// - /// The format string. - /// The string representation. - public string ToString(string? format) - { - return ToString(format, null); - } - - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// - /// The format string. - /// Format to use for localization and number formatting. Defaults to if null. - /// The string representation. public string ToString(string? format, IFormatProvider? provider) { - return QuantityFormatter.Format(this, format, provider); + return QuantityFormatter.Default.Format(this, format, provider); } #endregion - #region IConvertible Methods - - TypeCode IConvertible.GetTypeCode() - { - return TypeCode.Object; - } - - bool IConvertible.ToBoolean(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(WarpingMomentOfInertia)} to bool is not supported."); - } - - byte IConvertible.ToByte(IFormatProvider? provider) - { - return Convert.ToByte(_value); - } - - char IConvertible.ToChar(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(WarpingMomentOfInertia)} to char is not supported."); - } - - DateTime IConvertible.ToDateTime(IFormatProvider? provider) - { - throw new InvalidCastException($"Converting {typeof(WarpingMomentOfInertia)} to DateTime is not supported."); - } - - decimal IConvertible.ToDecimal(IFormatProvider? provider) - { - return Convert.ToDecimal(_value); - } - - double IConvertible.ToDouble(IFormatProvider? provider) - { - return Convert.ToDouble(_value); - } - - short IConvertible.ToInt16(IFormatProvider? provider) - { - return Convert.ToInt16(_value); - } - - int IConvertible.ToInt32(IFormatProvider? provider) - { - return Convert.ToInt32(_value); - } - - long IConvertible.ToInt64(IFormatProvider? provider) - { - return Convert.ToInt64(_value); - } - - sbyte IConvertible.ToSByte(IFormatProvider? provider) - { - return Convert.ToSByte(_value); - } - - float IConvertible.ToSingle(IFormatProvider? provider) - { - return Convert.ToSingle(_value); - } - - string IConvertible.ToString(IFormatProvider? provider) - { - return ToString(null, provider); - } - - object IConvertible.ToType(Type conversionType, IFormatProvider? provider) - { - if (conversionType == typeof(WarpingMomentOfInertia)) - return this; - else if (conversionType == typeof(WarpingMomentOfInertiaUnit)) - return Unit; - else if (conversionType == typeof(QuantityInfo)) - return WarpingMomentOfInertia.Info; - else if (conversionType == typeof(BaseDimensions)) - return WarpingMomentOfInertia.BaseDimensions; - else - throw new InvalidCastException($"Converting {typeof(WarpingMomentOfInertia)} to {conversionType} is not supported."); - } - - ushort IConvertible.ToUInt16(IFormatProvider? provider) - { - return Convert.ToUInt16(_value); - } - - uint IConvertible.ToUInt32(IFormatProvider? provider) - { - return Convert.ToUInt32(_value); - } - - ulong IConvertible.ToUInt64(IFormatProvider? provider) - { - return Convert.ToUInt64(_value); - } - - #endregion } } diff --git a/UnitsNet/GeneratedCode/Quantity.g.cs b/UnitsNet/GeneratedCode/Quantity.g.cs index bbd4d73463..c46b03b6a3 100644 --- a/UnitsNet/GeneratedCode/Quantity.g.cs +++ b/UnitsNet/GeneratedCode/Quantity.g.cs @@ -17,720 +17,163 @@ // 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 UnitsNet.Units; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; - #nullable enable -namespace UnitsNet +namespace UnitsNet; + +/// +/// Dynamically parse or construct quantities when types are only known at runtime. +/// +public partial class Quantity { /// - /// Dynamically parse or construct quantities when types are only known at runtime. + /// Serves as a repository for predefined quantity conversion mappings, facilitating the automatic generation and retrieval of unit conversions in the UnitsNet library. /// - public partial class Quantity + internal static class Provider { /// - /// All QuantityInfo instances mapped by quantity name that are present in UnitsNet by default. + /// All QuantityInfo instances that are present in UnitsNet by default. /// - public static readonly IDictionary ByName = new Dictionary + internal static IReadOnlyList DefaultQuantities => new QuantityInfo[] { - { "AbsorbedDoseOfIonizingRadiation", AbsorbedDoseOfIonizingRadiation.Info }, - { "Acceleration", Acceleration.Info }, - { "AmountOfSubstance", AmountOfSubstance.Info }, - { "AmplitudeRatio", AmplitudeRatio.Info }, - { "Angle", Angle.Info }, - { "Area", Area.Info }, - { "AreaDensity", AreaDensity.Info }, - { "AreaMomentOfInertia", AreaMomentOfInertia.Info }, - { "BitRate", BitRate.Info }, - { "BrakeSpecificFuelConsumption", BrakeSpecificFuelConsumption.Info }, - { "CoefficientOfThermalExpansion", CoefficientOfThermalExpansion.Info }, - { "Compressibility", Compressibility.Info }, - { "Density", Density.Info }, - { "DoseAreaProduct", DoseAreaProduct.Info }, - { "Duration", Duration.Info }, - { "DynamicViscosity", DynamicViscosity.Info }, - { "ElectricAdmittance", ElectricAdmittance.Info }, - { "ElectricApparentEnergy", ElectricApparentEnergy.Info }, - { "ElectricApparentPower", ElectricApparentPower.Info }, - { "ElectricCapacitance", ElectricCapacitance.Info }, - { "ElectricCharge", ElectricCharge.Info }, - { "ElectricChargeDensity", ElectricChargeDensity.Info }, - { "ElectricConductance", ElectricConductance.Info }, - { "ElectricConductivity", ElectricConductivity.Info }, - { "ElectricCurrent", ElectricCurrent.Info }, - { "ElectricCurrentDensity", ElectricCurrentDensity.Info }, - { "ElectricCurrentGradient", ElectricCurrentGradient.Info }, - { "ElectricField", ElectricField.Info }, - { "ElectricImpedance", ElectricImpedance.Info }, - { "ElectricInductance", ElectricInductance.Info }, - { "ElectricPotential", ElectricPotential.Info }, - { "ElectricPotentialChangeRate", ElectricPotentialChangeRate.Info }, - { "ElectricReactance", ElectricReactance.Info }, - { "ElectricReactiveEnergy", ElectricReactiveEnergy.Info }, - { "ElectricReactivePower", ElectricReactivePower.Info }, - { "ElectricResistance", ElectricResistance.Info }, - { "ElectricResistivity", ElectricResistivity.Info }, - { "ElectricSurfaceChargeDensity", ElectricSurfaceChargeDensity.Info }, - { "ElectricSusceptance", ElectricSusceptance.Info }, - { "Energy", Energy.Info }, - { "EnergyDensity", EnergyDensity.Info }, - { "Entropy", Entropy.Info }, - { "FluidResistance", FluidResistance.Info }, - { "Force", Force.Info }, - { "ForceChangeRate", ForceChangeRate.Info }, - { "ForcePerLength", ForcePerLength.Info }, - { "Frequency", Frequency.Info }, - { "FuelEfficiency", FuelEfficiency.Info }, - { "HeatFlux", HeatFlux.Info }, - { "HeatTransferCoefficient", HeatTransferCoefficient.Info }, - { "Illuminance", Illuminance.Info }, - { "Impulse", Impulse.Info }, - { "Information", Information.Info }, - { "Irradiance", Irradiance.Info }, - { "Irradiation", Irradiation.Info }, - { "Jerk", Jerk.Info }, - { "KinematicViscosity", KinematicViscosity.Info }, - { "LeakRate", LeakRate.Info }, - { "Length", Length.Info }, - { "Level", Level.Info }, - { "LinearDensity", LinearDensity.Info }, - { "LinearPowerDensity", LinearPowerDensity.Info }, - { "Luminance", Luminance.Info }, - { "Luminosity", Luminosity.Info }, - { "LuminousFlux", LuminousFlux.Info }, - { "LuminousIntensity", LuminousIntensity.Info }, - { "MagneticField", MagneticField.Info }, - { "MagneticFlux", MagneticFlux.Info }, - { "Magnetization", Magnetization.Info }, - { "Mass", Mass.Info }, - { "MassConcentration", MassConcentration.Info }, - { "MassFlow", MassFlow.Info }, - { "MassFlux", MassFlux.Info }, - { "MassFraction", MassFraction.Info }, - { "MassMomentOfInertia", MassMomentOfInertia.Info }, - { "Molality", Molality.Info }, - { "MolarEnergy", MolarEnergy.Info }, - { "MolarEntropy", MolarEntropy.Info }, - { "MolarFlow", MolarFlow.Info }, - { "Molarity", Molarity.Info }, - { "MolarMass", MolarMass.Info }, - { "Permeability", Permeability.Info }, - { "Permittivity", Permittivity.Info }, - { "PorousMediumPermeability", PorousMediumPermeability.Info }, - { "Power", Power.Info }, - { "PowerDensity", PowerDensity.Info }, - { "PowerRatio", PowerRatio.Info }, - { "Pressure", Pressure.Info }, - { "PressureChangeRate", PressureChangeRate.Info }, - { "RadiationEquivalentDose", RadiationEquivalentDose.Info }, - { "RadiationEquivalentDoseRate", RadiationEquivalentDoseRate.Info }, - { "RadiationExposure", RadiationExposure.Info }, - { "Radioactivity", Radioactivity.Info }, - { "Ratio", Ratio.Info }, - { "RatioChangeRate", RatioChangeRate.Info }, - { "ReciprocalArea", ReciprocalArea.Info }, - { "ReciprocalLength", ReciprocalLength.Info }, - { "RelativeHumidity", RelativeHumidity.Info }, - { "RotationalAcceleration", RotationalAcceleration.Info }, - { "RotationalSpeed", RotationalSpeed.Info }, - { "RotationalStiffness", RotationalStiffness.Info }, - { "RotationalStiffnessPerLength", RotationalStiffnessPerLength.Info }, - { "Scalar", Scalar.Info }, - { "SolidAngle", SolidAngle.Info }, - { "SpecificEnergy", SpecificEnergy.Info }, - { "SpecificEntropy", SpecificEntropy.Info }, - { "SpecificFuelConsumption", SpecificFuelConsumption.Info }, - { "SpecificVolume", SpecificVolume.Info }, - { "SpecificWeight", SpecificWeight.Info }, - { "Speed", Speed.Info }, - { "StandardVolumeFlow", StandardVolumeFlow.Info }, - { "Temperature", Temperature.Info }, - { "TemperatureChangeRate", TemperatureChangeRate.Info }, - { "TemperatureDelta", TemperatureDelta.Info }, - { "TemperatureGradient", TemperatureGradient.Info }, - { "ThermalConductivity", ThermalConductivity.Info }, - { "ThermalInsulance", ThermalInsulance.Info }, - { "Torque", Torque.Info }, - { "Turbidity", Turbidity.Info }, - { "VitaminA", VitaminA.Info }, - { "Volume", Volume.Info }, - { "VolumeConcentration", VolumeConcentration.Info }, - { "VolumeFlow", VolumeFlow.Info }, - { "VolumeFlowPerArea", VolumeFlowPerArea.Info }, - { "VolumePerLength", VolumePerLength.Info }, - { "VolumetricHeatCapacity", VolumetricHeatCapacity.Info }, - { "WarpingMomentOfInertia", WarpingMomentOfInertia.Info }, + AbsorbedDoseOfIonizingRadiation.Info, + Acceleration.Info, + AmountOfSubstance.Info, + AmplitudeRatio.Info, + Angle.Info, + Area.Info, + AreaDensity.Info, + AreaMomentOfInertia.Info, + BitRate.Info, + BrakeSpecificFuelConsumption.Info, + CoefficientOfThermalExpansion.Info, + Compressibility.Info, + Density.Info, + DoseAreaProduct.Info, + Duration.Info, + DynamicViscosity.Info, + ElectricAdmittance.Info, + ElectricApparentEnergy.Info, + ElectricApparentPower.Info, + ElectricCapacitance.Info, + ElectricCharge.Info, + ElectricChargeDensity.Info, + ElectricConductance.Info, + ElectricConductivity.Info, + ElectricCurrent.Info, + ElectricCurrentDensity.Info, + ElectricCurrentGradient.Info, + ElectricField.Info, + ElectricImpedance.Info, + ElectricInductance.Info, + ElectricPotential.Info, + ElectricPotentialChangeRate.Info, + ElectricReactance.Info, + ElectricReactiveEnergy.Info, + ElectricReactivePower.Info, + ElectricResistance.Info, + ElectricResistivity.Info, + ElectricSurfaceChargeDensity.Info, + ElectricSusceptance.Info, + Energy.Info, + EnergyDensity.Info, + Entropy.Info, + FluidResistance.Info, + Force.Info, + ForceChangeRate.Info, + ForcePerLength.Info, + Frequency.Info, + FuelEfficiency.Info, + HeatFlux.Info, + HeatTransferCoefficient.Info, + Illuminance.Info, + Impulse.Info, + Information.Info, + Irradiance.Info, + Irradiation.Info, + Jerk.Info, + KinematicViscosity.Info, + LeakRate.Info, + Length.Info, + Level.Info, + LinearDensity.Info, + LinearPowerDensity.Info, + Luminance.Info, + Luminosity.Info, + LuminousFlux.Info, + LuminousIntensity.Info, + MagneticField.Info, + MagneticFlux.Info, + Magnetization.Info, + Mass.Info, + MassConcentration.Info, + MassFlow.Info, + MassFlux.Info, + MassFraction.Info, + MassMomentOfInertia.Info, + Molality.Info, + MolarEnergy.Info, + MolarEntropy.Info, + MolarFlow.Info, + Molarity.Info, + MolarMass.Info, + Permeability.Info, + Permittivity.Info, + PorousMediumPermeability.Info, + Power.Info, + PowerDensity.Info, + PowerRatio.Info, + Pressure.Info, + PressureChangeRate.Info, + RadiationEquivalentDose.Info, + RadiationEquivalentDoseRate.Info, + RadiationExposure.Info, + Radioactivity.Info, + Ratio.Info, + RatioChangeRate.Info, + ReciprocalArea.Info, + ReciprocalLength.Info, + RelativeHumidity.Info, + RotationalAcceleration.Info, + RotationalSpeed.Info, + RotationalStiffness.Info, + RotationalStiffnessPerLength.Info, + Scalar.Info, + SolidAngle.Info, + SpecificEnergy.Info, + SpecificEntropy.Info, + SpecificFuelConsumption.Info, + SpecificVolume.Info, + SpecificWeight.Info, + Speed.Info, + StandardVolumeFlow.Info, + Temperature.Info, + TemperatureChangeRate.Info, + TemperatureDelta.Info, + TemperatureGradient.Info, + ThermalConductivity.Info, + ThermalInsulance.Info, + Torque.Info, + Turbidity.Info, + VitaminA.Info, + Volume.Info, + VolumeConcentration.Info, + VolumeFlow.Info, + VolumeFlowPerArea.Info, + VolumePerLength.Info, + VolumetricHeatCapacity.Info, + WarpingMomentOfInertia.Info, }; /// - /// Dynamically constructs a quantity of the given with the value in the quantity's base units. + /// All implicit quantity conversions that exist by default. /// - /// The of the quantity to create. - /// The value to construct the quantity with. - /// The created quantity. - public static IQuantity FromQuantityInfo(QuantityInfo quantityInfo, double value) + internal static readonly IReadOnlyList DefaultConversions = new QuantityConversionMapping[] { - return quantityInfo.Name switch - { - "AbsorbedDoseOfIonizingRadiation" => AbsorbedDoseOfIonizingRadiation.From(value, AbsorbedDoseOfIonizingRadiation.BaseUnit), - "Acceleration" => Acceleration.From(value, Acceleration.BaseUnit), - "AmountOfSubstance" => AmountOfSubstance.From(value, AmountOfSubstance.BaseUnit), - "AmplitudeRatio" => AmplitudeRatio.From(value, AmplitudeRatio.BaseUnit), - "Angle" => Angle.From(value, Angle.BaseUnit), - "Area" => Area.From(value, Area.BaseUnit), - "AreaDensity" => AreaDensity.From(value, AreaDensity.BaseUnit), - "AreaMomentOfInertia" => AreaMomentOfInertia.From(value, AreaMomentOfInertia.BaseUnit), - "BitRate" => BitRate.From(value, BitRate.BaseUnit), - "BrakeSpecificFuelConsumption" => BrakeSpecificFuelConsumption.From(value, BrakeSpecificFuelConsumption.BaseUnit), - "CoefficientOfThermalExpansion" => CoefficientOfThermalExpansion.From(value, CoefficientOfThermalExpansion.BaseUnit), - "Compressibility" => Compressibility.From(value, Compressibility.BaseUnit), - "Density" => Density.From(value, Density.BaseUnit), - "DoseAreaProduct" => DoseAreaProduct.From(value, DoseAreaProduct.BaseUnit), - "Duration" => Duration.From(value, Duration.BaseUnit), - "DynamicViscosity" => DynamicViscosity.From(value, DynamicViscosity.BaseUnit), - "ElectricAdmittance" => ElectricAdmittance.From(value, ElectricAdmittance.BaseUnit), - "ElectricApparentEnergy" => ElectricApparentEnergy.From(value, ElectricApparentEnergy.BaseUnit), - "ElectricApparentPower" => ElectricApparentPower.From(value, ElectricApparentPower.BaseUnit), - "ElectricCapacitance" => ElectricCapacitance.From(value, ElectricCapacitance.BaseUnit), - "ElectricCharge" => ElectricCharge.From(value, ElectricCharge.BaseUnit), - "ElectricChargeDensity" => ElectricChargeDensity.From(value, ElectricChargeDensity.BaseUnit), - "ElectricConductance" => ElectricConductance.From(value, ElectricConductance.BaseUnit), - "ElectricConductivity" => ElectricConductivity.From(value, ElectricConductivity.BaseUnit), - "ElectricCurrent" => ElectricCurrent.From(value, ElectricCurrent.BaseUnit), - "ElectricCurrentDensity" => ElectricCurrentDensity.From(value, ElectricCurrentDensity.BaseUnit), - "ElectricCurrentGradient" => ElectricCurrentGradient.From(value, ElectricCurrentGradient.BaseUnit), - "ElectricField" => ElectricField.From(value, ElectricField.BaseUnit), - "ElectricImpedance" => ElectricImpedance.From(value, ElectricImpedance.BaseUnit), - "ElectricInductance" => ElectricInductance.From(value, ElectricInductance.BaseUnit), - "ElectricPotential" => ElectricPotential.From(value, ElectricPotential.BaseUnit), - "ElectricPotentialChangeRate" => ElectricPotentialChangeRate.From(value, ElectricPotentialChangeRate.BaseUnit), - "ElectricReactance" => ElectricReactance.From(value, ElectricReactance.BaseUnit), - "ElectricReactiveEnergy" => ElectricReactiveEnergy.From(value, ElectricReactiveEnergy.BaseUnit), - "ElectricReactivePower" => ElectricReactivePower.From(value, ElectricReactivePower.BaseUnit), - "ElectricResistance" => ElectricResistance.From(value, ElectricResistance.BaseUnit), - "ElectricResistivity" => ElectricResistivity.From(value, ElectricResistivity.BaseUnit), - "ElectricSurfaceChargeDensity" => ElectricSurfaceChargeDensity.From(value, ElectricSurfaceChargeDensity.BaseUnit), - "ElectricSusceptance" => ElectricSusceptance.From(value, ElectricSusceptance.BaseUnit), - "Energy" => Energy.From(value, Energy.BaseUnit), - "EnergyDensity" => EnergyDensity.From(value, EnergyDensity.BaseUnit), - "Entropy" => Entropy.From(value, Entropy.BaseUnit), - "FluidResistance" => FluidResistance.From(value, FluidResistance.BaseUnit), - "Force" => Force.From(value, Force.BaseUnit), - "ForceChangeRate" => ForceChangeRate.From(value, ForceChangeRate.BaseUnit), - "ForcePerLength" => ForcePerLength.From(value, ForcePerLength.BaseUnit), - "Frequency" => Frequency.From(value, Frequency.BaseUnit), - "FuelEfficiency" => FuelEfficiency.From(value, FuelEfficiency.BaseUnit), - "HeatFlux" => HeatFlux.From(value, HeatFlux.BaseUnit), - "HeatTransferCoefficient" => HeatTransferCoefficient.From(value, HeatTransferCoefficient.BaseUnit), - "Illuminance" => Illuminance.From(value, Illuminance.BaseUnit), - "Impulse" => Impulse.From(value, Impulse.BaseUnit), - "Information" => Information.From(value, Information.BaseUnit), - "Irradiance" => Irradiance.From(value, Irradiance.BaseUnit), - "Irradiation" => Irradiation.From(value, Irradiation.BaseUnit), - "Jerk" => Jerk.From(value, Jerk.BaseUnit), - "KinematicViscosity" => KinematicViscosity.From(value, KinematicViscosity.BaseUnit), - "LeakRate" => LeakRate.From(value, LeakRate.BaseUnit), - "Length" => Length.From(value, Length.BaseUnit), - "Level" => Level.From(value, Level.BaseUnit), - "LinearDensity" => LinearDensity.From(value, LinearDensity.BaseUnit), - "LinearPowerDensity" => LinearPowerDensity.From(value, LinearPowerDensity.BaseUnit), - "Luminance" => Luminance.From(value, Luminance.BaseUnit), - "Luminosity" => Luminosity.From(value, Luminosity.BaseUnit), - "LuminousFlux" => LuminousFlux.From(value, LuminousFlux.BaseUnit), - "LuminousIntensity" => LuminousIntensity.From(value, LuminousIntensity.BaseUnit), - "MagneticField" => MagneticField.From(value, MagneticField.BaseUnit), - "MagneticFlux" => MagneticFlux.From(value, MagneticFlux.BaseUnit), - "Magnetization" => Magnetization.From(value, Magnetization.BaseUnit), - "Mass" => Mass.From(value, Mass.BaseUnit), - "MassConcentration" => MassConcentration.From(value, MassConcentration.BaseUnit), - "MassFlow" => MassFlow.From(value, MassFlow.BaseUnit), - "MassFlux" => MassFlux.From(value, MassFlux.BaseUnit), - "MassFraction" => MassFraction.From(value, MassFraction.BaseUnit), - "MassMomentOfInertia" => MassMomentOfInertia.From(value, MassMomentOfInertia.BaseUnit), - "Molality" => Molality.From(value, Molality.BaseUnit), - "MolarEnergy" => MolarEnergy.From(value, MolarEnergy.BaseUnit), - "MolarEntropy" => MolarEntropy.From(value, MolarEntropy.BaseUnit), - "MolarFlow" => MolarFlow.From(value, MolarFlow.BaseUnit), - "Molarity" => Molarity.From(value, Molarity.BaseUnit), - "MolarMass" => MolarMass.From(value, MolarMass.BaseUnit), - "Permeability" => Permeability.From(value, Permeability.BaseUnit), - "Permittivity" => Permittivity.From(value, Permittivity.BaseUnit), - "PorousMediumPermeability" => PorousMediumPermeability.From(value, PorousMediumPermeability.BaseUnit), - "Power" => Power.From(value, Power.BaseUnit), - "PowerDensity" => PowerDensity.From(value, PowerDensity.BaseUnit), - "PowerRatio" => PowerRatio.From(value, PowerRatio.BaseUnit), - "Pressure" => Pressure.From(value, Pressure.BaseUnit), - "PressureChangeRate" => PressureChangeRate.From(value, PressureChangeRate.BaseUnit), - "RadiationEquivalentDose" => RadiationEquivalentDose.From(value, RadiationEquivalentDose.BaseUnit), - "RadiationEquivalentDoseRate" => RadiationEquivalentDoseRate.From(value, RadiationEquivalentDoseRate.BaseUnit), - "RadiationExposure" => RadiationExposure.From(value, RadiationExposure.BaseUnit), - "Radioactivity" => Radioactivity.From(value, Radioactivity.BaseUnit), - "Ratio" => Ratio.From(value, Ratio.BaseUnit), - "RatioChangeRate" => RatioChangeRate.From(value, RatioChangeRate.BaseUnit), - "ReciprocalArea" => ReciprocalArea.From(value, ReciprocalArea.BaseUnit), - "ReciprocalLength" => ReciprocalLength.From(value, ReciprocalLength.BaseUnit), - "RelativeHumidity" => RelativeHumidity.From(value, RelativeHumidity.BaseUnit), - "RotationalAcceleration" => RotationalAcceleration.From(value, RotationalAcceleration.BaseUnit), - "RotationalSpeed" => RotationalSpeed.From(value, RotationalSpeed.BaseUnit), - "RotationalStiffness" => RotationalStiffness.From(value, RotationalStiffness.BaseUnit), - "RotationalStiffnessPerLength" => RotationalStiffnessPerLength.From(value, RotationalStiffnessPerLength.BaseUnit), - "Scalar" => Scalar.From(value, Scalar.BaseUnit), - "SolidAngle" => SolidAngle.From(value, SolidAngle.BaseUnit), - "SpecificEnergy" => SpecificEnergy.From(value, SpecificEnergy.BaseUnit), - "SpecificEntropy" => SpecificEntropy.From(value, SpecificEntropy.BaseUnit), - "SpecificFuelConsumption" => SpecificFuelConsumption.From(value, SpecificFuelConsumption.BaseUnit), - "SpecificVolume" => SpecificVolume.From(value, SpecificVolume.BaseUnit), - "SpecificWeight" => SpecificWeight.From(value, SpecificWeight.BaseUnit), - "Speed" => Speed.From(value, Speed.BaseUnit), - "StandardVolumeFlow" => StandardVolumeFlow.From(value, StandardVolumeFlow.BaseUnit), - "Temperature" => Temperature.From(value, Temperature.BaseUnit), - "TemperatureChangeRate" => TemperatureChangeRate.From(value, TemperatureChangeRate.BaseUnit), - "TemperatureDelta" => TemperatureDelta.From(value, TemperatureDelta.BaseUnit), - "TemperatureGradient" => TemperatureGradient.From(value, TemperatureGradient.BaseUnit), - "ThermalConductivity" => ThermalConductivity.From(value, ThermalConductivity.BaseUnit), - "ThermalInsulance" => ThermalInsulance.From(value, ThermalInsulance.BaseUnit), - "Torque" => Torque.From(value, Torque.BaseUnit), - "Turbidity" => Turbidity.From(value, Turbidity.BaseUnit), - "VitaminA" => VitaminA.From(value, VitaminA.BaseUnit), - "Volume" => Volume.From(value, Volume.BaseUnit), - "VolumeConcentration" => VolumeConcentration.From(value, VolumeConcentration.BaseUnit), - "VolumeFlow" => VolumeFlow.From(value, VolumeFlow.BaseUnit), - "VolumeFlowPerArea" => VolumeFlowPerArea.From(value, VolumeFlowPerArea.BaseUnit), - "VolumePerLength" => VolumePerLength.From(value, VolumePerLength.BaseUnit), - "VolumetricHeatCapacity" => VolumetricHeatCapacity.From(value, VolumetricHeatCapacity.BaseUnit), - "WarpingMomentOfInertia" => WarpingMomentOfInertia.From(value, WarpingMomentOfInertia.BaseUnit), - _ => throw new ArgumentException($"{quantityInfo.Name} is not a supported quantity.") - }; - } - - /// - /// Try to dynamically construct a quantity. - /// - /// Numeric value. - /// Unit enum value. - /// The resulting quantity if successful, otherwise default. - /// True if successful with assigned the value, otherwise false. - public static bool TryFrom(double value, Enum? unit, [NotNullWhen(true)] out IQuantity? quantity) - { - quantity = unit switch - { - AbsorbedDoseOfIonizingRadiationUnit absorbedDoseOfIonizingRadiationUnit => AbsorbedDoseOfIonizingRadiation.From(value, absorbedDoseOfIonizingRadiationUnit), - AccelerationUnit accelerationUnit => Acceleration.From(value, accelerationUnit), - AmountOfSubstanceUnit amountOfSubstanceUnit => AmountOfSubstance.From(value, amountOfSubstanceUnit), - AmplitudeRatioUnit amplitudeRatioUnit => AmplitudeRatio.From(value, amplitudeRatioUnit), - AngleUnit angleUnit => Angle.From(value, angleUnit), - AreaUnit areaUnit => Area.From(value, areaUnit), - AreaDensityUnit areaDensityUnit => AreaDensity.From(value, areaDensityUnit), - AreaMomentOfInertiaUnit areaMomentOfInertiaUnit => AreaMomentOfInertia.From(value, areaMomentOfInertiaUnit), - BitRateUnit bitRateUnit => BitRate.From(value, bitRateUnit), - BrakeSpecificFuelConsumptionUnit brakeSpecificFuelConsumptionUnit => BrakeSpecificFuelConsumption.From(value, brakeSpecificFuelConsumptionUnit), - CoefficientOfThermalExpansionUnit coefficientOfThermalExpansionUnit => CoefficientOfThermalExpansion.From(value, coefficientOfThermalExpansionUnit), - CompressibilityUnit compressibilityUnit => Compressibility.From(value, compressibilityUnit), - DensityUnit densityUnit => Density.From(value, densityUnit), - DoseAreaProductUnit doseAreaProductUnit => DoseAreaProduct.From(value, doseAreaProductUnit), - DurationUnit durationUnit => Duration.From(value, durationUnit), - DynamicViscosityUnit dynamicViscosityUnit => DynamicViscosity.From(value, dynamicViscosityUnit), - ElectricAdmittanceUnit electricAdmittanceUnit => ElectricAdmittance.From(value, electricAdmittanceUnit), - ElectricApparentEnergyUnit electricApparentEnergyUnit => ElectricApparentEnergy.From(value, electricApparentEnergyUnit), - ElectricApparentPowerUnit electricApparentPowerUnit => ElectricApparentPower.From(value, electricApparentPowerUnit), - ElectricCapacitanceUnit electricCapacitanceUnit => ElectricCapacitance.From(value, electricCapacitanceUnit), - ElectricChargeUnit electricChargeUnit => ElectricCharge.From(value, electricChargeUnit), - ElectricChargeDensityUnit electricChargeDensityUnit => ElectricChargeDensity.From(value, electricChargeDensityUnit), - ElectricConductanceUnit electricConductanceUnit => ElectricConductance.From(value, electricConductanceUnit), - ElectricConductivityUnit electricConductivityUnit => ElectricConductivity.From(value, electricConductivityUnit), - ElectricCurrentUnit electricCurrentUnit => ElectricCurrent.From(value, electricCurrentUnit), - ElectricCurrentDensityUnit electricCurrentDensityUnit => ElectricCurrentDensity.From(value, electricCurrentDensityUnit), - ElectricCurrentGradientUnit electricCurrentGradientUnit => ElectricCurrentGradient.From(value, electricCurrentGradientUnit), - ElectricFieldUnit electricFieldUnit => ElectricField.From(value, electricFieldUnit), - ElectricImpedanceUnit electricImpedanceUnit => ElectricImpedance.From(value, electricImpedanceUnit), - ElectricInductanceUnit electricInductanceUnit => ElectricInductance.From(value, electricInductanceUnit), - ElectricPotentialUnit electricPotentialUnit => ElectricPotential.From(value, electricPotentialUnit), - ElectricPotentialChangeRateUnit electricPotentialChangeRateUnit => ElectricPotentialChangeRate.From(value, electricPotentialChangeRateUnit), - ElectricReactanceUnit electricReactanceUnit => ElectricReactance.From(value, electricReactanceUnit), - ElectricReactiveEnergyUnit electricReactiveEnergyUnit => ElectricReactiveEnergy.From(value, electricReactiveEnergyUnit), - ElectricReactivePowerUnit electricReactivePowerUnit => ElectricReactivePower.From(value, electricReactivePowerUnit), - ElectricResistanceUnit electricResistanceUnit => ElectricResistance.From(value, electricResistanceUnit), - ElectricResistivityUnit electricResistivityUnit => ElectricResistivity.From(value, electricResistivityUnit), - ElectricSurfaceChargeDensityUnit electricSurfaceChargeDensityUnit => ElectricSurfaceChargeDensity.From(value, electricSurfaceChargeDensityUnit), - ElectricSusceptanceUnit electricSusceptanceUnit => ElectricSusceptance.From(value, electricSusceptanceUnit), - EnergyUnit energyUnit => Energy.From(value, energyUnit), - EnergyDensityUnit energyDensityUnit => EnergyDensity.From(value, energyDensityUnit), - EntropyUnit entropyUnit => Entropy.From(value, entropyUnit), - FluidResistanceUnit fluidResistanceUnit => FluidResistance.From(value, fluidResistanceUnit), - ForceUnit forceUnit => Force.From(value, forceUnit), - ForceChangeRateUnit forceChangeRateUnit => ForceChangeRate.From(value, forceChangeRateUnit), - ForcePerLengthUnit forcePerLengthUnit => ForcePerLength.From(value, forcePerLengthUnit), - FrequencyUnit frequencyUnit => Frequency.From(value, frequencyUnit), - FuelEfficiencyUnit fuelEfficiencyUnit => FuelEfficiency.From(value, fuelEfficiencyUnit), - HeatFluxUnit heatFluxUnit => HeatFlux.From(value, heatFluxUnit), - HeatTransferCoefficientUnit heatTransferCoefficientUnit => HeatTransferCoefficient.From(value, heatTransferCoefficientUnit), - IlluminanceUnit illuminanceUnit => Illuminance.From(value, illuminanceUnit), - ImpulseUnit impulseUnit => Impulse.From(value, impulseUnit), - InformationUnit informationUnit => Information.From(value, informationUnit), - IrradianceUnit irradianceUnit => Irradiance.From(value, irradianceUnit), - IrradiationUnit irradiationUnit => Irradiation.From(value, irradiationUnit), - JerkUnit jerkUnit => Jerk.From(value, jerkUnit), - KinematicViscosityUnit kinematicViscosityUnit => KinematicViscosity.From(value, kinematicViscosityUnit), - LeakRateUnit leakRateUnit => LeakRate.From(value, leakRateUnit), - LengthUnit lengthUnit => Length.From(value, lengthUnit), - LevelUnit levelUnit => Level.From(value, levelUnit), - LinearDensityUnit linearDensityUnit => LinearDensity.From(value, linearDensityUnit), - LinearPowerDensityUnit linearPowerDensityUnit => LinearPowerDensity.From(value, linearPowerDensityUnit), - LuminanceUnit luminanceUnit => Luminance.From(value, luminanceUnit), - LuminosityUnit luminosityUnit => Luminosity.From(value, luminosityUnit), - LuminousFluxUnit luminousFluxUnit => LuminousFlux.From(value, luminousFluxUnit), - LuminousIntensityUnit luminousIntensityUnit => LuminousIntensity.From(value, luminousIntensityUnit), - MagneticFieldUnit magneticFieldUnit => MagneticField.From(value, magneticFieldUnit), - MagneticFluxUnit magneticFluxUnit => MagneticFlux.From(value, magneticFluxUnit), - MagnetizationUnit magnetizationUnit => Magnetization.From(value, magnetizationUnit), - MassUnit massUnit => Mass.From(value, massUnit), - MassConcentrationUnit massConcentrationUnit => MassConcentration.From(value, massConcentrationUnit), - MassFlowUnit massFlowUnit => MassFlow.From(value, massFlowUnit), - MassFluxUnit massFluxUnit => MassFlux.From(value, massFluxUnit), - MassFractionUnit massFractionUnit => MassFraction.From(value, massFractionUnit), - MassMomentOfInertiaUnit massMomentOfInertiaUnit => MassMomentOfInertia.From(value, massMomentOfInertiaUnit), - MolalityUnit molalityUnit => Molality.From(value, molalityUnit), - MolarEnergyUnit molarEnergyUnit => MolarEnergy.From(value, molarEnergyUnit), - MolarEntropyUnit molarEntropyUnit => MolarEntropy.From(value, molarEntropyUnit), - MolarFlowUnit molarFlowUnit => MolarFlow.From(value, molarFlowUnit), - MolarityUnit molarityUnit => Molarity.From(value, molarityUnit), - MolarMassUnit molarMassUnit => MolarMass.From(value, molarMassUnit), - PermeabilityUnit permeabilityUnit => Permeability.From(value, permeabilityUnit), - PermittivityUnit permittivityUnit => Permittivity.From(value, permittivityUnit), - PorousMediumPermeabilityUnit porousMediumPermeabilityUnit => PorousMediumPermeability.From(value, porousMediumPermeabilityUnit), - PowerUnit powerUnit => Power.From(value, powerUnit), - PowerDensityUnit powerDensityUnit => PowerDensity.From(value, powerDensityUnit), - PowerRatioUnit powerRatioUnit => PowerRatio.From(value, powerRatioUnit), - PressureUnit pressureUnit => Pressure.From(value, pressureUnit), - PressureChangeRateUnit pressureChangeRateUnit => PressureChangeRate.From(value, pressureChangeRateUnit), - RadiationEquivalentDoseUnit radiationEquivalentDoseUnit => RadiationEquivalentDose.From(value, radiationEquivalentDoseUnit), - RadiationEquivalentDoseRateUnit radiationEquivalentDoseRateUnit => RadiationEquivalentDoseRate.From(value, radiationEquivalentDoseRateUnit), - RadiationExposureUnit radiationExposureUnit => RadiationExposure.From(value, radiationExposureUnit), - RadioactivityUnit radioactivityUnit => Radioactivity.From(value, radioactivityUnit), - RatioUnit ratioUnit => Ratio.From(value, ratioUnit), - RatioChangeRateUnit ratioChangeRateUnit => RatioChangeRate.From(value, ratioChangeRateUnit), - ReciprocalAreaUnit reciprocalAreaUnit => ReciprocalArea.From(value, reciprocalAreaUnit), - ReciprocalLengthUnit reciprocalLengthUnit => ReciprocalLength.From(value, reciprocalLengthUnit), - RelativeHumidityUnit relativeHumidityUnit => RelativeHumidity.From(value, relativeHumidityUnit), - RotationalAccelerationUnit rotationalAccelerationUnit => RotationalAcceleration.From(value, rotationalAccelerationUnit), - RotationalSpeedUnit rotationalSpeedUnit => RotationalSpeed.From(value, rotationalSpeedUnit), - RotationalStiffnessUnit rotationalStiffnessUnit => RotationalStiffness.From(value, rotationalStiffnessUnit), - RotationalStiffnessPerLengthUnit rotationalStiffnessPerLengthUnit => RotationalStiffnessPerLength.From(value, rotationalStiffnessPerLengthUnit), - ScalarUnit scalarUnit => Scalar.From(value, scalarUnit), - SolidAngleUnit solidAngleUnit => SolidAngle.From(value, solidAngleUnit), - SpecificEnergyUnit specificEnergyUnit => SpecificEnergy.From(value, specificEnergyUnit), - SpecificEntropyUnit specificEntropyUnit => SpecificEntropy.From(value, specificEntropyUnit), - SpecificFuelConsumptionUnit specificFuelConsumptionUnit => SpecificFuelConsumption.From(value, specificFuelConsumptionUnit), - SpecificVolumeUnit specificVolumeUnit => SpecificVolume.From(value, specificVolumeUnit), - SpecificWeightUnit specificWeightUnit => SpecificWeight.From(value, specificWeightUnit), - SpeedUnit speedUnit => Speed.From(value, speedUnit), - StandardVolumeFlowUnit standardVolumeFlowUnit => StandardVolumeFlow.From(value, standardVolumeFlowUnit), - TemperatureUnit temperatureUnit => Temperature.From(value, temperatureUnit), - TemperatureChangeRateUnit temperatureChangeRateUnit => TemperatureChangeRate.From(value, temperatureChangeRateUnit), - TemperatureDeltaUnit temperatureDeltaUnit => TemperatureDelta.From(value, temperatureDeltaUnit), - TemperatureGradientUnit temperatureGradientUnit => TemperatureGradient.From(value, temperatureGradientUnit), - ThermalConductivityUnit thermalConductivityUnit => ThermalConductivity.From(value, thermalConductivityUnit), - ThermalInsulanceUnit thermalInsulanceUnit => ThermalInsulance.From(value, thermalInsulanceUnit), - TorqueUnit torqueUnit => Torque.From(value, torqueUnit), - TurbidityUnit turbidityUnit => Turbidity.From(value, turbidityUnit), - VitaminAUnit vitaminAUnit => VitaminA.From(value, vitaminAUnit), - VolumeUnit volumeUnit => Volume.From(value, volumeUnit), - VolumeConcentrationUnit volumeConcentrationUnit => VolumeConcentration.From(value, volumeConcentrationUnit), - VolumeFlowUnit volumeFlowUnit => VolumeFlow.From(value, volumeFlowUnit), - VolumeFlowPerAreaUnit volumeFlowPerAreaUnit => VolumeFlowPerArea.From(value, volumeFlowPerAreaUnit), - VolumePerLengthUnit volumePerLengthUnit => VolumePerLength.From(value, volumePerLengthUnit), - VolumetricHeatCapacityUnit volumetricHeatCapacityUnit => VolumetricHeatCapacity.From(value, volumetricHeatCapacityUnit), - WarpingMomentOfInertiaUnit warpingMomentOfInertiaUnit => WarpingMomentOfInertia.From(value, warpingMomentOfInertiaUnit), - _ => null - }; - - return quantity is not null; - } - - /// - /// Try to dynamically parse a quantity string representation. - /// - /// The format provider to use for lookup. Defaults to if null. - /// Type of quantity, such as . - /// Quantity string representation, such as "1.5 kg". Must be compatible with given quantity type. - /// The resulting quantity if successful, otherwise default. - /// The parsed quantity. - public static bool TryParse(IFormatProvider? formatProvider, Type quantityType, [NotNullWhen(true)] string? quantityString, [NotNullWhen(true)] out IQuantity? quantity) - { - quantity = default(IQuantity); - - if (!typeof(IQuantity).IsAssignableFrom(quantityType)) - return false; - - var parser = UnitsNetSetup.Default.QuantityParser; - - return quantityType switch - { - Type _ when quantityType == typeof(AbsorbedDoseOfIonizingRadiation) => parser.TryParse(quantityString, formatProvider, AbsorbedDoseOfIonizingRadiation.From, out quantity), - Type _ when quantityType == typeof(Acceleration) => parser.TryParse(quantityString, formatProvider, Acceleration.From, out quantity), - Type _ when quantityType == typeof(AmountOfSubstance) => parser.TryParse(quantityString, formatProvider, AmountOfSubstance.From, out quantity), - Type _ when quantityType == typeof(AmplitudeRatio) => parser.TryParse(quantityString, formatProvider, AmplitudeRatio.From, out quantity), - Type _ when quantityType == typeof(Angle) => parser.TryParse(quantityString, formatProvider, Angle.From, out quantity), - Type _ when quantityType == typeof(Area) => parser.TryParse(quantityString, formatProvider, Area.From, out quantity), - Type _ when quantityType == typeof(AreaDensity) => parser.TryParse(quantityString, formatProvider, AreaDensity.From, out quantity), - Type _ when quantityType == typeof(AreaMomentOfInertia) => parser.TryParse(quantityString, formatProvider, AreaMomentOfInertia.From, out quantity), - Type _ when quantityType == typeof(BitRate) => parser.TryParse(quantityString, formatProvider, BitRate.From, out quantity), - Type _ when quantityType == typeof(BrakeSpecificFuelConsumption) => parser.TryParse(quantityString, formatProvider, BrakeSpecificFuelConsumption.From, out quantity), - Type _ when quantityType == typeof(CoefficientOfThermalExpansion) => parser.TryParse(quantityString, formatProvider, CoefficientOfThermalExpansion.From, out quantity), - Type _ when quantityType == typeof(Compressibility) => parser.TryParse(quantityString, formatProvider, Compressibility.From, out quantity), - Type _ when quantityType == typeof(Density) => parser.TryParse(quantityString, formatProvider, Density.From, out quantity), - Type _ when quantityType == typeof(DoseAreaProduct) => parser.TryParse(quantityString, formatProvider, DoseAreaProduct.From, out quantity), - Type _ when quantityType == typeof(Duration) => parser.TryParse(quantityString, formatProvider, Duration.From, out quantity), - Type _ when quantityType == typeof(DynamicViscosity) => parser.TryParse(quantityString, formatProvider, DynamicViscosity.From, out quantity), - Type _ when quantityType == typeof(ElectricAdmittance) => parser.TryParse(quantityString, formatProvider, ElectricAdmittance.From, out quantity), - Type _ when quantityType == typeof(ElectricApparentEnergy) => parser.TryParse(quantityString, formatProvider, ElectricApparentEnergy.From, out quantity), - Type _ when quantityType == typeof(ElectricApparentPower) => parser.TryParse(quantityString, formatProvider, ElectricApparentPower.From, out quantity), - Type _ when quantityType == typeof(ElectricCapacitance) => parser.TryParse(quantityString, formatProvider, ElectricCapacitance.From, out quantity), - Type _ when quantityType == typeof(ElectricCharge) => parser.TryParse(quantityString, formatProvider, ElectricCharge.From, out quantity), - Type _ when quantityType == typeof(ElectricChargeDensity) => parser.TryParse(quantityString, formatProvider, ElectricChargeDensity.From, out quantity), - Type _ when quantityType == typeof(ElectricConductance) => parser.TryParse(quantityString, formatProvider, ElectricConductance.From, out quantity), - Type _ when quantityType == typeof(ElectricConductivity) => parser.TryParse(quantityString, formatProvider, ElectricConductivity.From, out quantity), - Type _ when quantityType == typeof(ElectricCurrent) => parser.TryParse(quantityString, formatProvider, ElectricCurrent.From, out quantity), - Type _ when quantityType == typeof(ElectricCurrentDensity) => parser.TryParse(quantityString, formatProvider, ElectricCurrentDensity.From, out quantity), - Type _ when quantityType == typeof(ElectricCurrentGradient) => parser.TryParse(quantityString, formatProvider, ElectricCurrentGradient.From, out quantity), - Type _ when quantityType == typeof(ElectricField) => parser.TryParse(quantityString, formatProvider, ElectricField.From, out quantity), - Type _ when quantityType == typeof(ElectricImpedance) => parser.TryParse(quantityString, formatProvider, ElectricImpedance.From, out quantity), - Type _ when quantityType == typeof(ElectricInductance) => parser.TryParse(quantityString, formatProvider, ElectricInductance.From, out quantity), - Type _ when quantityType == typeof(ElectricPotential) => parser.TryParse(quantityString, formatProvider, ElectricPotential.From, out quantity), - Type _ when quantityType == typeof(ElectricPotentialChangeRate) => parser.TryParse(quantityString, formatProvider, ElectricPotentialChangeRate.From, out quantity), - Type _ when quantityType == typeof(ElectricReactance) => parser.TryParse(quantityString, formatProvider, ElectricReactance.From, out quantity), - Type _ when quantityType == typeof(ElectricReactiveEnergy) => parser.TryParse(quantityString, formatProvider, ElectricReactiveEnergy.From, out quantity), - Type _ when quantityType == typeof(ElectricReactivePower) => parser.TryParse(quantityString, formatProvider, ElectricReactivePower.From, out quantity), - Type _ when quantityType == typeof(ElectricResistance) => parser.TryParse(quantityString, formatProvider, ElectricResistance.From, out quantity), - Type _ when quantityType == typeof(ElectricResistivity) => parser.TryParse(quantityString, formatProvider, ElectricResistivity.From, out quantity), - Type _ when quantityType == typeof(ElectricSurfaceChargeDensity) => parser.TryParse(quantityString, formatProvider, ElectricSurfaceChargeDensity.From, out quantity), - Type _ when quantityType == typeof(ElectricSusceptance) => parser.TryParse(quantityString, formatProvider, ElectricSusceptance.From, out quantity), - Type _ when quantityType == typeof(Energy) => parser.TryParse(quantityString, formatProvider, Energy.From, out quantity), - Type _ when quantityType == typeof(EnergyDensity) => parser.TryParse(quantityString, formatProvider, EnergyDensity.From, out quantity), - Type _ when quantityType == typeof(Entropy) => parser.TryParse(quantityString, formatProvider, Entropy.From, out quantity), - Type _ when quantityType == typeof(FluidResistance) => parser.TryParse(quantityString, formatProvider, FluidResistance.From, out quantity), - Type _ when quantityType == typeof(Force) => parser.TryParse(quantityString, formatProvider, Force.From, out quantity), - Type _ when quantityType == typeof(ForceChangeRate) => parser.TryParse(quantityString, formatProvider, ForceChangeRate.From, out quantity), - Type _ when quantityType == typeof(ForcePerLength) => parser.TryParse(quantityString, formatProvider, ForcePerLength.From, out quantity), - Type _ when quantityType == typeof(Frequency) => parser.TryParse(quantityString, formatProvider, Frequency.From, out quantity), - Type _ when quantityType == typeof(FuelEfficiency) => parser.TryParse(quantityString, formatProvider, FuelEfficiency.From, out quantity), - Type _ when quantityType == typeof(HeatFlux) => parser.TryParse(quantityString, formatProvider, HeatFlux.From, out quantity), - Type _ when quantityType == typeof(HeatTransferCoefficient) => parser.TryParse(quantityString, formatProvider, HeatTransferCoefficient.From, out quantity), - Type _ when quantityType == typeof(Illuminance) => parser.TryParse(quantityString, formatProvider, Illuminance.From, out quantity), - Type _ when quantityType == typeof(Impulse) => parser.TryParse(quantityString, formatProvider, Impulse.From, out quantity), - Type _ when quantityType == typeof(Information) => parser.TryParse(quantityString, formatProvider, Information.From, out quantity), - Type _ when quantityType == typeof(Irradiance) => parser.TryParse(quantityString, formatProvider, Irradiance.From, out quantity), - Type _ when quantityType == typeof(Irradiation) => parser.TryParse(quantityString, formatProvider, Irradiation.From, out quantity), - Type _ when quantityType == typeof(Jerk) => parser.TryParse(quantityString, formatProvider, Jerk.From, out quantity), - Type _ when quantityType == typeof(KinematicViscosity) => parser.TryParse(quantityString, formatProvider, KinematicViscosity.From, out quantity), - Type _ when quantityType == typeof(LeakRate) => parser.TryParse(quantityString, formatProvider, LeakRate.From, out quantity), - Type _ when quantityType == typeof(Length) => parser.TryParse(quantityString, formatProvider, Length.From, out quantity), - Type _ when quantityType == typeof(Level) => parser.TryParse(quantityString, formatProvider, Level.From, out quantity), - Type _ when quantityType == typeof(LinearDensity) => parser.TryParse(quantityString, formatProvider, LinearDensity.From, out quantity), - Type _ when quantityType == typeof(LinearPowerDensity) => parser.TryParse(quantityString, formatProvider, LinearPowerDensity.From, out quantity), - Type _ when quantityType == typeof(Luminance) => parser.TryParse(quantityString, formatProvider, Luminance.From, out quantity), - Type _ when quantityType == typeof(Luminosity) => parser.TryParse(quantityString, formatProvider, Luminosity.From, out quantity), - Type _ when quantityType == typeof(LuminousFlux) => parser.TryParse(quantityString, formatProvider, LuminousFlux.From, out quantity), - Type _ when quantityType == typeof(LuminousIntensity) => parser.TryParse(quantityString, formatProvider, LuminousIntensity.From, out quantity), - Type _ when quantityType == typeof(MagneticField) => parser.TryParse(quantityString, formatProvider, MagneticField.From, out quantity), - Type _ when quantityType == typeof(MagneticFlux) => parser.TryParse(quantityString, formatProvider, MagneticFlux.From, out quantity), - Type _ when quantityType == typeof(Magnetization) => parser.TryParse(quantityString, formatProvider, Magnetization.From, out quantity), - Type _ when quantityType == typeof(Mass) => parser.TryParse(quantityString, formatProvider, Mass.From, out quantity), - Type _ when quantityType == typeof(MassConcentration) => parser.TryParse(quantityString, formatProvider, MassConcentration.From, out quantity), - Type _ when quantityType == typeof(MassFlow) => parser.TryParse(quantityString, formatProvider, MassFlow.From, out quantity), - Type _ when quantityType == typeof(MassFlux) => parser.TryParse(quantityString, formatProvider, MassFlux.From, out quantity), - Type _ when quantityType == typeof(MassFraction) => parser.TryParse(quantityString, formatProvider, MassFraction.From, out quantity), - Type _ when quantityType == typeof(MassMomentOfInertia) => parser.TryParse(quantityString, formatProvider, MassMomentOfInertia.From, out quantity), - Type _ when quantityType == typeof(Molality) => parser.TryParse(quantityString, formatProvider, Molality.From, out quantity), - Type _ when quantityType == typeof(MolarEnergy) => parser.TryParse(quantityString, formatProvider, MolarEnergy.From, out quantity), - Type _ when quantityType == typeof(MolarEntropy) => parser.TryParse(quantityString, formatProvider, MolarEntropy.From, out quantity), - Type _ when quantityType == typeof(MolarFlow) => parser.TryParse(quantityString, formatProvider, MolarFlow.From, out quantity), - Type _ when quantityType == typeof(Molarity) => parser.TryParse(quantityString, formatProvider, Molarity.From, out quantity), - Type _ when quantityType == typeof(MolarMass) => parser.TryParse(quantityString, formatProvider, MolarMass.From, out quantity), - Type _ when quantityType == typeof(Permeability) => parser.TryParse(quantityString, formatProvider, Permeability.From, out quantity), - Type _ when quantityType == typeof(Permittivity) => parser.TryParse(quantityString, formatProvider, Permittivity.From, out quantity), - Type _ when quantityType == typeof(PorousMediumPermeability) => parser.TryParse(quantityString, formatProvider, PorousMediumPermeability.From, out quantity), - Type _ when quantityType == typeof(Power) => parser.TryParse(quantityString, formatProvider, Power.From, out quantity), - Type _ when quantityType == typeof(PowerDensity) => parser.TryParse(quantityString, formatProvider, PowerDensity.From, out quantity), - Type _ when quantityType == typeof(PowerRatio) => parser.TryParse(quantityString, formatProvider, PowerRatio.From, out quantity), - Type _ when quantityType == typeof(Pressure) => parser.TryParse(quantityString, formatProvider, Pressure.From, out quantity), - Type _ when quantityType == typeof(PressureChangeRate) => parser.TryParse(quantityString, formatProvider, PressureChangeRate.From, out quantity), - Type _ when quantityType == typeof(RadiationEquivalentDose) => parser.TryParse(quantityString, formatProvider, RadiationEquivalentDose.From, out quantity), - Type _ when quantityType == typeof(RadiationEquivalentDoseRate) => parser.TryParse(quantityString, formatProvider, RadiationEquivalentDoseRate.From, out quantity), - Type _ when quantityType == typeof(RadiationExposure) => parser.TryParse(quantityString, formatProvider, RadiationExposure.From, out quantity), - Type _ when quantityType == typeof(Radioactivity) => parser.TryParse(quantityString, formatProvider, Radioactivity.From, out quantity), - Type _ when quantityType == typeof(Ratio) => parser.TryParse(quantityString, formatProvider, Ratio.From, out quantity), - Type _ when quantityType == typeof(RatioChangeRate) => parser.TryParse(quantityString, formatProvider, RatioChangeRate.From, out quantity), - Type _ when quantityType == typeof(ReciprocalArea) => parser.TryParse(quantityString, formatProvider, ReciprocalArea.From, out quantity), - Type _ when quantityType == typeof(ReciprocalLength) => parser.TryParse(quantityString, formatProvider, ReciprocalLength.From, out quantity), - Type _ when quantityType == typeof(RelativeHumidity) => parser.TryParse(quantityString, formatProvider, RelativeHumidity.From, out quantity), - Type _ when quantityType == typeof(RotationalAcceleration) => parser.TryParse(quantityString, formatProvider, RotationalAcceleration.From, out quantity), - Type _ when quantityType == typeof(RotationalSpeed) => parser.TryParse(quantityString, formatProvider, RotationalSpeed.From, out quantity), - Type _ when quantityType == typeof(RotationalStiffness) => parser.TryParse(quantityString, formatProvider, RotationalStiffness.From, out quantity), - Type _ when quantityType == typeof(RotationalStiffnessPerLength) => parser.TryParse(quantityString, formatProvider, RotationalStiffnessPerLength.From, out quantity), - Type _ when quantityType == typeof(Scalar) => parser.TryParse(quantityString, formatProvider, Scalar.From, out quantity), - Type _ when quantityType == typeof(SolidAngle) => parser.TryParse(quantityString, formatProvider, SolidAngle.From, out quantity), - Type _ when quantityType == typeof(SpecificEnergy) => parser.TryParse(quantityString, formatProvider, SpecificEnergy.From, out quantity), - Type _ when quantityType == typeof(SpecificEntropy) => parser.TryParse(quantityString, formatProvider, SpecificEntropy.From, out quantity), - Type _ when quantityType == typeof(SpecificFuelConsumption) => parser.TryParse(quantityString, formatProvider, SpecificFuelConsumption.From, out quantity), - Type _ when quantityType == typeof(SpecificVolume) => parser.TryParse(quantityString, formatProvider, SpecificVolume.From, out quantity), - Type _ when quantityType == typeof(SpecificWeight) => parser.TryParse(quantityString, formatProvider, SpecificWeight.From, out quantity), - Type _ when quantityType == typeof(Speed) => parser.TryParse(quantityString, formatProvider, Speed.From, out quantity), - Type _ when quantityType == typeof(StandardVolumeFlow) => parser.TryParse(quantityString, formatProvider, StandardVolumeFlow.From, out quantity), - Type _ when quantityType == typeof(Temperature) => parser.TryParse(quantityString, formatProvider, Temperature.From, out quantity), - Type _ when quantityType == typeof(TemperatureChangeRate) => parser.TryParse(quantityString, formatProvider, TemperatureChangeRate.From, out quantity), - Type _ when quantityType == typeof(TemperatureDelta) => parser.TryParse(quantityString, formatProvider, TemperatureDelta.From, out quantity), - Type _ when quantityType == typeof(TemperatureGradient) => parser.TryParse(quantityString, formatProvider, TemperatureGradient.From, out quantity), - Type _ when quantityType == typeof(ThermalConductivity) => parser.TryParse(quantityString, formatProvider, ThermalConductivity.From, out quantity), - Type _ when quantityType == typeof(ThermalInsulance) => parser.TryParse(quantityString, formatProvider, ThermalInsulance.From, out quantity), - Type _ when quantityType == typeof(Torque) => parser.TryParse(quantityString, formatProvider, Torque.From, out quantity), - Type _ when quantityType == typeof(Turbidity) => parser.TryParse(quantityString, formatProvider, Turbidity.From, out quantity), - Type _ when quantityType == typeof(VitaminA) => parser.TryParse(quantityString, formatProvider, VitaminA.From, out quantity), - Type _ when quantityType == typeof(Volume) => parser.TryParse(quantityString, formatProvider, Volume.From, out quantity), - Type _ when quantityType == typeof(VolumeConcentration) => parser.TryParse(quantityString, formatProvider, VolumeConcentration.From, out quantity), - Type _ when quantityType == typeof(VolumeFlow) => parser.TryParse(quantityString, formatProvider, VolumeFlow.From, out quantity), - Type _ when quantityType == typeof(VolumeFlowPerArea) => parser.TryParse(quantityString, formatProvider, VolumeFlowPerArea.From, out quantity), - Type _ when quantityType == typeof(VolumePerLength) => parser.TryParse(quantityString, formatProvider, VolumePerLength.From, out quantity), - Type _ when quantityType == typeof(VolumetricHeatCapacity) => parser.TryParse(quantityString, formatProvider, VolumetricHeatCapacity.From, out quantity), - Type _ when quantityType == typeof(WarpingMomentOfInertia) => parser.TryParse(quantityString, formatProvider, WarpingMomentOfInertia.From, out quantity), - _ => false - }; - } - - internal static IEnumerable GetQuantityTypes() - { - yield return typeof(AbsorbedDoseOfIonizingRadiation); - yield return typeof(Acceleration); - yield return typeof(AmountOfSubstance); - yield return typeof(AmplitudeRatio); - yield return typeof(Angle); - yield return typeof(Area); - yield return typeof(AreaDensity); - yield return typeof(AreaMomentOfInertia); - yield return typeof(BitRate); - yield return typeof(BrakeSpecificFuelConsumption); - yield return typeof(CoefficientOfThermalExpansion); - yield return typeof(Compressibility); - yield return typeof(Density); - yield return typeof(DoseAreaProduct); - yield return typeof(Duration); - yield return typeof(DynamicViscosity); - yield return typeof(ElectricAdmittance); - yield return typeof(ElectricApparentEnergy); - yield return typeof(ElectricApparentPower); - yield return typeof(ElectricCapacitance); - yield return typeof(ElectricCharge); - yield return typeof(ElectricChargeDensity); - yield return typeof(ElectricConductance); - yield return typeof(ElectricConductivity); - yield return typeof(ElectricCurrent); - yield return typeof(ElectricCurrentDensity); - yield return typeof(ElectricCurrentGradient); - yield return typeof(ElectricField); - yield return typeof(ElectricImpedance); - yield return typeof(ElectricInductance); - yield return typeof(ElectricPotential); - yield return typeof(ElectricPotentialChangeRate); - yield return typeof(ElectricReactance); - yield return typeof(ElectricReactiveEnergy); - yield return typeof(ElectricReactivePower); - yield return typeof(ElectricResistance); - yield return typeof(ElectricResistivity); - yield return typeof(ElectricSurfaceChargeDensity); - yield return typeof(ElectricSusceptance); - yield return typeof(Energy); - yield return typeof(EnergyDensity); - yield return typeof(Entropy); - yield return typeof(FluidResistance); - yield return typeof(Force); - yield return typeof(ForceChangeRate); - yield return typeof(ForcePerLength); - yield return typeof(Frequency); - yield return typeof(FuelEfficiency); - yield return typeof(HeatFlux); - yield return typeof(HeatTransferCoefficient); - yield return typeof(Illuminance); - yield return typeof(Impulse); - yield return typeof(Information); - yield return typeof(Irradiance); - yield return typeof(Irradiation); - yield return typeof(Jerk); - yield return typeof(KinematicViscosity); - yield return typeof(LeakRate); - yield return typeof(Length); - yield return typeof(Level); - yield return typeof(LinearDensity); - yield return typeof(LinearPowerDensity); - yield return typeof(Luminance); - yield return typeof(Luminosity); - yield return typeof(LuminousFlux); - yield return typeof(LuminousIntensity); - yield return typeof(MagneticField); - yield return typeof(MagneticFlux); - yield return typeof(Magnetization); - yield return typeof(Mass); - yield return typeof(MassConcentration); - yield return typeof(MassFlow); - yield return typeof(MassFlux); - yield return typeof(MassFraction); - yield return typeof(MassMomentOfInertia); - yield return typeof(Molality); - yield return typeof(MolarEnergy); - yield return typeof(MolarEntropy); - yield return typeof(MolarFlow); - yield return typeof(Molarity); - yield return typeof(MolarMass); - yield return typeof(Permeability); - yield return typeof(Permittivity); - yield return typeof(PorousMediumPermeability); - yield return typeof(Power); - yield return typeof(PowerDensity); - yield return typeof(PowerRatio); - yield return typeof(Pressure); - yield return typeof(PressureChangeRate); - yield return typeof(RadiationEquivalentDose); - yield return typeof(RadiationEquivalentDoseRate); - yield return typeof(RadiationExposure); - yield return typeof(Radioactivity); - yield return typeof(Ratio); - yield return typeof(RatioChangeRate); - yield return typeof(ReciprocalArea); - yield return typeof(ReciprocalLength); - yield return typeof(RelativeHumidity); - yield return typeof(RotationalAcceleration); - yield return typeof(RotationalSpeed); - yield return typeof(RotationalStiffness); - yield return typeof(RotationalStiffnessPerLength); - yield return typeof(Scalar); - yield return typeof(SolidAngle); - yield return typeof(SpecificEnergy); - yield return typeof(SpecificEntropy); - yield return typeof(SpecificFuelConsumption); - yield return typeof(SpecificVolume); - yield return typeof(SpecificWeight); - yield return typeof(Speed); - yield return typeof(StandardVolumeFlow); - yield return typeof(Temperature); - yield return typeof(TemperatureChangeRate); - yield return typeof(TemperatureDelta); - yield return typeof(TemperatureGradient); - yield return typeof(ThermalConductivity); - yield return typeof(ThermalInsulance); - yield return typeof(Torque); - yield return typeof(Turbidity); - yield return typeof(VitaminA); - yield return typeof(Volume); - yield return typeof(VolumeConcentration); - yield return typeof(VolumeFlow); - yield return typeof(VolumeFlowPerArea); - yield return typeof(VolumePerLength); - yield return typeof(VolumetricHeatCapacity); - yield return typeof(WarpingMomentOfInertia); - } + 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 2cd4c2623f..98765665bc 100644 --- a/UnitsNet/GenericMath/GenericMathExtensions.cs +++ b/UnitsNet/GenericMath/GenericMathExtensions.cs @@ -20,11 +20,19 @@ public static class GenericMathExtensions /// The type of the quantity elements in the source sequence. /// The sum of the quantities, using the unit of the first element in the sequence. /// - /// Note that the generic math LINQ support is still missing in the BCL, but is being worked on: - /// - /// API Proposal: Generic LINQ Numeric Operators · Issue - /// #64031 · dotnet/runtime - /// + /// Unless + /// + /// requires a custom implementation for the interface, you + /// should consider switching to one of the more performant versions of this extension, found in the + /// , and + /// . + /// + /// Note that the generic math LINQ support is still missing in the BCL, but is being worked on: + /// + /// API Proposal: Generic LINQ Numeric Operators · Issue + /// #64031 · dotnet/runtime + /// + /// /// public static TQuantity Sum(this IEnumerable source) where TQuantity : IQuantity, IAdditionOperators, IAdditiveIdentity @@ -52,20 +60,28 @@ public static TQuantity Sum(this IEnumerable source) /// The average of the quantities, using the unit of the first element in the sequence. /// Thrown when the sequence is empty. /// - /// Note that the generic math LINQ support is still missing in the BCL, but is being worked on: - /// - /// API Proposal: Generic LINQ Numeric Operators · Issue - /// #64031 · dotnet/runtime - /// + /// Unless + /// + /// requires a custom implementation for the interface, you + /// should consider switching to one of the more performant versions of this extension, found in the + /// , and + /// . + /// + /// Note that the generic math LINQ support is still missing in the BCL, but is being worked on: + /// + /// API Proposal: Generic LINQ Numeric Operators · Issue + /// #64031 · dotnet/runtime + /// + /// /// 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/IArithmeticQuantity.cs b/UnitsNet/IArithmeticQuantity.cs index 7bb86eaa4e..949839b2d4 100644 --- a/UnitsNet/IArithmeticQuantity.cs +++ b/UnitsNet/IArithmeticQuantity.cs @@ -1,32 +1,92 @@ -// 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; +#if NET using System.Numerics; +#endif namespace UnitsNet; /// -/// An that (in .NET 7+) implements generic math interfaces for arithmetic operations. +/// Represents a quantity that has both magnitude and direction, supporting various arithmetic operations and +/// comparisons. /// -/// The type itself, for the CRT pattern. -/// The underlying unit enum type. -public interface IArithmeticQuantity : IQuantity +/// +/// This interface defines standard linear arithmetic operations such as addition, subtraction, multiplication, and +/// division. +/// These types of quantities naturally support comparison operations with either absolute or relative tolerance, which +/// is useful for determining equality within a certain margin of error. +/// +/// For more information, see the Wikipedia page on +/// +/// Dimensional +/// Analysis +/// +/// . +/// +/// +/// The type that implements this interface. +public interface ILinearQuantity : IQuantityInstance #if NET7_0_OR_GREATER - , IAdditionOperators , IAdditiveIdentity - , ISubtractionOperators - , IMultiplyOperators - , IDivisionOperators - , IUnaryNegationOperators #endif - where TSelf : IArithmeticQuantity - where TUnitType : struct, Enum + where TSelf : ILinearQuantity { #if NET7_0_OR_GREATER /// /// The zero value of this quantity. /// static abstract TSelf Zero { get; } + + static TSelf IAdditiveIdentity.AdditiveIdentity + { + get => TSelf.Zero; + } + +#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 +} + +/// +/// An that (in .NET 7+) implements generic math interfaces for arithmetic +/// operations. +/// +/// The type itself, for the CRT pattern. +/// The underlying unit enum type. +// [Obsolete("This interface is replaced by the IVectorQuantity and ILogarithmicQuantity alternatives")] +public interface IArithmeticQuantity : IQuantity, ILinearQuantity +#if NET7_0_OR_GREATER + , IAdditionOperators + , ISubtractionOperators + , IMultiplyOperators + , IDivisionOperators + , IUnaryNegationOperators #endif + where TSelf : IArithmeticQuantity + where TUnitType : struct, Enum +{ } diff --git a/UnitsNet/IQuantity.cs b/UnitsNet/IQuantity.cs index d9e6c2c221..20ae5a6914 100644 --- a/UnitsNet/IQuantity.cs +++ b/UnitsNet/IQuantity.cs @@ -5,6 +5,7 @@ using System.Globalization; #if NET7_0_OR_GREATER using System.Numerics; + #endif using UnitsNet.Units; @@ -30,17 +31,23 @@ 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 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. - double As(UnitSystem unitSystem); + // /// + // /// 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 /// /// /// Compare equality to given a for the maximum allowed +/- difference. @@ -54,15 +61,13 @@ public interface IQuantity : IFormattable /// 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. 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. @@ -72,7 +77,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 . @@ -81,24 +86,38 @@ 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 , which affects things like . + /// 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 string representation of value and unit. Uses two significant digits after radix. + /// Gets the unique key for the unit type and its corresponding value. /// - /// String representation. - /// Format to use for localization and number formatting. Defaults to if null. - string ToString(IFormatProvider? provider); + /// + /// This property is particularly useful when using an enum-based unit in a hash-based collection, + /// as it avoids the boxing that would normally occur when casting the enum to . + /// + UnitKey UnitKey { get; } } /// @@ -113,11 +132,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; } @@ -129,17 +148,49 @@ 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); - - /// - /// Converts to a quantity with a unit determined by the given , which affects things like . - /// If multiple units were found for the given , the first match will be used. - /// - /// The to convert the quantity to. - /// A new quantity with the determined 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 + + #region Implementation of IQuantity + + QuantityInfo IQuantity.QuantityInfo + { + get => QuantityInfo; + } + + Enum IQuantity.Unit + { + get => Unit; + } + + #endregion + +#endif + } + + /// + /// + /// This is a specialization of that is used (internally) for constraining certain + /// methods, without having to include the unit type as additional generic parameter. + /// + /// + public interface IQuantityInstance : IQuantity + where TQuantity : IQuantity + { +#if NET + internal static abstract TQuantity Create(QuantityValue value, UnitKey unit); +#else + /// + new IQuantityInstanceInfo QuantityInfo { get; } +#endif } /// @@ -147,10 +198,71 @@ public interface IQuantity : IQuantity /// /// The type itself, for the CRT pattern. /// The underlying unit enum type. - public interface IQuantity : IQuantity + public interface IQuantity : IQuantityInstance, 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; } + +#if NET + /// + /// Creates an instance of the quantity from a specified value and unit. + /// + /// 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(QuantityValue value, TUnitType unit); + + static TSelf IQuantityInstance.Create(QuantityValue value, UnitKey unit) => TSelf.From(value, unit.ToUnit()); + + IQuantity IQuantity.ToUnit(TUnitType unit) + { + return TSelf.From(UnitConverter.Default.ConvertValue(Value, Unit, unit), unit); + } + + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) + { + TUnitType unit = QuantityInfo.GetDefaultUnit(unitSystem); + return TSelf.From(UnitConverter.Default.ConvertValue(Value, Unit, unit), unit); + } + +#endif + + } + + /// + /// An that (in .NET 7+) implements generic math interfaces for arithmetic operations. + /// + /// The type itself, for the CRT pattern. + /// + public interface IAffineQuantity : IQuantityInstance + #if NET7_0_OR_GREATER + , IAdditiveIdentity + where TOffset : IAdditiveIdentity + #endif + where TSelf : IAffineQuantity + { + #if NET7_0_OR_GREATER + /// + /// The zero value of this quantity. + /// + static abstract TSelf Zero { get; } + + static TOffset IAdditiveIdentity.AdditiveIdentity => TOffset.AdditiveIdentity; + #endif + + #if EXTENDED_EQUALS_INTERFACE /// /// /// Compare equality to given a for the maximum allowed +/- difference. @@ -171,6 +283,86 @@ public interface IQuantity : IQuantity /// 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); + 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 + { + } + + + /// + /// 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. + /// + /// The type itself, for the CRT pattern. + /// + /// Logarithmic quantities are different from linear quantities in that they represent values on a logarithmic scale. + /// This interface extends and provides additional functionality specific + /// to logarithmic quantities, including arithmetic operations and a logarithmic scaling factor. + /// The logarithmic scale assumed here is base-10. + /// + public interface ILogarithmicQuantity : IQuantityInstance + #if NET7_0_OR_GREATER + , IMultiplicativeIdentity + #endif + where TSelf : ILogarithmicQuantity + { + #if NET7_0_OR_GREATER + /// + /// 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. + /// + static abstract QuantityValue LogarithmicScalingFactor { get; } + + /// + /// The zero value of this quantity. + /// + static abstract TSelf Zero { get; } + + 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. + /// + 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/IQuantityInfo.cs b/UnitsNet/IQuantityInfo.cs new file mode 100644 index 0000000000..97b9cdb1e6 --- /dev/null +++ b/UnitsNet/IQuantityInfo.cs @@ -0,0 +1,217 @@ +// 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.Resources; +using UnitsNet.Units; + +namespace UnitsNet; + +/// +/// Information about the quantity, such as names, unit values and zero quantity. +/// This is useful to enumerate units and present names with quantities and units +/// chose dynamically at runtime, such as unit conversion apps or allowing the user to change the +/// unit representation. +/// +/// +/// Typically you obtain this by looking it up via . +/// +public interface IQuantityInfo +{ + /// + /// Quantity name, such as "Length" or "Mass". + /// + string Name { get; } + + /// + /// The units for this quantity. + /// + IReadOnlyList UnitInfos { get; } + + /// + /// The base unit of this quantity. + /// + UnitInfo BaseUnitInfo { get; } + + /// + /// Zero value of quantity, such as . + /// + IQuantity Zero { get; } + + /// + /// Quantity value type, such as or . + /// + Type QuantityType { get; } + + /// + /// Unit enum type, such as or . + /// + Type UnitType { get; } + + /// + /// The for a quantity. + /// + BaseDimensions BaseDimensions { get; } + + /// + /// Used for loading the localization resources associated with the current quantity. + /// + ResourceManager? UnitAbbreviations { get; } + + /// + /// Gets the associated with the specified unit. + /// + /// The unit for which to get the . + /// The associated with the specified unit. + /// Thrown if the specified unit is not found. + /// + /// Thrown when the type of > does not match the type of the current . + /// + UnitInfo this[UnitKey unit] { get; } + + // /// + // /// Attempts to retrieve the unit information for the specified unit. + // /// + // /// The unit for which to retrieve information. + // /// + // /// 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. + // /// + // bool TryGetUnitInfo(UnitKey unit, [NotNullWhen(true)] out UnitInfo? unitInfo); + + /// + /// Gets the whose is a subset of . + /// + /// + /// Length.Info.GetUnitInfoFor(unitSystemWithFootAsLengthUnit) returns for + /// . + /// + /// The to check against. + /// + /// The that has that is a subset of + /// . + /// + /// is null. + /// No unit was found that is a subset of . + /// + /// More than one unit was found that is a subset of + /// . + /// + UnitInfo GetUnitInfoFor(BaseUnits baseUnits); + + /// + /// Gets an of that have that is a + /// subset of . + /// + /// The to check against. + /// + /// An of that have that is a + /// subset of . + /// + /// is null. + IEnumerable GetUnitInfosFor(BaseUnits baseUnits); + + // /// + // /// Creates an instance of from the specified value and unit. + // /// + // /// The numerical value of the quantity. + // /// The unit of the quantity, represented as an enumeration. + // /// An instance of representing the specified value and unit. + // /// Thrown when is null. + // /// Thrown when is not a valid unit for this quantity. + // IQuantity From(QuantityValue value, Enum unit); +} + +// /// +// /// +// /// This is a specialization of , for when the unit type is known. +// /// Typically, you obtain this by looking it up statically from or +// /// , or dynamically via . +// /// +// /// The unit enum type, such as . +// public interface IQuantityInfo : IQuantityInfo +// where TUnit : struct, Enum +// { +// /// +// new IQuantity Zero { get; } +// +// /// +// new IReadOnlyCollection> UnitInfos { get; } +// +// /// +// new UnitInfo BaseUnitInfo { get; } +// +// /// +// UnitInfo this[TUnit unit] { get; } +// +// /// +// bool TryGetUnitInfo(TUnit unit, [NotNullWhen(true)] out UnitInfo? unitInfo); +// +// /// +// new UnitInfo GetUnitInfoFor(BaseUnits baseUnits); +// +// /// +// new IEnumerable> GetUnitInfosFor(BaseUnits baseUnits); +// +// /// +// IQuantity From(QuantityValue value, TUnit unit); +// } + +/// +/// +/// This is a specialization of that is used (internally) for constraining certain +/// methods, without having to include the unit type as additional generic parameter. +/// +public interface IQuantityInstanceInfo : IQuantityInfo + where TQuantity : IQuantity +{ + /// + new TQuantity Zero { get; } + + internal TQuantity Create(QuantityValue value, UnitKey unitKey); +} + +// /// +// public interface IQuantityInfo : IQuantityInfo, IQuantityInstanceInfo +// where TQuantity : IQuantity +// where TUnit : struct, Enum +// { +// /// +// new TQuantity Zero { get; } +// +// /// +// new IReadOnlyCollection> UnitInfos { get; } +// +// /// +// new UnitInfo BaseUnitInfo { get; } +// +// /// +// new UnitInfo this[TUnit unit] { get; } +// +// /// +// new UnitInfo GetUnitInfoFor(BaseUnits baseUnits); +// +// /// +// new IEnumerable> GetUnitInfosFor(BaseUnits baseUnits); +// +// /// +// new TQuantity From(QuantityValue value, TUnit unit); +// +// // #if NET +// // +// // #region Implementation of IQuantityInstanceInfo +// // +// // TQuantity IQuantityInstanceInfo.Create(QuantityValue value, UnitKey unitKey) +// // { +// // return From(value, unitKey.ToUnit()); +// // } +// // +// // #endregion +// // +// // #endif +// } diff --git a/UnitsNet/IUnitDefinition.cs b/UnitsNet/IUnitDefinition.cs new file mode 100644 index 0000000000..6d67b8bac5 --- /dev/null +++ b/UnitsNet/IUnitDefinition.cs @@ -0,0 +1,97 @@ +// 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; + +namespace UnitsNet; + +/// +/// Defines the configuration for mapping units, including their name, plural name, base units, +/// and conversion expressions to and from the base units. +/// +public interface IUnitDefinition +{ + /// + /// The singular name of the unit, such as "Centimeter". + /// + string Name { get; } + + /// + /// The plural name of the unit, such as "Centimeters". + /// + string PluralName { get; } + + /// + /// 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; } +} + +/// +/// Defines the configuration for mapping units, including their value, name, plural name, and base units. +/// +/// The type of the unit enumeration. +public interface IUnitDefinition : IUnitDefinition + where TUnit : struct, Enum +{ + /// + /// The enum value of the unit, such as . + /// + TUnit Value { 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 34148b3866..af234f76b7 100644 --- a/UnitsNet/QuantityFormatter.cs +++ b/UnitsNet/QuantityFormatter.cs @@ -2,6 +2,7 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Collections.Generic; using System.Globalization; namespace UnitsNet; @@ -11,63 +12,42 @@ namespace UnitsNet; /// public class QuantityFormatter { + private readonly UnitAbbreviationsCache _unitAbbreviations; + /// - /// Formats a quantity using the given format string and format provider. + /// Initializes a new instance of the class. /// - /// The quantity to format. - /// The format string. - /// - /// The valid format strings are as follows: - /// - /// - /// A standard numeric format string. - /// - /// Any of the - /// - /// Standard format specifiers - /// . - /// - /// - /// - /// "A" or "a". - /// The default unit abbreviation for , such as "m". - /// - /// - /// "A0", "A1", ..., "An" or "a0", "a1", ..., "an". - /// - /// The n-th unit abbreviation for the . "a0" is the same as "a". - /// A will be thrown if the requested abbreviation index does not exist. - /// - /// - /// - /// "S" or "s". - /// - /// The value with 2 significant digits after the radix followed by the unit abbreviation, such as - /// "1.23 m". - /// - /// - /// - /// "S0", "S1", ..., "Sn" or "s0", "s1", ..., "sn". - /// - /// The value with n significant digits after the radix followed by the unit abbreviation. "S2" - /// and "s2" is the same as "s". - /// - /// - /// - /// For more information about the formatter, see the - /// - /// QuantityFormatter - /// section - /// . - /// - /// The string representation. - /// Thrown when the format specifier is invalid. + /// The cache of unit abbreviations used for formatting quantities. + public QuantityFormatter(UnitAbbreviationsCache unitAbbreviations) + { + _unitAbbreviations = unitAbbreviations ?? throw new ArgumentNullException(nameof(unitAbbreviations)); + } + + /// + /// Gets the default instance of the class. + /// + /// + /// The default instance, initialized with the default + /// . + /// + public static QuantityFormatter Default => UnitsNetSetup.Default.Formatter; + + /// + [Obsolete("Consider switching to one of the more performant instance methods available on QuantityFormatter.Default.")] public static string Format(IQuantity quantity, string format) where TUnitType : struct, Enum { return Format(quantity, format, CultureInfo.CurrentCulture); } + /// + [Obsolete("Consider switching to one of the more performant instance methods available on QuantityFormatter.Default.")] + public static string Format(IQuantity quantity, string? format, IFormatProvider? formatProvider) + where TUnitType : struct, Enum + { + return Default.Format(quantity, format, formatProvider); + } + /// /// Formats a quantity using the given format string and format provider. /// @@ -84,9 +64,11 @@ public static string Format(IQuantity quantity, string for /// A standard numeric format string. /// /// Any of the - /// + /// /// Standard format specifiers - /// . + /// + /// . /// /// /// @@ -97,7 +79,10 @@ public static string Format(IQuantity quantity, string for /// "A0", "A1", ..., "An" or "a0", "a1", ..., "an". /// /// The n-th unit abbreviation for the . "a0" is the same as "a". - /// A will be thrown if the requested abbreviation index does not exist. + /// + /// A will be thrown if the requested abbreviation index does not + /// exist. + /// /// /// /// @@ -119,18 +104,13 @@ public static string Format(IQuantity quantity, string for /// /// QuantityFormatter /// section - /// . + /// + /// . /// /// The string representation. /// Thrown when the format specifier is invalid. - public static string Format(IQuantity quantity, string? format, IFormatProvider? formatProvider) - where TUnitType : struct, Enum - { - return FormatUntrimmed(quantity, format, formatProvider).TrimEnd(); - } - - private static string FormatUntrimmed(IQuantity quantity, string? format, IFormatProvider? formatProvider) - where TUnitType : struct, Enum + public string Format(TQuantity quantity, string? format = null, IFormatProvider? formatProvider = null) + where TQuantity : IQuantity { formatProvider ??= CultureInfo.CurrentCulture; if (format is null) @@ -141,12 +121,18 @@ private static string FormatUntrimmed(IQuantity quantity, { 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 UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(quantity.Unit, formatProvider); + return _unitAbbreviations.GetDefaultAbbreviation(quantity.UnitKey, formatProvider); case 'U' or 'u': throw new FormatException($"The \"{format}\" format is no longer supported: consider using the Unit property."); case 'V' or 'v': @@ -164,13 +150,11 @@ private static string FormatUntrimmed(IQuantity quantity, 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): { - var abbreviations = UnitsNetSetup.Default.UnitAbbreviations.GetUnitAbbreviations(quantity.Unit, formatProvider); + IReadOnlyList abbreviations = _unitAbbreviations.GetUnitAbbreviations(quantity.UnitKey, formatProvider); - if (abbreviationIndex >= abbreviations.Length) + if (abbreviationIndex >= abbreviations.Count) { throw new FormatException($"The \"{format}\" format string is invalid because the index is out of range."); } @@ -182,13 +166,11 @@ private static string FormatUntrimmed(IQuantity quantity, 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): { - var abbreviations = UnitsNetSetup.Default.UnitAbbreviations.GetUnitAbbreviations(quantity.Unit, formatProvider); + IReadOnlyList abbreviations = _unitAbbreviations.GetUnitAbbreviations(quantity.UnitKey, formatProvider); - if (abbreviationIndex >= abbreviations.Length) + if (abbreviationIndex >= abbreviations.Count) { throw new FormatException($"The \"{format}\" format string is invalid because the index is out of range."); } @@ -202,23 +184,18 @@ private static string FormatUntrimmed(IQuantity quantity, #endif } } + + var abbreviation = _unitAbbreviations.GetDefaultAbbreviation(quantity.UnitKey, formatProvider); + if (abbreviation.Length == 0) + { + return quantity.Value.ToString(format, formatProvider); + } - // Anything else is a standard numeric format string with default unit abbreviation postfix. - return FormatWithValueAndAbbreviation(quantity, format, formatProvider); - } - - private static string FormatWithValueAndAbbreviation(IQuantity quantity, string format, IFormatProvider formatProvider) - where TUnitType : struct, Enum - { - var abbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(quantity.Unit, formatProvider); - return string.Format(formatProvider, $"{{0:{format}}} {{1}}", quantity.Value, abbreviation); - } - - private static string ToStringWithSignificantDigitsAfterRadix(IQuantity quantity, IFormatProvider formatProvider, int number) - where TUnitType : struct, Enum - { - var formatForSignificantDigits = UnitFormatter.GetFormat(quantity.Value, number); - var formatArgs = UnitFormatter.GetFormatArgs(quantity.Unit, quantity.Value, formatProvider, []); - return string.Format(formatProvider, formatForSignificantDigits, formatArgs); +#if NET + // TODO see about using the Span overloads (net 8+) + return quantity.Value.ToString(format, formatProvider) + ' ' + abbreviation; +#else + return quantity.Value.ToString(format, formatProvider) + ' ' + abbreviation; +#endif } } diff --git a/UnitsNet/QuantityInfo.cs b/UnitsNet/QuantityInfo.cs index d50bf8ce69..28d27c3e5c 100644 --- a/UnitsNet/QuantityInfo.cs +++ b/UnitsNet/QuantityInfo.cs @@ -1,178 +1,658 @@ // 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; using System.Linq; -using UnitsNet.Units; +using System.Resources; -namespace UnitsNet +namespace UnitsNet; + +/// +[DebuggerDisplay("{Name} ({QuantityType.FullName})")] +public abstract class QuantityInfo : IQuantityInfo { /// - /// Information about the quantity, such as names, unit values and zero quantity. - /// This is useful to enumerate units and present names with quantities and units - /// chose dynamically at runtime, such as unit conversion apps or allowing the user to change the - /// unit representation. + /// Initializes a new instance of the class. /// - /// - /// Typically you obtain this by looking it up via . - /// - public class QuantityInfo - { - /// - /// Constructs an instance. - /// - /// Name of the quantity. - /// The unit enum type, such as . - /// The information about the units for this quantity. - /// The base unit enum value. - /// The zero quantity. - /// The base dimensions of the quantity. - /// Quantity type can not be undefined. - /// If units -or- baseUnit -or- zero -or- baseDimensions is null. - public QuantityInfo(string name, Type unitType, UnitInfo[] unitInfos, Enum baseUnit, IQuantity zero, BaseDimensions baseDimensions) - { - if (baseUnit == null) throw new ArgumentNullException(nameof(baseUnit)); + /// The name of the quantity. + /// The type representing the quantity. + /// The base dimensions of the quantity. + /// + /// When provided, the resource manager used for localizing the quantity's unit abbreviations. + /// + /// + /// Thrown if , , or is + /// null. + /// + protected QuantityInfo(string name, Type quantityType, BaseDimensions baseDimensions, ResourceManager? unitAbbreviations) + { + Name = name ?? throw new ArgumentNullException(nameof(name)); + QuantityType = quantityType ?? throw new ArgumentNullException(nameof(quantityType)); + BaseDimensions = baseDimensions ?? throw new ArgumentNullException(nameof(baseDimensions)); + UnitAbbreviations = unitAbbreviations; + } - BaseDimensions = baseDimensions ?? throw new ArgumentNullException(nameof(baseDimensions)); - Zero = zero ?? throw new ArgumentNullException(nameof(zero)); - Name = name ?? throw new ArgumentNullException(nameof(name)); - UnitType = unitType ?? throw new ArgumentNullException(nameof(unitType)); - UnitInfos = unitInfos ?? throw new ArgumentNullException(nameof(unitInfos)); + /// + public string Name { get; } - BaseUnitInfo = UnitInfos.First(unitInfo => unitInfo.Value.Equals(baseUnit)); - QuantityType = zero.GetType(); - } + /// + public Type QuantityType { get; } - /// - /// Quantity name, such as "Length" or "Mass". - /// - public string Name { get; } - - /// - /// The units for this quantity. - /// - public UnitInfo[] UnitInfos { get; } - - /// - /// The base unit of this quantity. - /// - public UnitInfo BaseUnitInfo { get; } - - /// - /// Zero value of quantity, such as . - /// - public IQuantity Zero { get; } - - /// - /// Unit enum type, such as or . - /// - public Type UnitType { get; } - - /// - /// Quantity value type, such as or . - /// - public Type QuantityType { get; } - - /// - [Obsolete("Replaced by the QuantityType property.")] - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - public Type ValueType - { - get => QuantityType; - } + /// + [Obsolete("Replaced by the QuantityType property.")] + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + public Type ValueType + { + get => QuantityType; + } - /// - /// The for a quantity. - /// - public BaseDimensions BaseDimensions { get; } - - /// - /// Gets the whose is a subset of . - /// - /// Length.Info.GetUnitInfoFor(unitSystemWithFootAsLengthUnit) returns for . - /// The to check against. - /// The that has that is a subset of . - /// is null. - /// No unit was found that is a subset of . - /// More than one unit was found that is a subset of . - public UnitInfo GetUnitInfoFor(BaseUnits baseUnits) - { - if (baseUnits is null) - throw new ArgumentNullException(nameof(baseUnits)); + /// + public abstract Type UnitType { get; } - var matchingUnitInfos = GetUnitInfosFor(baseUnits) - .Take(2) - .ToArray(); + /// + public BaseDimensions BaseDimensions { get; } - var firstUnitInfo = matchingUnitInfos.FirstOrDefault(); - if (firstUnitInfo == null) - throw new InvalidOperationException($"No unit was found that is a subset of {nameof(baseUnits)}"); + /// + public ResourceManager? UnitAbbreviations { get; } - if (matchingUnitInfos.Length > 1) - throw new InvalidOperationException($"More than one unit was found that is a subset of {nameof(baseUnits)}"); + /// + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + public IQuantity Zero + { + get => GetGenericZero(); + } - return firstUnitInfo; - } + /// + protected internal abstract IQuantity GetGenericZero(); - /// - /// Gets an of that have that is a subset of . - /// - /// The to check against. - /// An of that have that is a subset of . - /// is null. - public IEnumerable GetUnitInfosFor(BaseUnits baseUnits) - { - if (baseUnits is null) - throw new ArgumentNullException(nameof(baseUnits)); + /// + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + public UnitInfo BaseUnitInfo + { + get => GetGenericBaseUnitInfo(); + } + + /// + protected internal abstract UnitInfo GetGenericBaseUnitInfo(); - return UnitInfos.Where(unitInfo => unitInfo.BaseUnits.IsSubsetOf(baseUnits)); - } + /// + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + public IReadOnlyList UnitInfos + { + get => GetGenericUnitInfos(); } - /// - /// - /// This is a specialization of , for when the unit type is known. - /// Typically you obtain this by looking it up statically from or - /// , or dynamically via . - /// - /// The unit enum type, such as . - public class QuantityInfo : QuantityInfo - where TUnit : struct, Enum + /// + protected internal abstract IReadOnlyList GetGenericUnitInfos(); + + /// + public abstract UnitInfo this[UnitKey unit] { get; } + + // /// + // public abstract bool TryGetUnitInfo(UnitKey unit, [NotNullWhen(true)] out UnitInfo? unitInfo); + + /// + public UnitInfo GetUnitInfoFor(BaseUnits baseUnits) { - /// - public QuantityInfo(string name, UnitInfo[] unitInfos, TUnit baseUnit, IQuantity zero, BaseDimensions baseDimensions) - : base(name, typeof(TUnit), unitInfos.ToArray(), baseUnit, zero, baseDimensions) - { - Zero = zero; - UnitInfos = unitInfos ?? throw new ArgumentNullException(nameof(unitInfos)); - BaseUnitInfo = UnitInfos.First(unitInfo => unitInfo.Value.Equals(baseUnit)); - UnitType = baseUnit; - } + return UnitInfos.GetUnitInfoFor(baseUnits); + } + + /// + public IEnumerable GetUnitInfosFor(BaseUnits baseUnits) + { + return UnitInfos.GetUnitInfosFor(baseUnits); + } + + /// + /// Creates an instance of from the specified value and unit. + /// + /// The numerical value of the quantity. + /// The unit of the quantity, represented as an enumeration. + /// 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(QuantityValue value, UnitKey unitKey); + + /// + public override string ToString() + { + return Name; + } +} + +/// +/// +/// This is a specialization of , for when the unit type is known. +/// Typically, you obtain this by looking it up statically from or +/// , or dynamically via . +/// +/// The unit enum type, such as . +public abstract class QuantityInfo : QuantityInfo//, IQuantityInfo + where TUnit : struct, Enum +{ + /// + protected QuantityInfo(string name, Type quantityType, BaseDimensions baseDimensions, ResourceManager? unitAbbreviations = null) + : base(name, quantityType, baseDimensions, unitAbbreviations) + { + } + + #region Implementation of IQuantityInfo + + /// + public new UnitInfo BaseUnitInfo + { + get => GetBaseUnitInfo(); + } + + /// + protected internal abstract UnitInfo GetBaseUnitInfo(); + + /// + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + public new IQuantity Zero + { + get => GetZero(); + } + + /// + protected internal abstract IQuantity GetZero(); + + /// + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + public new IReadOnlyList> UnitInfos + { + get => GetUnitInfos(); + } + + /// + protected internal abstract IReadOnlyList> GetUnitInfos(); + + /// + public UnitInfo this[TUnit unit] + { + get => GetUnitInfo(unit); + } + + /// + /// Retrieves the unit information for the specified unit. + /// + /// The unit for which to retrieve information. + /// An instance containing information about the specified unit. + /// Thrown if the specified unit is not valid for this quantity. + protected internal abstract UnitInfo GetUnitInfo(TUnit unit); + + // /// + // public abstract bool TryGetUnitInfo(TUnit unit, [NotNullWhen(true)] out UnitInfo? unitInfo); + + /// + public new UnitInfo GetUnitInfoFor(BaseUnits baseUnits) + { + return UnitInfos.GetUnitInfoFor(baseUnits); + } + + /// + public new IEnumerable> GetUnitInfosFor(BaseUnits baseUnits) + { + return UnitInfos.GetUnitInfosFor(baseUnits); + } + + /// + public IQuantity From(QuantityValue value, TUnit unit) + { + return CreateGenericQuantity(value, unit); + } + + /// + protected internal abstract IQuantity CreateGenericQuantity(QuantityValue value, TUnit unit); + + #endregion + + #region Overrides of QuantityInfo + + /// + public override Type UnitType + { + get => typeof(TUnit); + } + + /// + protected internal override IQuantity GetGenericZero() + { + return Zero; + } + + /// + protected internal override UnitInfo GetGenericBaseUnitInfo() + { + return BaseUnitInfo; + } + + /// + protected internal override IReadOnlyList GetGenericUnitInfos() + { + return UnitInfos; + } + + /// + public override UnitInfo this[UnitKey unit] + { + get => this[unit.ToUnit()]; + } + + // /// + // public override bool TryGetUnitInfo(UnitKey unit, [NotNullWhen(true)] out UnitInfo? unitInfo) + // { + // if (unit.UnitType == typeof(TUnit) && TryGetUnitInfo(unit.ToUnit(), out UnitInfo? unitMapping)) + // { + // unitInfo = unitMapping; + // return true; + // } + // + // unitInfo = null; + // return false; + // } + + /// + internal override IQuantity From(QuantityValue value, UnitKey unitKey) + { + return From(value, unitKey.ToUnit()); + } + + #endregion +} + +/// +public abstract class QuantityInfoBase : QuantityInfo, IQuantityInstanceInfo + where TQuantity : IQuantity + where TUnit : struct, Enum + where TUnitInfo : UnitInfo +{ + /// + /// Initializes a new instance of the class. + /// + /// The name of the quantity. + /// The zero value of the quantity. + /// The base dimensions of the quantity. + /// The delegate for creating a quantity from a value and unit. + /// + /// When provided, the resource manager used for localizing the quantity's unit abbreviations. + /// + protected QuantityInfoBase(string name, TQuantity zero, BaseDimensions baseDimensions, QuantityFromDelegate fromDelegate, + ResourceManager? unitAbbreviations) + : base(name, zero.GetType(), baseDimensions, unitAbbreviations) + { + Zero = zero; + FromDelegate = fromDelegate; + } + + private QuantityFromDelegate FromDelegate { get; } + + + #region Implementation of IQuantityInfo - /// - public new UnitInfo[] UnitInfos { get; } + /// + public new TQuantity Zero { get; } - /// - public new UnitInfo BaseUnitInfo { get; } + /// + public new abstract IReadOnlyList UnitInfos { get; } - /// - public new IQuantity Zero { get; } + /// + public new abstract TUnitInfo BaseUnitInfo { get; } - /// - public new TUnit UnitType { get; } + /// + public new abstract TUnitInfo this[TUnit unit] { get; } - /// - public new UnitInfo GetUnitInfoFor(BaseUnits baseUnits) + /// + public abstract bool TryGetUnitInfo(TUnit unit, [NotNullWhen(true)] out TUnitInfo? unitInfo); + + /// + public new IEnumerable GetUnitInfosFor(BaseUnits baseUnits) + { + return UnitInfos.GetUnitInfosFor(baseUnits); + } + + /// + public new TUnitInfo GetUnitInfoFor(BaseUnits baseUnits) + { + return UnitInfos.GetUnitInfoFor(baseUnits); + } + + /// + /// Creates an instance of the quantity from the specified value and unit. + /// + /// The numerical value of the quantity. + /// The unit of the quantity. + /// An instance of representing the specified value and unit. + public new TQuantity From(QuantityValue value, TUnit unit) + { + return FromDelegate(value, unit); + } + + // /// + // public new TQuantity From(QuantityValue value, Enum unit) + // { + // if (unit is not TUnit typedUnit) + // { + // throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TUnit)} is supported.", nameof(unit)); + // } + // + // return From(value, typedUnit); + // } + + /// + TQuantity IQuantityInstanceInfo.Create(QuantityValue value, UnitKey unitKey) + { + return From(value, unitKey.ToUnit()); + } + + #endregion + + #region Overrides of QuantityInfo + + /// + protected internal override IQuantity GetZero() + { + return Zero; + } + + /// + protected internal override UnitInfo GetBaseUnitInfo() + { + return BaseUnitInfo; + } + + /// + protected internal override IReadOnlyList> GetUnitInfos() + { + return UnitInfos; + } + + /// + protected internal override UnitInfo GetUnitInfo(TUnit unit) + { + return this[unit]; + } + + // /// + // public override bool TryGetUnitInfo(TUnit unit, [NotNullWhen(true)] out UnitInfo? unitInfo) + // { + // if (TryGetUnitInfo(unit, out TUnitInfo? unitMapping)) + // { + // unitInfo = unitMapping; + // return true; + // } + // + // unitInfo = null; + // return false; + // } + + /// + protected internal override IQuantity CreateGenericQuantity(QuantityValue value, TUnit unit) + { + return From(value, unit); + } + + #endregion +} + +/// +public class QuantityInfo : QuantityInfoBase>//, IQuantityInfo + where TQuantity : IQuantity + where TUnit : struct, Enum +{ + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private readonly Dictionary> _unitMappings; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private readonly UnitInfo[] _unitInfos; + + #if NET + + /// + /// Initializes a new instance of the class using the default quantity name. + /// + /// A collection of unit mapping configurations. + /// The base unit of the quantity. + /// The base dimensions of the quantity. + /// + /// When provided, the resource manager used for localizing the quantity's unit abbreviations. + /// + /// Thrown when is null. + /// + /// Thrown when no unit mapping configuration is found for the specified . + /// + public QuantityInfo(TUnit baseUnit, IEnumerable> unitMappings, BaseDimensions baseDimensions, ResourceManager? unitAbbreviations = null) + : this(typeof(TQuantity).Name, baseUnit, unitMappings, baseDimensions, TQuantity.From, unitAbbreviations) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The name of the quantity. + /// A collection of unit mapping configurations. + /// The base unit of the quantity. + /// The base dimensions of the quantity. + /// + /// When provided, the resource manager used for localizing the quantity's unit abbreviations. + /// + /// Thrown when is null. + /// + /// Thrown when no unit mapping configuration is found for the specified . + /// + public QuantityInfo(string name, TUnit baseUnit, IEnumerable> unitMappings, BaseDimensions baseDimensions, ResourceManager? unitAbbreviations = null) + : 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. + /// + /// A collection of unit mapping configurations. + /// The base unit of the quantity. + /// The base dimensions of the quantity. + /// A delegate to create a quantity from a value and unit. + /// + /// When provided, the resource manager used for localizing the quantity's unit abbreviations. + /// + /// Thrown when is null. + /// + /// Thrown when no unit mapping configuration is found for the specified . + /// + public QuantityInfo(TUnit baseUnit, IEnumerable> unitMappings, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations = null) + : this(typeof(TQuantity).Name, baseUnit, unitMappings, baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The name of the quantity. + /// A collection of unit mapping configurations. + /// The base unit of the quantity. + /// The base dimensions of the quantity. + /// A delegate to create a quantity from a value and unit. + /// + /// When provided, the resource manager used for localizing the quantity's unit abbreviations. + /// + /// Thrown when is null. + /// + /// Thrown when no unit mapping configuration is found for the specified . + /// + public QuantityInfo(string name, TUnit baseUnit, IEnumerable> unitMappings, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations = null) + : this(name, baseUnit, unitMappings, fromDelegate(QuantityValue.Zero, baseUnit), baseDimensions, fromDelegate, unitAbbreviations) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The name of the quantity. + /// The base unit of the quantity. + /// A collection of unit mapping configurations. + /// The zero value of the quantity. + /// The base dimensions of the quantity. + /// A delegate to create a quantity from a value and unit. + /// + /// When provided, the resource manager used for localizing the quantity's unit abbreviations. + /// + /// Thrown when is null. + /// + /// Thrown when no unit mapping configuration is found for the specified . + /// + public QuantityInfo(string name, TUnit baseUnit, IEnumerable> unitMappings, TQuantity zero, BaseDimensions baseDimensions, + QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations = null) + : base(name, zero, baseDimensions, fromDelegate, unitAbbreviations) + { + if (unitMappings == null) { - return (UnitInfo)base.GetUnitInfoFor(baseUnits); + throw new ArgumentNullException(nameof(unitMappings)); } - - /// - public new IEnumerable> GetUnitInfosFor(BaseUnits baseUnits) +#if NET + _unitInfos = unitMappings.Select(unit => new UnitInfo(this, unit)).ToArray(); + _unitMappings = _unitInfos.ToDictionary(info => info.Value); +#else + _unitMappings = unitMappings.ToDictionary(unit => unit.Value, unit => new UnitInfo(this, unit), UnitEqualityComparer.Default); + _unitInfos = _unitMappings.Values.ToArray(); +#endif + if (!_unitMappings.TryGetValue(baseUnit, out UnitInfo? baseUnitInfo)) { - return base.GetUnitInfosFor(baseUnits).Cast>(); + throw new UnitNotFoundException($"No unit mapping configuration found for the specified base unit: {baseUnit}"); } + + BaseUnitInfo = baseUnitInfo; + } + + /// + /// Gets a read-only collection of the units associated with this quantity. + /// + /// + /// A collection of units of type . + /// + public IReadOnlyCollection Units + { + get => _unitMappings.Keys; + } + + #region Overrides of QuantityInfoBase> + + /// + [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] + public override UnitInfo BaseUnitInfo { get; } + + /// + public override UnitInfo this[TUnit unit] + { + get => _unitMappings[unit]; } + + /// + public override bool TryGetUnitInfo(TUnit unit, [NotNullWhen(true)] out UnitInfo? unitInfo) + { + return _unitMappings.TryGetValue(unit, out unitInfo); + } + + /// + [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] + public sealed override IReadOnlyList> UnitInfos + { + get => _unitInfos; + } + + #endregion + + #region Explicit implementation of IQuantityInfo + + // [DebuggerBrowsable(DebuggerBrowsableState.Never)] + // IReadOnlyCollection> IQuantityInfo.UnitInfos + // { + // get => UnitInfos; + // } + + // [DebuggerBrowsable(DebuggerBrowsableState.Never)] + // UnitInfo IQuantityInfo.BaseUnitInfo + // { + // get => BaseUnitInfo; + // } + + // IUnitInfo IQuantityInfo.this[TUnit unit] + // { + // get => this[unit]; + // } + + // bool IQuantityInfo.TryGetUnitInfo(TUnit unit, [NotNullWhen(true)] out IUnitInfo? unitInfo) + // { + // if (TryGetUnitInfo(unit, out UnitInfo? info)) + // { + // unitInfo = info; + // return true; + // } + // + // unitInfo = null; + // return false; + // } + + // IUnitInfo IQuantityInfo.GetUnitInfoFor(BaseUnits baseUnits) + // { + // return GetUnitInfoFor(baseUnits); + // } + + // IEnumerable> IQuantityInfo.GetUnitInfosFor(BaseUnits baseUnits) + // { + // return GetUnitInfosFor(baseUnits); + // } + + // IQuantity IQuantityInfo.From(QuantityValue value, TUnit unit) + // { + // return From(value, unit); + // } + + // [DebuggerBrowsable(DebuggerBrowsableState.Never)] + // IQuantity IQuantityInfo.Zero + // { + // get => Zero; + // } + + + // /// + // TQuantity IQuantityInstanceInfo.Create(QuantityValue value, UnitKey unitKey) + // { + // return From(value, unitKey.ToUnit()); + // } + + #endregion + + #region Implementation of IQuantityInfo + + // [DebuggerBrowsable(DebuggerBrowsableState.Never)] + // IReadOnlyCollection> IQuantityInfo.UnitInfos + // { + // get => UnitInfos; + // } + + // [DebuggerBrowsable(DebuggerBrowsableState.Never)] + // IUnitInfo IQuantityInfo.BaseUnitInfo + // { + // get => BaseUnitInfo; + // } + + // UnitInfo IQuantityInfo.this[TUnit unit] + // { + // get => this[unit]; + // } + + // UnitInfo IQuantityInfo.GetUnitInfoFor(BaseUnits baseUnits) + // { + // return GetUnitInfoFor(baseUnits); + // } + + // IEnumerable> IQuantityInfo.GetUnitInfosFor(BaseUnits baseUnits) + // { + // return GetUnitInfosFor(baseUnits); + // } + + #endregion } diff --git a/UnitsNet/QuantityInfoLookup.cs b/UnitsNet/QuantityInfoLookup.cs index 2c3dc302ad..df19596b97 100644 --- a/UnitsNet/QuantityInfoLookup.cs +++ b/UnitsNet/QuantityInfoLookup.cs @@ -6,11 +6,12 @@ using System.Collections.Frozen; using QuantityByTypeLookupDictionary = System.Collections.Frozen.FrozenDictionary; using QuantityByNameLookupDictionary = System.Collections.Frozen.FrozenDictionary; +using UnitByKeyLookupDictionary = System.Collections.Frozen.FrozenDictionary; #else using QuantityByTypeLookupDictionary = System.Collections.Generic.Dictionary; using QuantityByNameLookupDictionary = System.Collections.Generic.Dictionary; -#endif using UnitByKeyLookupDictionary = System.Collections.Generic.Dictionary; +#endif namespace UnitsNet; @@ -20,10 +21,11 @@ namespace UnitsNet; /// /// Access type is internal until this class is matured and ready for external use. /// -internal class QuantityInfoLookup +public class QuantityInfoLookup { private readonly QuantityInfo[] _quantities; private readonly Lazy _quantitiesByName; + private readonly Lazy _quantitiesByType; private readonly Lazy _quantitiesByUnitType; private readonly Lazy _unitsByKey; @@ -36,6 +38,15 @@ private QuantityByNameLookupDictionary GroupQuantitiesByName() #endif } + private QuantityByTypeLookupDictionary GroupQuantitiesByType() + { +#if NET8_0_OR_GREATER + return _quantities.ToFrozenDictionary(info => info.QuantityType); +#else + return _quantities.ToDictionary(info => info.QuantityType); +#endif + } + private QuantityByTypeLookupDictionary GroupQuantitiesByUnitType() { #if NET8_0_OR_GREATER @@ -47,7 +58,11 @@ private QuantityByTypeLookupDictionary GroupQuantitiesByUnitType() private UnitByKeyLookupDictionary GroupUnitsByKey() { +#if NET8_0_OR_GREATER + return _quantities.SelectMany(quantityInfo => quantityInfo.UnitInfos).ToFrozenDictionary(x => x.UnitKey); +#else return _quantities.SelectMany(quantityInfo => quantityInfo.UnitInfos).ToDictionary(x => x.UnitKey); +#endif } /// @@ -67,12 +82,13 @@ public QuantityInfoLookup(IEnumerable quantityInfos) { _quantities = quantityInfos.ToArray(); _quantitiesByName = new Lazy(GroupQuantitiesByName); + _quantitiesByType = new Lazy(GroupQuantitiesByType); _quantitiesByUnitType = new Lazy(GroupQuantitiesByUnitType); _unitsByKey = new Lazy(GroupUnitsByKey); } /// - /// All enum value names of , such as "Length" and "Mass". + /// All quantity names, such as "Length" and "Mass". /// public IReadOnlyCollection Names => _quantitiesByName.Value.Keys; @@ -86,6 +102,52 @@ 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. + /// + /// The type of the quantity to retrieve information for. + /// The for the specified quantity type. + /// + /// Thrown when the is not of type . + /// + /// + /// Thrown when the specified quantity type is not registered in the current configuration. + /// + public QuantityInfo GetQuantityInfo(Type quantityType) + { + if (TryGetQuantityInfo(quantityType, out QuantityInfo? quantityInfo)) + { + return quantityInfo; + } + + if (!typeof(IQuantity).IsAssignableFrom(quantityType)) + { + throw new ArgumentException($"Type {quantityType} must be of type UnitsNet.IQuantity."); + } + + throw new QuantityNotFoundException($"The specified quantity type is not registered in the current configuration: '{quantityType}'."); + } + + /// + /// Try to get the for a given quantity type. + /// + public bool TryGetQuantityInfo(Type quantityType, [NotNullWhen(true)] out QuantityInfo? quantityInfo) + { + return _quantitiesByType.Value.TryGetValue(quantityType, out quantityInfo); + } + /// /// Retrieves the for a specified . /// @@ -99,6 +161,7 @@ public UnitInfo GetUnitInfo(UnitKey unitKey) { if (!TryGetUnitInfo(unitKey, out UnitInfo? unitInfo)) { + // throw new UnitNotFoundException($"Unit not found in the list of {_unitsByKey.Value.Count} units: unitKey.UnitType.GetHashCode = {unitKey.UnitType.GetHashCode()}, unitKey.Value={unitKey.UnitValue}, unitKey.UnitType.FullName = {unitKey.UnitType.FullName}"); throw new UnitNotFoundException($"No unit information found for the specified enum value: {unitKey}."); } @@ -112,16 +175,7 @@ public bool TryGetUnitInfo(UnitKey unitKey, [NotNullWhen(true)] out UnitInfo? un { return _unitsByKey.Value.TryGetValue(unitKey, out unitInfo); } - - /// - /// - /// - /// - public void AddUnitInfo(UnitInfo unitInfo) - { - _unitsByKey.Value.Add(unitInfo.UnitKey, unitInfo); - } - + /// /// Dynamically construct a quantity. /// @@ -129,12 +183,9 @@ public void AddUnitInfo(UnitInfo unitInfo) /// 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) { - // TODO Support custom units, currently only hardcoded built-in quantities are supported. - return Quantity.TryFrom(value, (Enum)unit, out IQuantity? quantity) - ? quantity - : throw new UnitNotFoundException($"Unit value {unit} of type {unit.GetType()} is not a known unit enum type. Expected types like UnitsNet.Units.LengthUnit. Did you pass in a custom enum type defined outside the UnitsNet library?"); + return GetUnitInfo(unit).From(value); } /// @@ -149,10 +200,22 @@ 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) { - // TODO Support custom units, currently only hardcoded built-in quantities are supported. - return Quantity.TryFrom(value, unit, out quantity); + if (unit == null) + { + quantity = null; + return false; + } + + if (!TryGetUnitInfo(unit, out UnitInfo? unitInfo)) + { + quantity = null; + return false; + } + + quantity = unitInfo.From(value); + return true; } /// @@ -163,7 +226,7 @@ public bool TryFrom(double value, [NotNullWhen(true)] Enum? unit, [NotNullWhen(t /// /// Thrown when no quantity information is found for the specified quantity name. /// - internal QuantityInfo GetQuantityByName(string quantityName) + public QuantityInfo GetQuantityByName(string quantityName) { if (!ByName.TryGetValue(quantityName, out QuantityInfo? quantityInfo)) { @@ -187,7 +250,7 @@ internal QuantityInfo GetQuantityByName(string quantityName) /// /// true if the quantity name was found; otherwise, false. /// - internal bool TryGetQuantityByName(string quantityName, [NotNullWhen(true)] out QuantityInfo? quantityInfo) + public bool TryGetQuantityByName(string quantityName, [NotNullWhen(true)] out QuantityInfo? quantityInfo) { return ByName.TryGetValue(quantityName, out quantityInfo); } @@ -210,7 +273,7 @@ internal bool TryGetQuantityByName(string quantityName, [NotNullWhen(true)] out /// /// Thrown when no unit is found for the specified quantity name and unit name. /// - internal UnitInfo GetUnitByName(string quantityName, string unitName) + public UnitInfo GetUnitByName(string quantityName, string unitName) { QuantityInfo quantityInfo = GetQuantityByName(quantityName); UnitInfo? unitInfo = quantityInfo.UnitInfos.FirstOrDefault(unit => string.Equals(unit.Name, unitName, StringComparison.OrdinalIgnoreCase)); @@ -231,7 +294,7 @@ internal UnitInfo GetUnitByName(string quantityName, string unitName) /// parsing failed. /// /// true if the unit information was successfully parsed; otherwise, false. - internal bool TryGetUnitByName(string quantityName, string unitName, [NotNullWhen(true)] out UnitInfo? unitInfo) + public bool TryGetUnitByName(string quantityName, string unitName, [NotNullWhen(true)] out UnitInfo? unitInfo) { if (!TryGetQuantityByName(quantityName, out QuantityInfo? quantityInfo)) { @@ -243,12 +306,32 @@ internal bool TryGetUnitByName(string quantityName, string unitName, [NotNullWhe return unitInfo is not null; } - + /// + /// Attempts to retrieve the associated with the specified unit type. + /// + /// The of the unit to look up. + /// + /// When this method returns, contains the associated with the specified unit type, + /// if the lookup was successful; otherwise, null. + /// + /// + /// true if a associated with the specified unit type was found; otherwise, + /// false. + /// public bool TryGetQuantityByUnitType(Type unitType, [NotNullWhen(true)] out QuantityInfo? quantityInfo) { return _quantitiesByUnitType.Value.TryGetValue(unitType, out quantityInfo); } + /// + /// Retrieves the associated with the specified unit type. + /// + /// The of the unit for which the quantity information is requested. + /// The corresponding to the specified unit type. + /// + /// Thrown when no quantity is found for the specified unit type. + /// The exception includes additional data with the key "unitType" containing the name of the unit type. + /// public QuantityInfo GetQuantityByUnitType(Type unitType) { if (TryGetQuantityByUnitType(unitType, out QuantityInfo? quantityInfo)) diff --git a/UnitsNet/QuantityTypeConverter.cs b/UnitsNet/QuantityTypeConverter.cs index 7722b87623..e93644a92e 100644 --- a/UnitsNet/QuantityTypeConverter.cs +++ b/UnitsNet/QuantityTypeConverter.cs @@ -3,6 +3,7 @@ using System; using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace UnitsNet @@ -58,7 +59,7 @@ public ConvertToUnitAttribute(object? unitType) : base(unitType) { } public class DisplayAsUnitAttribute : DefaultUnitAttribute { /// - /// The formatting used when the quantity is converted to string. See + /// The formatting used when the quantity is converted to string. See for more information about the supported formats. /// public string Format { get; set; } @@ -66,7 +67,7 @@ public class DisplayAsUnitAttribute : DefaultUnitAttribute /// Initializes a new instance of the class. /// /// The unit the quantity should be displayed in - /// Formatting string + /// Formatting string passed to the public DisplayAsUnitAttribute(object? unitType, string format = "G") : base(unitType) { Format = format; @@ -138,7 +139,11 @@ public override bool CanConvertFrom(ITypeDescriptorContext? context, Type source return (sourceType == typeof(string)) || base.CanConvertFrom(context, sourceType); } - private static TAttribute? GetAttribute(ITypeDescriptorContext? context) where TAttribute : UnitAttributeBase + private static TAttribute? GetAttribute< +#if NET + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicFields)] +#endif + TAttribute>(ITypeDescriptorContext? context) where TAttribute : UnitAttributeBase { if (context?.PropertyDescriptor is null) return null; @@ -147,11 +152,12 @@ public override bool CanConvertFrom(ITypeDescriptorContext? context, Type source // 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}]."); } } @@ -159,36 +165,48 @@ public override bool CanConvertFrom(ITypeDescriptorContext? context, Type source } /// - /// 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; } @@ -218,22 +236,22 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destina { DisplayAsUnitAttribute? displayAsUnit = GetAttribute(context); - if (value is not IQuantity qvalue || destinationType != typeof(string)) + if (value is not IQuantity quantity || destinationType != typeof(string)) { return base.ConvertTo(context, culture, value, destinationType); } if (displayAsUnit == null) { - return qvalue.ToString(culture); + return quantity.ToString(culture); } - if (displayAsUnit.UnitType == null) + if (displayAsUnit.UnitType is { } targetUnit) { - return qvalue.ToString(displayAsUnit.Format, culture); + quantity = UnitConverter.Default.ConvertTo(quantity, targetUnit); } - return qvalue.ToUnit(displayAsUnit.UnitType).ToString(displayAsUnit.Format, culture); + return quantity.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 0815506966..1e6eb2b96d 100644 --- a/UnitsNet/UnitConverter.cs +++ b/UnitsNet/UnitConverter.cs @@ -2,563 +2,1201 @@ // 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; -using System.Reflection; +using System.Globalization; +using System.Linq; using UnitsNet.InternalHelpers; -using UnitsNet.Units; -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.Provider.DefaultConversions)) + { + 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.Provider.DefaultConversions)); + + 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) { - var unitConverter = new UnitConverter(); - RegisterDefaultConversions(unitConverter); + 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)) + { + convertedQuantity = toUnitInfo.From(convertedValue); + return true; + } - return unitConverter; + convertedQuantity = null; + return false; + } + + /// + /// 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; + } + + /// + /// 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)) + { + return TryConvertValueInternal(value, fromUnitInfo, toUnitInfo, out convertedValue); + } + + convertedValue = default; + return false; + } - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - public static void RegisterDefaultConversions(UnitConverter 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) { - if (unitConverter is null) - throw new ArgumentNullException(nameof(unitConverter)); + return TryConvertValueFromOneQuantityToAnother(value, fromUnitInfo, toUnitInfo, out convertedValue); + } + + convertedValue = toUnitInfo.GetValueFrom(value, fromUnitInfo); + return true; + } - foreach(var quantity in Quantity.GetQuantityTypes()) + /// + /// 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()) { - var registerMethod = quantity.GetMethod(nameof(Length.RegisterDefaultConversions), BindingFlags.NonPublic | BindingFlags.Static); - registerMethod?.Invoke(null, new object[]{unitConverter}); + convertedValue = toUnit.ConvertValueFromBaseUnit(fromUnit.ConvertValueToBaseUnit(value)); + return true; } - } - /// - /// 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 - { - var quantityType = typeof(TQuantity); - var conversionLookup = new ConversionFunctionLookupKey(quantityType, from, quantityType, to); - SetConversionFunction(conversionLookup, conversionFunction); - } - - /// - /// 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 + conversionExpression = sourceValue => sourceValue; + } + else { - SetConversionFunction(typeof(TQuantityFrom), from, typeof(TQuantityTo), to, conversionFunction); + convertedValue = default; + return false; } - - /// - /// 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) + + if (fromUnit.BaseUnits != BaseUnits.Undefined) { - var conversionLookup = new ConversionFunctionLookupKey(fromType, from, toType, to); - SetConversionFunction(conversionLookup, conversionFunction); - } - - /// - /// Sets the conversion function for a particular conversion function lookup. - /// - /// The lookup key. - /// The quantity conversion function. - internal void SetConversionFunction(ConversionFunctionLookupKey lookupKey, ConversionFunction conversionFunction) - { - ConversionFunctions[lookupKey] = conversionFunction; + 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; + } + } } - - /// - /// 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 - { - IQuantity TypelessConversionFunction(IQuantity quantity) => conversionFunction((TQuantity) quantity); - - ConversionFunctions[conversionLookup] = TypelessConversionFunction; - } - - /// - /// 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 - { - return GetConversionFunction(typeof(TQuantity), from, typeof(TQuantity), to); - } - - /// - /// 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 + else if (toUnit.BaseUnits != BaseUnits.Undefined) + { + if (sourceQuantity.UnitInfos.TryGetUnitWithBase(toUnit.BaseUnits, out UnitInfo? matchingUnit)) { - // We're not going to implement TryAs() in all quantities, so let's just try-catch here - convertedValue = fromQuantity.As(toUnitValue); + convertedValue = conversionExpression(ConvertValueInternal(value, fromUnit, matchingUnit)); return true; } - catch + + UnitInfo toBaseUnit = targetQuantity.BaseUnitInfo; + if (toUnit.BaseUnits != toBaseUnit.BaseUnits && toBaseUnit.BaseUnits != BaseUnits.Undefined) { - return false; + if (sourceQuantity.BaseUnitInfo.BaseUnits == toBaseUnit.BaseUnits) + { + convertedValue = toUnit.ConversionFromBase.Evaluate(conversionExpression(fromUnit.ConvertValueToBaseUnit(value))); + return true; + } } } - /// - /// 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.QuantityInfoLookup; - 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.QuantityInfoLookup; - if (quantities.TryGetUnitByName(quantityName, fromUnit, out UnitInfo? fromUnitInfo) && - quantities.TryGetUnitByName(quantityName, toUnit, out UnitInfo? toUnitInfo) && - Quantity.TryFrom(inputValue, fromUnitInfo.Value, out IQuantity? quantity)) + foreach (UnitInfo sourceUnit in sourceQuantity.UnitInfos) + { + if (sourceUnit.BaseUnits == BaseUnits.Undefined || sourceUnit.BaseUnits == fromUnit.BaseUnits) { - result = quantity.As(toUnitInfo.Value); + continue; + } + + if (targetQuantity.UnitInfos.TryGetUnitWithBase(sourceUnit.BaseUnits, out UnitInfo? matchingUnit)) + { + convertedValue = ConvertValueInternal(conversionExpression(ConvertValueInternal(value, fromUnit, sourceUnit)), matchingUnit, toUnit); return true; } - - result = 0d; - 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 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.QuantityInfoLookup; - 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.QuantityInfoLookup; - UnitParser unitParser = UnitsNetSetup.Default.UnitParser; - if (!quantities.TryGetQuantityByName(quantityName, out QuantityInfo? quantityInfo) ) + 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)) + { + return targetQuantityInfo.TryConvertFrom(value, fromUnitInfo, out convertedQuantity); + } + + 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)) + { + return targetQuantityInfo.TryConvertFrom(value, fromUnitInfo, out convertedQuantity); + } + + 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); + } + + /// + /// 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 value; + } + + UnitInfo fromUnitInfo = GetUnitInfo(fromUnitKey); + UnitInfo toUnitInfo = GetUnitInfo(toUnitKey); + return toUnitInfo.GetValueFrom(value, fromUnitInfo); + } + + /// + /// 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()) + { + 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); + } + + if (targetQuantity.UnitInfos.TryGetUnitWithBase(fromUnitInfo.BaseUnits, out UnitInfo? matchingUnit)) + { + return ConvertValueInternal(conversionExpression(value), matchingUnit, toUnitInfo); + } + + UnitInfo fromBaseUnit = sourceQuantity.BaseUnitInfo; + if (fromUnitInfo.BaseUnits != fromBaseUnit.BaseUnits && fromBaseUnit.BaseUnits != BaseUnits.Undefined) + { + 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)) { - result = 0; - return false; + return conversionExpression(ConvertValueInternal(value, fromUnitInfo, matchingUnit)); } - if (!unitParser.TryParse(fromUnitAbbrev, quantityInfo.UnitType, formatProvider, out Enum? fromUnit) || - !unitParser.TryParse(toUnitAbbrev, quantityInfo.UnitType, formatProvider, out Enum? toUnit)) + UnitInfo toBaseUnit = targetQuantity.BaseUnitInfo; + if (toUnitInfo.BaseUnits != toBaseUnit.BaseUnits && toBaseUnit.BaseUnits != BaseUnits.Undefined) { - result = 0; - return false; + if (sourceQuantity.BaseUnitInfo.BaseUnits == toBaseUnit.BaseUnits) + { + return toUnitInfo.ConversionFromBase.Evaluate(conversionExpression(fromUnitInfo.ConvertValueToBaseUnit(value))); + } } + } + + 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) + { + continue; + } + + if (targetQuantity.UnitInfos.TryGetUnitWithBase(sourceUnit.BaseUnits, out UnitInfo? matchingUnit)) + { + return ConvertValueInternal(conversionExpression(ConvertValueInternal(value, fromUnitInfo, sourceUnit)), matchingUnit, toUnitInfo); + } + } + + throw InvalidConversionException.CreateIncompatibleUnitsException(fromUnitInfo, targetQuantity); + } - result = Quantity.From(fromValue, fromUnit).As(toUnit); + /// + /// 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); + } + + /// + /// 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 df359557e6..0000000000 --- a/UnitsNet/UnitFormatter.cs +++ /dev/null @@ -1,80 +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 type of units to format. - /// The units - /// The unit value to format. - /// The current culture. - /// The list of format arguments. - /// An array of ToString format arguments. - public static object[] GetFormatArgs(TUnitType unit, double value, IFormatProvider? culture, IEnumerable args) - where TUnitType : struct, Enum - { - string abbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit, culture); - return new object[] {value, abbreviation}.Concat(args).ToArray(); - } - } -} diff --git a/UnitsNet/UnitInfo.cs b/UnitsNet/UnitInfo.cs index 7a7adc6819..c695c5eb05 100644 --- a/UnitsNet/UnitInfo.cs +++ b/UnitsNet/UnitInfo.cs @@ -5,118 +5,361 @@ using System.Diagnostics; using UnitsNet.Units; -namespace UnitsNet +namespace UnitsNet; + +/// +/// Information about the unit, such as its name and value. +/// This is useful to enumerate units and present names with quantities and units +/// chosen dynamically at runtime, such as unit conversion apps or allowing the user to change the +/// unit representation. +/// +/// +/// Typically you obtain this by looking it up via . +/// +public abstract class UnitInfo : IUnitDefinition//, IUnitInfo { + // /// + // /// Initializes a new instance of the class with the specified unit details. + // /// + // /// The singular name of the unit. Cannot be null. + // /// The plural name of the unit. Cannot be null. + // /// The base units associated with this unit. Cannot be null. + // /// + // /// The conversion expression to convert a value from the base unit to this unit. + // /// + // /// + // /// The conversion expression to convert a value from this unit to the base unit. + // /// + // /// + // /// Thrown when , , or is + // /// null. + // /// + // protected UnitInfo(string name, string pluralName, BaseUnits baseUnits, ConversionExpression conversionFromBase, ConversionExpression conversionToBase) + // { + // Name = name ?? throw new ArgumentNullException(nameof(name)); + // PluralName = pluralName ?? throw new ArgumentNullException(nameof(pluralName)); + // BaseUnits = baseUnits ?? throw new ArgumentNullException(nameof(baseUnits)); + // ConversionFromBase = conversionFromBase; + // ConversionToBase = conversionToBase; + // } + /// - /// Information about the unit, such as its name and value. - /// This is useful to enumerate units and present names with quantities and units - /// chosen dynamically at runtime, such as unit conversion apps or allowing the user to change the - /// unit representation. + /// Initializes a new instance of the class using the specified unit definition. /// - /// - /// Typically you obtain this by looking it up via . - /// - public class UnitInfo + /// + /// The unit definition containing details such as name, plural name, base units, and conversion + /// expressions. + /// + /// Thrown when the is null. + protected internal UnitInfo(IUnitDefinition mapping) { - /// - /// Creates an instance of the UnitInfo class. - /// - /// The enum value for this class, for example . - /// The plural name of the unit, such as "Centimeters". - /// The for this unit. - [Obsolete("Use the constructor that also takes a quantityName parameter.")] - public UnitInfo(Enum value, string pluralName, BaseUnits baseUnits) + if (mapping == null) { - Value = value ?? throw new ArgumentNullException(nameof(value)); - Name = value.ToString(); - PluralName = pluralName ?? throw new ArgumentNullException(nameof(pluralName)); - BaseUnits = baseUnits ?? throw new ArgumentNullException(nameof(baseUnits)); + throw new ArgumentNullException(nameof(mapping)); } - /// - /// Creates an instance of the UnitInfo class. - /// - /// The enum value for this class, for example . - /// The plural name of the unit, such as "Centimeters". - /// The for this unit. - /// The quantity name that this unit is for. - public UnitInfo(Enum value, string pluralName, BaseUnits baseUnits, string quantityName) - { - Value = value ?? throw new ArgumentNullException(nameof(value)); - Name = value.ToString(); - PluralName = pluralName ?? throw new ArgumentNullException(nameof(pluralName)); - BaseUnits = baseUnits ?? throw new ArgumentNullException(nameof(baseUnits)); - QuantityName = quantityName ?? throw new ArgumentNullException(nameof(quantityName)); - } + Name = mapping.Name; + PluralName = mapping.PluralName; + BaseUnits = mapping.BaseUnits; + ConversionFromBase = mapping.ConversionFromBase; + ConversionToBase = mapping.ConversionToBase; + } + + /// + public override string ToString() + { + return Name; + } + + #region Implementation of IUnitDefinition + + /// + public string Name { get; } + + /// + public string PluralName { get; } + + /// + public BaseUnits BaseUnits { get; } - /// - /// The enum value of the unit, such as . - /// - public Enum Value { get; } - - /// - /// The singular name of the unit, such as "Centimeter". - /// - public string Name { get; } - - /// - /// The plural name of the unit, such as "Centimeters". - /// - public string PluralName { get; } - - /// - /// Gets the for this unit. - /// - public BaseUnits BaseUnits { get; } - - /// - /// Name of the quantity this unit belongs to. May be null for custom units. - /// - public string? QuantityName { get; } - - /// - /// Gets the unique key representing the unit type and its corresponding value. - /// - /// - /// This key is particularly useful when using an enum-based unit in a hash-based collection, - /// as it avoids the boxing that would normally occur when casting the enum to . - /// - public virtual UnitKey UnitKey => Value; + /// + public ConversionExpression ConversionFromBase { get; } + + /// + public ConversionExpression ConversionToBase { get; } + + #endregion + + #region Implementation of IUnitInfo + + /// + /// The enum value of the unit, such as . + /// + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + public Enum Value + { + get => GetUnitValue(); } - /// + /// + protected abstract Enum GetUnitValue(); + + /// + /// Get the parent quantity information. + /// /// - /// This is a specialization of , for when the unit type is known. - /// Typically you obtain this by looking it up statically from or - /// or dynamically via . + /// This property provides detailed information about the quantity to which this unit belongs, + /// including its name, unit values, and zero quantity. It is useful for enumerating units and + /// presenting names with quantities and units chosen dynamically at runtime. /// - /// The unit enum type, such as . - [DebuggerDisplay("{Name} ({Value})")] - public class UnitInfo : UnitInfo - where TUnit : struct, Enum + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + public QuantityInfo QuantityInfo { - /// - [Obsolete("Use the constructor that also takes a quantityName parameter.")] - public UnitInfo(TUnit value, string pluralName, BaseUnits baseUnits) : - base(value, pluralName, baseUnits) - { - Value = value; - } + get => GetGenericInfo(); + } + + /// + protected internal abstract QuantityInfo GetGenericInfo(); + + /// + /// Gets the unique key representing the unit type and its corresponding value. + /// + /// + /// This key is particularly useful when using an enum-based unit in a hash-based collection, + /// as it avoids the boxing that would normally occur when casting the enum to . + /// + public abstract UnitKey UnitKey { get; } + + /// + /// Name of the quantity this unit belongs to. + /// + [Obsolete("Please use the QuantityInfo.Name instead.")] + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + public string QuantityName + { + get => QuantityInfo.Name; + } + + /// + /// Creates an instance of from the specified . + /// + /// The quantity value to convert. + /// An instance of representing the specified . + /// + /// This method utilizes the associated with this unit to create the quantity. + /// + public IQuantity From(QuantityValue value) + { + return CreateGenericQuantity(value); + } - /// - public UnitInfo(TUnit value, string pluralName, BaseUnits baseUnits, string quantityName) : - base(value, pluralName, baseUnits, quantityName) - { - Value = value; - } + /// + protected internal abstract IQuantity CreateGenericQuantity(QuantityValue value); - /// - public new TUnit Value { get; } - - /// - public override UnitKey UnitKey - { - get => UnitKey.ForUnit(Value); - } + #endregion +} + +/// /> +/// +/// Typically you obtain this by looking it up via . +/// +public abstract class UnitInfo : UnitInfo, IUnitDefinition //, IUnitInfo, IUnitDefinition + where TUnit : struct, Enum +{ + // /// + // /// Initializes a new instance of the class. + // /// + // /// The unit enumeration value represented by this instance. + // /// The singular name of the unit. + // /// The plural name of the unit. + // /// The base units associated with this unit. + // /// + // /// The conversion expression to convert a value from the base unit to this unit. + // /// + // /// + // /// The conversion expression to convert a value from this unit to the base unit. + // /// + // protected UnitInfo(TUnit unit, string name, string pluralName, BaseUnits baseUnits, ConversionExpression conversionFromBase, ConversionExpression conversionToBase) + // : base(name, pluralName, baseUnits, conversionFromBase, conversionToBase) + // { + // Value = unit; + // } + + /// + /// Initializes a new instance of the class using the specified unit definition. + /// + /// + /// The unit definition containing details such as the unit value, name, plural name, base units, and conversion + /// expressions. + /// + /// Thrown when the is null. + protected UnitInfo(IUnitDefinition mapping) + : base(mapping) + { + Value = mapping.Value; + } + + + #region Implementation of IUnitInfo + + /// + [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] + public new TUnit Value { get; } + + // /// + // [DebuggerBrowsable(DebuggerBrowsableState.Never)] + // public new QuantityInfo QuantityInfo + // { + // get => GetQuantityInfo(); + // } + // + // /// + // protected internal abstract QuantityInfo GetQuantityInfo(); + + // /// + // public new IQuantity From(QuantityValue value) + // { + // return QuantityInfo.From(value, Value); + // } + + #endregion +} + +/// +/// Represents information about a specific unit of measurement for a given quantity type. +/// +/// The type of the quantity information associated with this unit. +/// The type of the quantity associated with this unit. +/// The enumeration type representing the unit. +[DebuggerDisplay("{Name} ({Value})")] +public abstract class UnitInfoBase : UnitInfo + where TQuantityInfo : QuantityInfo + where TQuantity : IQuantity + where TUnit : struct, Enum +{ + // /// + // /// Initializes a new instance of the class. + // /// + // /// The quantity information associated with this unit. + // /// The unit of measurement. + // /// The singular name of the unit. + // /// The plural name of the unit. + // /// The base units associated with this unit. + // /// The conversion expression from the base unit to this unit. + // /// The conversion expression from this unit to the base unit. + // protected UnitInfoBase(TQuantityInfo quantityInfo, TUnit unit, string singularName, string pluralName, BaseUnits baseUnits, + // ConversionExpression conversionFromBase, + // ConversionExpression conversionToBase) + // : base(unit, singularName, pluralName, baseUnits, conversionFromBase, conversionToBase) + // { + // QuantityInfo = quantityInfo; + // } + + // /// + // /// Initializes a new instance of the class. + // /// + // /// The quantity information associated with this unit. + // /// + // /// The plural name of the unit. + // /// The base units associated with this unit. + // /// The conversion expression from the base unit to this unit. + // /// The conversion expression from this unit to the base unit. + // protected UnitInfoBase(TQuantityInfo quantityInfo, TUnit unit, string pluralName, BaseUnits baseUnits, + // ConversionExpression conversionFromBase, + // ConversionExpression conversionToBase) + // : this(quantityInfo, unit, unit.ToString(), pluralName, baseUnits, conversionFromBase, conversionToBase) + // { + // } + + /// + /// Initializes a new instance of the class + /// using the specified quantity information and unit mapping configuration. + /// + /// The quantity information associated with this unit. + /// The unit mapping configuration containing unit details. + /// Thrown when the is null. + protected UnitInfoBase(TQuantityInfo quantityInfo, IUnitDefinition mapping) + : base(mapping) + { + QuantityInfo = quantityInfo; + } + + /// + [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] + public new TQuantityInfo QuantityInfo { get; } + + /// + public override UnitKey UnitKey + { + get => UnitKey.ForUnit(Value); + } + + /// + /// 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(QuantityValue value); + + #region Overrides of UnitInfo + + // /// + // protected internal sealed override QuantityInfo GetQuantityInfo() + // { + // return QuantityInfo; + // } + + /// + protected internal sealed override IQuantity CreateGenericQuantity(QuantityValue value) + { + return From(value); + } + + /// + protected internal sealed override QuantityInfo GetGenericInfo() + { + return QuantityInfo; + } + + /// + protected override Enum GetUnitValue() + { + return Value; + } + + #endregion +} + +/// +public sealed class UnitInfo : UnitInfoBase, TQuantity, TUnit> //, IUnitInfo + where TQuantity : IQuantity + where TUnit : struct, Enum +{ + // /// + // public UnitInfo(QuantityInfo quantityInfo, TUnit value, string pluralName, BaseUnits baseUnits, + // ConversionExpression conversionFromBase, + // ConversionExpression conversionToBase) + // : base(quantityInfo, value, pluralName, baseUnits, conversionFromBase, conversionToBase) + // { + // } + // + // /// + // public UnitInfo(QuantityInfo quantityInfo, TUnit value, string singularName, string pluralName, BaseUnits baseUnits, + // ConversionExpression conversionFromBase, + // ConversionExpression conversionToBase) + // : base(quantityInfo, value, singularName, pluralName, baseUnits, conversionFromBase, conversionToBase) + // { + // } + + /// + internal UnitInfo(QuantityInfo quantityInfo, IUnitDefinition unitDefinition) + : base(quantityInfo, unitDefinition) + { + } + + /// + public override TQuantity From(QuantityValue value) + { + return QuantityInfo.From(value, Value); } } diff --git a/UnitsNet/UnitMath.cs b/UnitsNet/UnitMath.cs index e68099184f..055bdcf1b1 100644 --- a/UnitsNet/UnitMath.cs +++ b/UnitsNet/UnitMath.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Numerics; namespace UnitsNet { @@ -9,56 +10,30 @@ namespace UnitsNet /// public static class UnitMath { - /// Returns the absolute value of a . - /// - /// A quantity with a value that is greater than or equal to , - /// but less than or equal to . - /// - /// A quantity with a value, such that 0 ≤ value ≤ . - public static TQuantity Abs(this TQuantity value) where TQuantity : IQuantity - { - return value.Value >= 0 ? value : (TQuantity) Quantity.From(-value.Value, value.Unit); - } - - /// Computes the sum of a sequence of values. - /// A sequence of values to calculate the sum of. - /// The desired unit type for the resulting quantity - /// The sum of the values in the sequence, represented in the specified unit type. - /// - /// source is null. - /// - /// - /// source contains quantity types different from . - /// - public static TQuantity Sum(this IEnumerable source, TUnitType unitType) - where TUnitType : struct, Enum - where TQuantity : IQuantity - { - return (TQuantity) Quantity.From(source.Sum(x => x.As(unitType)), unitType); - } - /// - /// Computes the sum of the sequence of values that are obtained by invoking a - /// transform function on each element of the input sequence. + /// Returns the absolute value of the specified quantity. /// - /// A sequence of values that are used to calculate a sum. - /// A transform function to apply to each element. - /// The desired unit type for the resulting quantity - /// The type of the elements of source. - /// The type of quantity that is produced by this operation. - /// The type of unit enum. - /// The sum of the projected values, represented in the specified unit type. - /// - /// source or selector is null. - /// - /// - /// source contains quantity types different from . + /// + /// The type of the quantity, which must implement . + /// + /// + /// The quantity whose absolute value is to be calculated. + /// + /// + /// A quantity of type representing the absolute value of the input quantity. + /// + /// + /// Thrown if the input is null. /// - public static TQuantity Sum(this IEnumerable source, Func selector, TUnitType unitType) - where TUnitType : struct, Enum - where TQuantity : IQuantity + public static TQuantity Abs(this TQuantity value) where TQuantity : IQuantity { - return source.Select(selector).Sum(unitType); + // TODO see about constraining to IQuantityInstance +// #if NET +// return TQuantity.Create(QuantityValue.Abs(value.Value), value.UnitKey); +// #else +// return value.QuantityInfo.Create(QuantityValue.Abs(value.Value), value.UnitKey); +// #endif + return QuantityValue.IsNegative(value.Value) ? (TQuantity)value.QuantityInfo.From(-value.Value, value.UnitKey) : value; } /// Returns the smaller of two values. @@ -66,7 +41,8 @@ public static TQuantity Sum(this IEnumerableThe first of two values to compare. /// The second of two values to compare. /// Parameter or , whichever is smaller. - public static TQuantity Min(TQuantity val1, TQuantity val2) where TQuantity : IComparable, IQuantity + public static TQuantity Min(TQuantity val1, TQuantity val2) + where TQuantity : IQuantity, IComparable { return val1.CompareTo(val2) == 1 ? val2 : val1; } @@ -82,11 +58,12 @@ public static TQuantity Min(TQuantity val1, TQuantity val2) where TQu /// /// source contains quantity types different from . /// + [Obsolete("Duplicate of System.Linq.Min")] public static TQuantity Min(this IEnumerable source, TUnitType unitType) where TUnitType : struct, Enum where TQuantity : IQuantity { - return (TQuantity) Quantity.From(source.Min(x => x.As(unitType)), unitType); + return (TQuantity) Quantity.From(source.Min(x => x.As(unitType)), UnitKey.ForUnit(unitType)); } /// @@ -107,9 +84,10 @@ public static TQuantity Min(this IEnumerable so /// /// source contains quantity types different from . /// + [Obsolete("Duplicate of System.Linq.Min")] public static TQuantity Min(this IEnumerable source, Func selector, TUnitType unitType) - where TUnitType : struct, Enum where TQuantity : IQuantity + where TUnitType : struct, Enum { return source.Select(selector).Min(unitType); } @@ -119,7 +97,8 @@ public static TQuantity Min(this IEnumerableThe first of two values to compare. /// The second of two values to compare. /// Parameter or , whichever is larger. - public static TQuantity Max(TQuantity val1, TQuantity val2) where TQuantity : IComparable, IQuantity + public static TQuantity Max(TQuantity val1, TQuantity val2) + where TQuantity : IQuantity, IComparable { return val1.CompareTo(val2) == -1 ? val2 : val1; } @@ -135,11 +114,12 @@ public static TQuantity Max(TQuantity val1, TQuantity val2) where TQu /// /// source contains quantity types different from . /// + [Obsolete("Duplicate of System.Linq.Max")] public static TQuantity Max(this IEnumerable source, TUnitType unitType) - where TUnitType : struct, Enum where TQuantity : IQuantity + where TUnitType : struct, Enum { - return (TQuantity) Quantity.From(source.Max(x => x.As(unitType)), unitType); + return (TQuantity) Quantity.From(source.Max(x => x.As(unitType)), UnitKey.ForUnit(unitType)); } /// @@ -160,56 +140,14 @@ public static TQuantity Max(this IEnumerable so /// /// source contains quantity types different from . /// + [Obsolete("Duplicate of System.Linq.Max")] public static TQuantity Max(this IEnumerable source, Func selector, TUnitType unitType) - where TUnitType : struct, Enum where TQuantity : IQuantity - { - return source.Select(selector).Max(unitType); - } - - /// Computes the average of a sequence of values. - /// A sequence of values to calculate the average of. - /// The desired unit type for the resulting quantity - /// The average of the values in the sequence, represented in the specified unit type. - /// - /// source is null. - /// - /// source contains no elements. - /// - /// source contains quantity types different from . - /// - public static TQuantity Average(this IEnumerable source, TUnitType unitType) where TUnitType : struct, Enum - where TQuantity : IQuantity { - return (TQuantity) Quantity.From(source.Average(x => x.As(unitType)), unitType); - } - - /// - /// Computes the average of the sequence of values that are obtained by invoking - /// a transform function on each element of the input sequence. - /// - /// A sequence of values that are used to calculate an average. - /// A transform function to apply to each element. - /// The desired unit type for the resulting quantity - /// The type of the elements of source. - /// The type of quantity that is produced by this operation. - /// The type of unit enum. - /// The average of the projected values, represented in the specified unit type. - /// - /// source or selector is null. - /// - /// source contains no elements. - /// - /// source contains quantity types different from . - /// - public static TQuantity Average(this IEnumerable source, Func selector, TUnitType unitType) - where TUnitType : struct, Enum - where TQuantity : IQuantity - { - return source.Select(selector).Average(unitType); + return source.Select(selector).Max(unitType); } - + /// Returns clamped to the inclusive range of and . /// The value to be clamped. /// The lower bound of the result. @@ -228,10 +166,12 @@ public static TQuantity Average(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 : IQuantityInstance, 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 8c7d8299a7..1ee35d141a 100644 --- a/UnitsNet/UnitsNet.csproj +++ b/UnitsNet/UnitsNet.csproj @@ -1,8 +1,8 @@ - + UnitsNet - 6.0.0-pre014 + 6.0.0-pre016 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 @@ -56,4 +57,13 @@ + + + + + + + + + diff --git a/UnitsNet/UnitsNet.csproj.DotSettings b/UnitsNet/UnitsNet.csproj.DotSettings index a60c20895b..f894c0387c 100644 --- a/UnitsNet/UnitsNet.csproj.DotSettings +++ b/UnitsNet/UnitsNet.csproj.DotSettings @@ -1,4 +1,15 @@  True True - True \ No newline at end of file + True + True + True + True + True + True + True + True + True + True + True + True \ No newline at end of file